db.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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.ext.declarative import declarative_base
  9. from sqlalchemy.orm import sessionmaker, scoped_session
  10. from sqlalchemy.sql.type_api import _T
  11. from config import SRC_LOG_LEVELS, DATA_DIR, DATABASE_URL, BACKEND_DIR
  12. log = logging.getLogger(__name__)
  13. log.setLevel(SRC_LOG_LEVELS["DB"])
  14. class JSONField(types.TypeDecorator):
  15. impl = types.Text
  16. cache_ok = True
  17. def process_bind_param(self, value: Optional[_T], dialect: Dialect) -> Any:
  18. return json.dumps(value)
  19. def process_result_value(self, value: Optional[_T], dialect: Dialect) -> Any:
  20. if value is not None:
  21. return json.loads(value)
  22. def copy(self, **kw: Any) -> Self:
  23. return JSONField(self.impl.length)
  24. def db_value(self, value):
  25. return json.dumps(value)
  26. def python_value(self, value):
  27. if value is not None:
  28. return json.loads(value)
  29. # Check if the file exists
  30. if os.path.exists(f"{DATA_DIR}/ollama.db"):
  31. # Rename the file
  32. os.rename(f"{DATA_DIR}/ollama.db", f"{DATA_DIR}/webui.db")
  33. log.info("Database migrated from Ollama-WebUI successfully.")
  34. else:
  35. pass
  36. SQLALCHEMY_DATABASE_URL = DATABASE_URL
  37. if "sqlite" in SQLALCHEMY_DATABASE_URL:
  38. engine = create_engine(
  39. SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
  40. )
  41. else:
  42. engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
  43. SessionLocal = sessionmaker(
  44. autocommit=False, autoflush=False, bind=engine, expire_on_commit=False
  45. )
  46. Base = declarative_base()
  47. Session = scoped_session(SessionLocal)
  48. from contextlib import contextmanager
  49. # Dependency
  50. def get_session():
  51. db = SessionLocal()
  52. try:
  53. yield db
  54. finally:
  55. db.close()
  56. get_db = contextmanager(get_session)