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 17 kB

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