You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

db_manager.py 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import threading
  2. from datetime import datetime
  3. from typing import Optional
  4. from loguru import logger
  5. from sqlalchemy import exc, text, func
  6. from sqlmodel import Session, SQLModel, and_, create_engine, select
  7. from .schema_manager import SchemaManager
  8. from ..datamodel import (
  9. Response,
  10. LinkTypes
  11. )
  12. # from .dbutils import init_db_samples
  13. class DatabaseManager:
  14. """A class to manage database operations"""
  15. _init_lock = threading.Lock()
  16. def __init__(self, engine_uri: str, auto_upgrade: bool = True):
  17. connection_args = {
  18. "check_same_thread": True} if "sqlite" in engine_uri else {}
  19. self.engine = create_engine(engine_uri, connect_args=connection_args)
  20. self.schema_manager = SchemaManager(
  21. engine=self.engine,
  22. auto_upgrade=auto_upgrade,
  23. )
  24. # Check and upgrade on startup
  25. upgraded, status = self.schema_manager.check_and_upgrade()
  26. if upgraded:
  27. logger.info("Database schema was upgraded automatically")
  28. else:
  29. logger.info(f"Schema status: {status}")
  30. def reset_db(self, recreate_tables: bool = True):
  31. """
  32. Reset the database by dropping all tables and optionally recreating them.
  33. Args:
  34. recreate_tables (bool): If True, recreates the tables after dropping them.
  35. Set to False if you want to call create_db_and_tables() separately.
  36. """
  37. if not self._init_lock.acquire(blocking=False):
  38. logger.warning("Database reset already in progress")
  39. return Response(
  40. message="Database reset already in progress",
  41. status=False,
  42. data=None
  43. )
  44. try:
  45. # Dispose existing connections
  46. self.engine.dispose()
  47. with Session(self.engine) as session:
  48. try:
  49. # Disable foreign key checks for SQLite
  50. if 'sqlite' in str(self.engine.url):
  51. session.exec(text('PRAGMA foreign_keys=OFF'))
  52. # Drop all tables
  53. SQLModel.metadata.drop_all(self.engine)
  54. logger.info("All tables dropped successfully")
  55. # Re-enable foreign key checks for SQLite
  56. if 'sqlite' in str(self.engine.url):
  57. session.exec(text('PRAGMA foreign_keys=ON'))
  58. session.commit()
  59. except Exception as e:
  60. session.rollback()
  61. raise e
  62. finally:
  63. session.close()
  64. self._init_lock.release()
  65. if recreate_tables:
  66. logger.info("Recreating tables...")
  67. self.create_db_and_tables()
  68. return Response(
  69. message="Database reset successfully" if recreate_tables else "Database tables dropped successfully",
  70. status=True,
  71. data=None
  72. )
  73. except Exception as e:
  74. error_msg = f"Error while resetting database: {str(e)}"
  75. logger.error(error_msg)
  76. return Response(
  77. message=error_msg,
  78. status=False,
  79. data=None
  80. )
  81. finally:
  82. if self._init_lock.locked():
  83. self._init_lock.release()
  84. logger.info("Database reset lock released")
  85. def create_db_and_tables(self):
  86. """Create a new database and tables"""
  87. with self._init_lock:
  88. try:
  89. SQLModel.metadata.create_all(self.engine)
  90. logger.info("Database tables created successfully")
  91. try:
  92. # init_db_samples(self)
  93. pass
  94. except Exception as e:
  95. logger.info(
  96. "Error while initializing database samples: " + str(e))
  97. except Exception as e:
  98. logger.info("Error while creating database tables:" + str(e))
  99. def upsert(self, model: SQLModel, return_json: bool = True):
  100. """Create or update an entity
  101. Args:
  102. model (SQLModel): The model instance to create or update
  103. return_json (bool, optional): If True, returns the model as a dictionary.
  104. If False, returns the SQLModel instance. Defaults to True.
  105. Returns:
  106. Response: Contains status, message and data (either dict or SQLModel based on return_json)
  107. """
  108. status = True
  109. model_class = type(model)
  110. existing_model = None
  111. with Session(self.engine) as session:
  112. try:
  113. existing_model = session.exec(
  114. select(model_class).where(model_class.id == model.id)).first()
  115. if existing_model:
  116. model.updated_at = datetime.now()
  117. for key, value in model.model_dump().items():
  118. setattr(existing_model, key, value)
  119. model = existing_model # Use the updated existing model
  120. session.add(model)
  121. else:
  122. session.add(model)
  123. session.commit()
  124. session.refresh(model)
  125. except Exception as e:
  126. session.rollback()
  127. logger.error("Error while updating/creating " +
  128. str(model_class.__name__) + ": " + str(e))
  129. status = False
  130. return Response(
  131. message=(
  132. f"{model_class.__name__} Updated Successfully"
  133. if existing_model
  134. else f"{model_class.__name__} Created Successfully"
  135. ),
  136. status=status,
  137. data=model.model_dump() if return_json else model,
  138. )
  139. def _model_to_dict(self, model_obj):
  140. return {col.name: getattr(model_obj, col.name) for col in model_obj.__table__.columns}
  141. def get(
  142. self,
  143. model_class: SQLModel,
  144. filters: dict = None,
  145. return_json: bool = False,
  146. order: str = "desc",
  147. ):
  148. """List entities"""
  149. with Session(self.engine) as session:
  150. result = []
  151. status = True
  152. status_message = ""
  153. try:
  154. statement = select(model_class)
  155. if filters:
  156. conditions = [getattr(model_class, col) ==
  157. value for col, value in filters.items()]
  158. statement = statement.where(and_(*conditions))
  159. if hasattr(model_class, "created_at") and order:
  160. order_by_clause = getattr(
  161. model_class.created_at, order)() # Dynamically apply asc/desc
  162. statement = statement.order_by(order_by_clause)
  163. items = session.exec(statement).all()
  164. result = [self._model_to_dict(
  165. item) if return_json else item for item in items]
  166. status_message = f"{model_class.__name__} Retrieved Successfully"
  167. except Exception as e:
  168. session.rollback()
  169. status = False
  170. status_message = f"Error while fetching {model_class.__name__}"
  171. logger.error("Error while getting items: " +
  172. str(model_class.__name__) + " " + str(e))
  173. return Response(message=status_message, status=status, data=result)
  174. def delete(self, model_class: SQLModel, filters: dict = None):
  175. """Delete an entity"""
  176. status_message = ""
  177. status = True
  178. with Session(self.engine) as session:
  179. try:
  180. statement = select(model_class)
  181. if filters:
  182. conditions = [
  183. getattr(model_class, col) == value for col, value in filters.items()]
  184. statement = statement.where(and_(*conditions))
  185. rows = session.exec(statement).all()
  186. if rows:
  187. for row in rows:
  188. session.delete(row)
  189. session.commit()
  190. status_message = f"{model_class.__name__} Deleted Successfully"
  191. else:
  192. status_message = "Row not found"
  193. logger.info(f"Row with filters {filters} not found")
  194. except exc.IntegrityError as e:
  195. session.rollback()
  196. status = False
  197. status_message = f"Integrity error: The {model_class.__name__} is linked to another entity and cannot be deleted. {e}"
  198. # Log the specific integrity error
  199. logger.error(status_message)
  200. except Exception as e:
  201. session.rollback()
  202. status = False
  203. status_message = f"Error while deleting: {e}"
  204. logger.error(status_message)
  205. return Response(message=status_message, status=status, data=None)
  206. def link(
  207. self,
  208. link_type: LinkTypes,
  209. primary_id: int,
  210. secondary_id: int,
  211. sequence: Optional[int] = None,
  212. ):
  213. """Link two entities with automatic sequence handling."""
  214. with Session(self.engine) as session:
  215. try:
  216. # Get classes from LinkTypes
  217. primary_class = link_type.primary_class
  218. secondary_class = link_type.secondary_class
  219. link_table = link_type.link_table
  220. # Get entities
  221. primary_entity = session.get(primary_class, primary_id)
  222. secondary_entity = session.get(secondary_class, secondary_id)
  223. if not primary_entity or not secondary_entity:
  224. return Response(message="One or both entities do not exist", status=False)
  225. # Get field names
  226. primary_id_field = f"{primary_class.__name__.lower()}_id"
  227. secondary_id_field = f"{secondary_class.__name__.lower()}_id"
  228. # Check for existing link
  229. existing_link = session.exec(
  230. select(link_table).where(
  231. and_(
  232. getattr(link_table, primary_id_field) == primary_id,
  233. getattr(
  234. link_table, secondary_id_field) == secondary_id
  235. )
  236. )
  237. ).first()
  238. if existing_link:
  239. return Response(message="Link already exists", status=False)
  240. # Get the next sequence number if not provided
  241. if sequence is None:
  242. max_seq_result = session.exec(
  243. select(func.max(link_table.sequence)).where(
  244. getattr(link_table, primary_id_field) == primary_id
  245. )
  246. ).first()
  247. sequence = 0 if max_seq_result is None else max_seq_result + 1
  248. # Create new link
  249. new_link = link_table(**{
  250. primary_id_field: primary_id,
  251. secondary_id_field: secondary_id,
  252. 'sequence': sequence
  253. })
  254. session.add(new_link)
  255. session.commit()
  256. return Response(
  257. message=f"Entities linked successfully with sequence {sequence}",
  258. status=True
  259. )
  260. except Exception as e:
  261. session.rollback()
  262. return Response(message=f"Error linking entities: {str(e)}", status=False)
  263. def unlink(
  264. self,
  265. link_type: LinkTypes,
  266. primary_id: int,
  267. secondary_id: int,
  268. sequence: Optional[int] = None
  269. ):
  270. """Unlink two entities and reorder sequences if needed."""
  271. with Session(self.engine) as session:
  272. try:
  273. # Get classes from LinkTypes
  274. primary_class = link_type.primary_class
  275. secondary_class = link_type.secondary_class
  276. link_table = link_type.link_table
  277. # Get field names
  278. primary_id_field = f"{primary_class.__name__.lower()}_id"
  279. secondary_id_field = f"{secondary_class.__name__.lower()}_id"
  280. # Find existing link
  281. statement = select(link_table).where(
  282. and_(
  283. getattr(link_table, primary_id_field) == primary_id,
  284. getattr(link_table, secondary_id_field) == secondary_id
  285. )
  286. )
  287. if sequence is not None:
  288. statement = statement.where(
  289. link_table.sequence == sequence)
  290. existing_link = session.exec(statement).first()
  291. if not existing_link:
  292. return Response(message="Link does not exist", status=False)
  293. deleted_sequence = existing_link.sequence
  294. session.delete(existing_link)
  295. # Reorder sequences for remaining links
  296. remaining_links = session.exec(
  297. select(link_table)
  298. .where(getattr(link_table, primary_id_field) == primary_id)
  299. .where(link_table.sequence > deleted_sequence)
  300. .order_by(link_table.sequence)
  301. ).all()
  302. # Decrease sequence numbers to fill the gap
  303. for link in remaining_links:
  304. link.sequence -= 1
  305. session.commit()
  306. return Response(
  307. message="Entities unlinked successfully and sequences reordered",
  308. status=True
  309. )
  310. except Exception as e:
  311. session.rollback()
  312. return Response(message=f"Error unlinking entities: {str(e)}", status=False)
  313. def get_linked_entities(
  314. self,
  315. link_type: LinkTypes,
  316. primary_id: int,
  317. return_json: bool = False,
  318. ):
  319. """Get linked entities based on link type and primary ID, ordered by sequence."""
  320. with Session(self.engine) as session:
  321. try:
  322. # Get classes from LinkTypes
  323. primary_class = link_type.primary_class
  324. secondary_class = link_type.secondary_class
  325. link_table = link_type.link_table
  326. # Get field names
  327. primary_id_field = f"{primary_class.__name__.lower()}_id"
  328. secondary_id_field = f"{secondary_class.__name__.lower()}_id"
  329. # Query both link and entity, ordered by sequence
  330. items = session.exec(
  331. select(secondary_class)
  332. .join(link_table, getattr(link_table, secondary_id_field) == secondary_class.id)
  333. .where(getattr(link_table, primary_id_field) == primary_id)
  334. .order_by(link_table.sequence)
  335. ).all()
  336. result = [
  337. item.model_dump() if return_json else item for item in items]
  338. return Response(
  339. message="Linked entities retrieved successfully",
  340. status=True,
  341. data=result
  342. )
  343. except Exception as e:
  344. logger.error(f"Error getting linked entities: {str(e)}")
  345. return Response(
  346. message=f"Error getting linked entities: {str(e)}",
  347. status=False,
  348. data=[]
  349. )
  350. # Add new close method
  351. async def close(self):
  352. """Close database connections and cleanup resources"""
  353. logger.info("Closing database connections...")
  354. try:
  355. # Dispose of the SQLAlchemy engine
  356. self.engine.dispose()
  357. logger.info("Database connections closed successfully")
  358. except Exception as e:
  359. logger.error(f"Error closing database connections: {str(e)}")
  360. raise