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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. import threading
  2. from datetime import datetime
  3. from pathlib import Path
  4. from typing import Optional, Union
  5. from loguru import logger
  6. from sqlalchemy import exc, inspect, text
  7. from sqlmodel import Session, SQLModel, and_, create_engine, select
  8. from ..datamodel import Response, Team
  9. from ..teammanager import TeamManager
  10. from .schema_manager import SchemaManager
  11. class DatabaseManager:
  12. _init_lock = threading.Lock()
  13. def __init__(self, engine_uri: str, base_dir: Optional[Path] = None):
  14. """
  15. Initialize DatabaseManager with database connection settings.
  16. Does not perform any database operations.
  17. Args:
  18. engine_uri: Database connection URI (e.g. sqlite:///db.sqlite3)
  19. base_dir: Base directory for migration files. If None, uses current directory
  20. """
  21. connection_args = {"check_same_thread": True} if "sqlite" in engine_uri else {}
  22. self.engine = create_engine(engine_uri, connect_args=connection_args)
  23. self.schema_manager = SchemaManager(
  24. engine=self.engine,
  25. base_dir=base_dir,
  26. )
  27. def initialize_database(self, auto_upgrade: bool = False, force_init_alembic: bool = True) -> Response:
  28. """
  29. Initialize database and migrations in the correct order.
  30. Args:
  31. auto_upgrade: If True, automatically generate and apply migrations for schema changes
  32. force_init_alembic: If True, reinitialize alembic configuration even if it exists
  33. """
  34. if not self._init_lock.acquire(blocking=False):
  35. return Response(message="Database initialization already in progress", status=False)
  36. try:
  37. inspector = inspect(self.engine)
  38. tables_exist = inspector.get_table_names()
  39. if not tables_exist:
  40. # Fresh install - create tables and initialize migrations
  41. logger.info("Creating database tables...")
  42. SQLModel.metadata.create_all(self.engine)
  43. if self.schema_manager.initialize_migrations(force=force_init_alembic):
  44. return Response(message="Database initialized successfully", status=True)
  45. return Response(message="Failed to initialize migrations", status=False)
  46. # Handle existing database
  47. if auto_upgrade:
  48. logger.info("Checking database schema...")
  49. if self.schema_manager.ensure_schema_up_to_date(): # <-- Use this instead
  50. return Response(message="Database schema is up to date", status=True)
  51. return Response(message="Database upgrade failed", status=False)
  52. return Response(message="Database is ready", status=True)
  53. except Exception as e:
  54. error_msg = f"Database initialization failed: {str(e)}"
  55. logger.error(error_msg)
  56. return Response(message=error_msg, status=False)
  57. finally:
  58. self._init_lock.release()
  59. def reset_db(self, recreate_tables: bool = True):
  60. """
  61. Reset the database by dropping all tables and optionally recreating them.
  62. Args:
  63. recreate_tables (bool): If True, recreates the tables after dropping them.
  64. Set to False if you want to call create_db_and_tables() separately.
  65. """
  66. if not self._init_lock.acquire(blocking=False):
  67. logger.warning("Database reset already in progress")
  68. return Response(message="Database reset already in progress", status=False, data=None)
  69. try:
  70. # Dispose existing connections
  71. self.engine.dispose()
  72. with Session(self.engine) as session:
  73. try:
  74. # Disable foreign key checks for SQLite
  75. if "sqlite" in str(self.engine.url):
  76. session.exec(text("PRAGMA foreign_keys=OFF"))
  77. # Drop all tables
  78. SQLModel.metadata.drop_all(self.engine)
  79. logger.info("All tables dropped successfully")
  80. # Re-enable foreign key checks for SQLite
  81. if "sqlite" in str(self.engine.url):
  82. session.exec(text("PRAGMA foreign_keys=ON"))
  83. session.commit()
  84. except Exception as e:
  85. session.rollback()
  86. raise e
  87. finally:
  88. session.close()
  89. self._init_lock.release()
  90. if recreate_tables:
  91. logger.info("Recreating tables...")
  92. self.initialize_database(auto_upgrade=False, force_init_alembic=True)
  93. return Response(
  94. message="Database reset successfully" if recreate_tables else "Database tables dropped successfully",
  95. status=True,
  96. data=None,
  97. )
  98. except Exception as e:
  99. error_msg = f"Error while resetting database: {str(e)}"
  100. logger.error(error_msg)
  101. return Response(message=error_msg, status=False, data=None)
  102. finally:
  103. if self._init_lock.locked():
  104. self._init_lock.release()
  105. logger.info("Database reset lock released")
  106. def upsert(self, model: SQLModel, return_json: bool = True):
  107. """Create or update an entity
  108. Args:
  109. model (SQLModel): The model instance to create or update
  110. return_json (bool, optional): If True, returns the model as a dictionary.
  111. If False, returns the SQLModel instance. Defaults to True.
  112. Returns:
  113. Response: Contains status, message and data (either dict or SQLModel based on return_json)
  114. """
  115. status = True
  116. model_class = type(model)
  117. existing_model = None
  118. with Session(self.engine) as session:
  119. try:
  120. existing_model = session.exec(select(model_class).where(model_class.id == model.id)).first()
  121. if existing_model:
  122. model.updated_at = datetime.now()
  123. for key, value in model.model_dump().items():
  124. setattr(existing_model, key, value)
  125. model = existing_model # Use the updated existing model
  126. session.add(model)
  127. else:
  128. session.add(model)
  129. session.commit()
  130. session.refresh(model)
  131. except Exception as e:
  132. session.rollback()
  133. logger.error("Error while updating/creating " + str(model_class.__name__) + ": " + str(e))
  134. status = False
  135. return Response(
  136. message=(
  137. f"{model_class.__name__} Updated Successfully"
  138. if existing_model
  139. else f"{model_class.__name__} Created Successfully"
  140. ),
  141. status=status,
  142. data=model.model_dump() if return_json else model,
  143. )
  144. def _model_to_dict(self, model_obj):
  145. return {col.name: getattr(model_obj, col.name) for col in model_obj.__table__.columns}
  146. def get(
  147. self,
  148. model_class: SQLModel,
  149. filters: dict = None,
  150. return_json: bool = False,
  151. order: str = "desc",
  152. ):
  153. """List entities"""
  154. with Session(self.engine) as session:
  155. result = []
  156. status = True
  157. status_message = ""
  158. try:
  159. statement = select(model_class)
  160. if filters:
  161. conditions = [getattr(model_class, col) == value for col, value in filters.items()]
  162. statement = statement.where(and_(*conditions))
  163. if hasattr(model_class, "created_at") and order:
  164. order_by_clause = getattr(model_class.created_at, order)() # Dynamically apply asc/desc
  165. statement = statement.order_by(order_by_clause)
  166. items = session.exec(statement).all()
  167. result = [self._model_to_dict(item) if return_json else item for item in items]
  168. status_message = f"{model_class.__name__} Retrieved Successfully"
  169. except Exception as e:
  170. session.rollback()
  171. status = False
  172. status_message = f"Error while fetching {model_class.__name__}"
  173. logger.error("Error while getting items: " + str(model_class.__name__) + " " + str(e))
  174. return Response(message=status_message, status=status, data=result)
  175. def delete(self, model_class: SQLModel, filters: dict = None):
  176. """Delete an entity"""
  177. status_message = ""
  178. status = True
  179. with Session(self.engine) as session:
  180. try:
  181. statement = select(model_class)
  182. if filters:
  183. conditions = [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. async def import_team(
  207. self, team_config: Union[str, Path, dict], user_id: str, check_exists: bool = False
  208. ) -> Response:
  209. try:
  210. # Load config if path provided
  211. if isinstance(team_config, (str, Path)):
  212. config = await TeamManager.load_from_file(team_config)
  213. else:
  214. config = team_config
  215. # Check existence if requested
  216. if check_exists:
  217. existing = await self._check_team_exists(config, user_id)
  218. if existing:
  219. return Response(
  220. message="Identical team configuration already exists", status=True, data={"id": existing.id}
  221. )
  222. # Store in database
  223. team_db = Team(user_id=user_id, config=config)
  224. result = self.upsert(team_db)
  225. return result
  226. except Exception as e:
  227. logger.error(f"Failed to import team: {str(e)}")
  228. return Response(message=str(e), status=False)
  229. async def import_teams_from_directory(
  230. self, directory: Union[str, Path], user_id: str, check_exists: bool = False
  231. ) -> Response:
  232. """
  233. Import all team configurations from a directory.
  234. Args:
  235. directory: Path to directory containing team configs
  236. user_id: User ID to associate with imported teams
  237. check_exists: Whether to check for existing teams
  238. Returns:
  239. Response containing import results for all files
  240. """
  241. try:
  242. # Load all configs from directory
  243. configs = await TeamManager.load_from_directory(directory)
  244. results = []
  245. for config in configs:
  246. try:
  247. result = await self.import_team(team_config=config, user_id=user_id, check_exists=check_exists)
  248. # Add result info
  249. results.append(
  250. {
  251. "status": result.status,
  252. "message": result.message,
  253. "id": result.data.get("id") if result.status else None,
  254. }
  255. )
  256. except Exception as e:
  257. logger.error(f"Failed to import team config: {str(e)}")
  258. results.append({"status": False, "message": str(e), "id": None})
  259. return Response(message="Directory import complete", status=True, data=results)
  260. except Exception as e:
  261. logger.error(f"Failed to import directory: {str(e)}")
  262. return Response(message=str(e), status=False)
  263. async def _check_team_exists(self, config: dict, user_id: str) -> Optional[Team]:
  264. """Check if identical team config already exists"""
  265. teams = self.get(Team, {"user_id": user_id}).data
  266. for team in teams:
  267. if team.config == config:
  268. return team
  269. return None
  270. async def close(self):
  271. """Close database connections and cleanup resources"""
  272. logger.info("Closing database connections...")
  273. try:
  274. # Dispose of the SQLAlchemy engine
  275. self.engine.dispose()
  276. logger.info("Database connections closed successfully")
  277. except Exception as e:
  278. logger.error(f"Error closing database connections: {str(e)}")
  279. raise