db.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import os
  2. import logging
  3. import json
  4. from contextlib import contextmanager
  5. from typing import Optional, Any
  6. from typing_extensions import Self
  7. from sqlalchemy import create_engine, types, Dialect
  8. from sqlalchemy.sql.type_api import _T
  9. from sqlalchemy.ext.declarative import declarative_base
  10. from sqlalchemy.orm import sessionmaker, scoped_session
  11. from peewee_migrate import Router
  12. from apps.webui.internal.wrappers import register_connection
  13. from env import SRC_LOG_LEVELS, BACKEND_DIR, DATABASE_URL
  14. log = logging.getLogger(__name__)
  15. log.setLevel(SRC_LOG_LEVELS["DB"])
  16. class JSONField(types.TypeDecorator):
  17. impl = types.Text
  18. cache_ok = True
  19. def process_bind_param(self, value: Optional[_T], dialect: Dialect) -> Any:
  20. return json.dumps(value)
  21. def process_result_value(self, value: Optional[_T], dialect: Dialect) -> Any:
  22. if value is not None:
  23. return json.loads(value)
  24. def copy(self, **kw: Any) -> Self:
  25. return JSONField(self.impl.length)
  26. def db_value(self, value):
  27. return json.dumps(value)
  28. def python_value(self, value):
  29. if value is not None:
  30. return json.loads(value)
  31. # Workaround to handle the peewee migration
  32. # This is required to ensure the peewee migration is handled before the alembic migration
  33. def handle_peewee_migration(DATABASE_URL):
  34. # db = None
  35. try:
  36. # Replace the postgresql:// with postgres:// to handle the peewee migration
  37. db = register_connection(DATABASE_URL.replace("postgresql://", "postgres://"))
  38. migrate_dir = BACKEND_DIR / "apps" / "webui" / "internal" / "migrations"
  39. router = Router(db, logger=log, migrate_dir=migrate_dir)
  40. router.run()
  41. db.close()
  42. except Exception as e:
  43. log.error(f"Failed to initialize the database connection: {e}")
  44. raise
  45. finally:
  46. # Properly closing the database connection
  47. if db and not db.is_closed():
  48. db.close()
  49. # Assert if db connection has been closed
  50. assert db.is_closed(), "Database connection is still open."
  51. handle_peewee_migration(DATABASE_URL)
  52. SQLALCHEMY_DATABASE_URL = DATABASE_URL
  53. if "sqlite" in SQLALCHEMY_DATABASE_URL:
  54. engine = create_engine(
  55. SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
  56. )
  57. else:
  58. engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
  59. SessionLocal = sessionmaker(
  60. autocommit=False, autoflush=False, bind=engine, expire_on_commit=False
  61. )
  62. Base = declarative_base()
  63. Session = scoped_session(SessionLocal)
  64. def get_session():
  65. db = SessionLocal()
  66. try:
  67. yield db
  68. finally:
  69. db.close()
  70. get_db = contextmanager(get_session)