db.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import json
  2. import logging
  3. from contextlib import contextmanager
  4. from typing import Any, Optional
  5. from open_webui.apps.webui.internal.wrappers import register_connection
  6. from open_webui.env import OPEN_WEBUI_DIR, DATABASE_URL, SRC_LOG_LEVELS
  7. from peewee_migrate import Router
  8. from sqlalchemy import Dialect, create_engine, types
  9. from sqlalchemy.ext.declarative import declarative_base
  10. from sqlalchemy.orm import scoped_session, sessionmaker
  11. from sqlalchemy.sql.type_api import _T
  12. from typing_extensions import Self
  13. log = logging.getLogger(__name__)
  14. log.setLevel(SRC_LOG_LEVELS["DB"])
  15. class JSONField(types.TypeDecorator):
  16. impl = types.Text
  17. cache_ok = True
  18. def process_bind_param(self, value: Optional[_T], dialect: Dialect) -> Any:
  19. return json.dumps(value)
  20. def process_result_value(self, value: Optional[_T], dialect: Dialect) -> Any:
  21. if value is not None:
  22. return json.loads(value)
  23. def copy(self, **kw: Any) -> Self:
  24. return JSONField(self.impl.length)
  25. def db_value(self, value):
  26. return json.dumps(value)
  27. def python_value(self, value):
  28. if value is not None:
  29. return json.loads(value)
  30. # Workaround to handle the peewee migration
  31. # This is required to ensure the peewee migration is handled before the alembic migration
  32. def handle_peewee_migration(DATABASE_URL):
  33. # db = None
  34. try:
  35. # Replace the postgresql:// with postgres:// to handle the peewee migration
  36. db = register_connection(DATABASE_URL.replace("postgresql://", "postgres://"))
  37. migrate_dir = OPEN_WEBUI_DIR / "apps" / "webui" / "internal" / "migrations"
  38. router = Router(db, logger=log, migrate_dir=migrate_dir)
  39. router.run()
  40. db.close()
  41. except Exception as e:
  42. log.error(f"Failed to initialize the database connection: {e}")
  43. raise
  44. finally:
  45. # Properly closing the database connection
  46. if db and not db.is_closed():
  47. db.close()
  48. # Assert if db connection has been closed
  49. assert db.is_closed(), "Database connection is still open."
  50. handle_peewee_migration(DATABASE_URL)
  51. SQLALCHEMY_DATABASE_URL = DATABASE_URL
  52. if "sqlite" in SQLALCHEMY_DATABASE_URL:
  53. engine = create_engine(
  54. SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
  55. )
  56. else:
  57. engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
  58. SessionLocal = sessionmaker(
  59. autocommit=False, autoflush=False, bind=engine, expire_on_commit=False
  60. )
  61. Base = declarative_base()
  62. Session = scoped_session(SessionLocal)
  63. def get_session():
  64. db = SessionLocal()
  65. try:
  66. yield db
  67. finally:
  68. db.close()
  69. get_db = contextmanager(get_session)