db.py 1.8 KB

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