db.py 2.9 KB

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