db.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import os
  2. import logging
  3. import json
  4. from contextlib import contextmanager
  5. from peewee_migrate import Router
  6. from apps.webui.internal.wrappers import register_connection
  7. from typing import Optional, Any
  8. from typing_extensions import Self
  9. from sqlalchemy import create_engine, types, Dialect
  10. from sqlalchemy.ext.declarative import declarative_base
  11. from sqlalchemy.orm import sessionmaker, scoped_session
  12. from sqlalchemy.sql.type_api import _T
  13. from config import SRC_LOG_LEVELS, DATA_DIR, DATABASE_URL, BACKEND_DIR
  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. # Check if the file exists
  32. if os.path.exists(f"{DATA_DIR}/ollama.db"):
  33. # Rename the file
  34. os.rename(f"{DATA_DIR}/ollama.db", f"{DATA_DIR}/webui.db")
  35. log.info("Database migrated from Ollama-WebUI successfully.")
  36. else:
  37. pass
  38. # Workaround to handle the peewee migration
  39. # This is required to ensure the peewee migration is handled before the alembic migration
  40. def handle_peewee_migration():
  41. try:
  42. db = register_connection(DATABASE_URL)
  43. migrate_dir = BACKEND_DIR / "apps" / "webui" / "internal" / "migrations"
  44. router = Router(db, logger=log, migrate_dir=migrate_dir)
  45. router.run()
  46. db.close()
  47. # check if db connection has been closed
  48. except Exception as e:
  49. log.error(f"Failed to initialize the database connection: {e}")
  50. raise
  51. finally:
  52. # Properly closing the database connection
  53. if db and not db.is_closed():
  54. db.close()
  55. # Assert if db connection has been closed
  56. assert db.is_closed(), "Database connection is still open."
  57. handle_peewee_migration()
  58. SQLALCHEMY_DATABASE_URL = DATABASE_URL
  59. if "sqlite" in SQLALCHEMY_DATABASE_URL:
  60. engine = create_engine(
  61. SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
  62. )
  63. else:
  64. engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
  65. SessionLocal = sessionmaker(
  66. autocommit=False, autoflush=False, bind=engine, expire_on_commit=False
  67. )
  68. Base = declarative_base()
  69. Session = scoped_session(SessionLocal)
  70. # Dependency
  71. def get_session():
  72. db = SessionLocal()
  73. try:
  74. yield db
  75. finally:
  76. db.close()
  77. get_db = contextmanager(get_session)