db.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import os
  2. import logging
  3. import json
  4. from peewee import *
  5. from peewee_migrate import Router
  6. from apps.webui.internal.wrappers import register_connection
  7. from config import SRC_LOG_LEVELS, DATA_DIR, DATABASE_URL, BACKEND_DIR
  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. # The `register_connection` function encapsulates the logic for setting up
  24. # the database connection based on the connection string, while `connect`
  25. # is a Peewee-specific method to manage the connection state and avoid errors
  26. # when a connection is already open.
  27. try:
  28. DB = register_connection(DATABASE_URL)
  29. log.info(f"Connected to a {DB.__class__.__name__} database.")
  30. except Exception as e:
  31. log.error(f"Failed to initialize the database connection: {e}")
  32. raise
  33. router = Router(
  34. DB,
  35. migrate_dir=BACKEND_DIR / "apps" / "webui" / "internal" / "migrations",
  36. logger=log,
  37. )
  38. router.run()
  39. try:
  40. DB.connect(reuse_if_open=True)
  41. except OperationalError as e:
  42. log.info(f"Failed to connect to database again due to: {e}")
  43. pass