db.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. @contextmanager
  48. def get_session():
  49. session = scoped_session(SessionLocal)
  50. try:
  51. yield session
  52. session.commit()
  53. except Exception as e:
  54. session.rollback()
  55. raise e