wrappers.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import logging
  2. from contextvars import ContextVar
  3. from open_webui.env import SRC_LOG_LEVELS
  4. from peewee import *
  5. from peewee import InterfaceError as PeeWeeInterfaceError
  6. from peewee import PostgresqlDatabase
  7. from playhouse.db_url import connect, parse
  8. from playhouse.shortcuts import ReconnectMixin
  9. log = logging.getLogger(__name__)
  10. log.setLevel(SRC_LOG_LEVELS["DB"])
  11. db_state_default = {"closed": None, "conn": None, "ctx": None, "transactions": None}
  12. db_state = ContextVar("db_state", default=db_state_default.copy())
  13. class PeeweeConnectionState(object):
  14. def __init__(self, **kwargs):
  15. super().__setattr__("_state", db_state)
  16. super().__init__(**kwargs)
  17. def __setattr__(self, name, value):
  18. self._state.get()[name] = value
  19. def __getattr__(self, name):
  20. value = self._state.get()[name]
  21. return value
  22. class CustomReconnectMixin(ReconnectMixin):
  23. reconnect_errors = (
  24. # psycopg2
  25. (OperationalError, "termin"),
  26. (InterfaceError, "closed"),
  27. # peewee
  28. (PeeWeeInterfaceError, "closed"),
  29. )
  30. class ReconnectingPostgresqlDatabase(CustomReconnectMixin, PostgresqlDatabase):
  31. pass
  32. def register_connection(db_url):
  33. db = connect(db_url, unquote_password=True)
  34. if isinstance(db, PostgresqlDatabase):
  35. # Enable autoconnect for SQLite databases, managed by Peewee
  36. db.autoconnect = True
  37. db.reuse_if_open = True
  38. log.info("Connected to PostgreSQL database")
  39. # Get the connection details
  40. connection = parse(db_url, unquote_password=True)
  41. # Use our custom database class that supports reconnection
  42. db = ReconnectingPostgresqlDatabase(**connection)
  43. db.connect(reuse_if_open=True)
  44. elif isinstance(db, SqliteDatabase):
  45. # Enable autoconnect for SQLite databases, managed by Peewee
  46. db.autoconnect = True
  47. db.reuse_if_open = True
  48. log.info("Connected to SQLite database")
  49. else:
  50. raise ValueError("Unsupported database connection")
  51. return db