db.py 960 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import json
  2. from peewee import *
  3. from peewee_migrate import Router
  4. from playhouse.db_url import connect
  5. from config import SRC_LOG_LEVELS, DATA_DIR, DATABASE_URL, BACKEND_DIR
  6. import os
  7. import logging
  8. log = logging.getLogger(__name__)
  9. log.setLevel(SRC_LOG_LEVELS["DB"])
  10. class JSONField(TextField):
  11. def db_value(self, value):
  12. return json.dumps(value)
  13. def python_value(self, value):
  14. if value is not None:
  15. return json.loads(value)
  16. # Check if the file exists
  17. if os.path.exists(f"{DATA_DIR}/ollama.db"):
  18. # Rename the file
  19. os.rename(f"{DATA_DIR}/ollama.db", f"{DATA_DIR}/webui.db")
  20. log.info("Database migrated from Ollama-WebUI successfully.")
  21. else:
  22. pass
  23. DB = connect(DATABASE_URL)
  24. log.info(f"Connected to a {DB.__class__.__name__} database.")
  25. router = Router(
  26. DB,
  27. migrate_dir=BACKEND_DIR / "apps" / "webui" / "internal" / "migrations",
  28. logger=log,
  29. )
  30. router.run()
  31. DB.connect(reuse_if_open=True)