db.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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(DATABASE_URL):
  41. try:
  42. # Replace the postgresql:// with postgres:// and %40 with @ in the DATABASE_URL
  43. db = register_connection(
  44. DATABASE_URL.replace("postgresql://", "postgres://").replace("%40", "@")
  45. )
  46. migrate_dir = BACKEND_DIR / "apps" / "webui" / "internal" / "migrations"
  47. router = Router(db, logger=log, migrate_dir=migrate_dir)
  48. router.run()
  49. db.close()
  50. # check if db connection has been closed
  51. except Exception as e:
  52. log.error(f"Failed to initialize the database connection: {e}")
  53. raise
  54. finally:
  55. # Properly closing the database connection
  56. if db and not db.is_closed():
  57. db.close()
  58. # Assert if db connection has been closed
  59. assert db.is_closed(), "Database connection is still open."
  60. handle_peewee_migration(DATABASE_URL)
  61. SQLALCHEMY_DATABASE_URL = DATABASE_URL
  62. if "sqlite" in SQLALCHEMY_DATABASE_URL:
  63. engine = create_engine(
  64. SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
  65. )
  66. else:
  67. engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
  68. SessionLocal = sessionmaker(
  69. autocommit=False, autoflush=False, bind=engine, expire_on_commit=False
  70. )
  71. Base = declarative_base()
  72. Session = scoped_session(SessionLocal)
  73. # Dependency
  74. def get_session():
  75. db = SessionLocal()
  76. try:
  77. yield db
  78. finally:
  79. db.close()
  80. get_db = contextmanager(get_session)