db.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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 (
  7. OPEN_WEBUI_DIR,
  8. DATABASE_URL,
  9. SRC_LOG_LEVELS,
  10. DATABASE_POOL_MAX_OVERFLOW,
  11. DATABASE_POOL_RECYCLE,
  12. DATABASE_POOL_SIZE,
  13. DATABASE_POOL_TIMEOUT,
  14. )
  15. from peewee_migrate import Router
  16. from sqlalchemy import Dialect, create_engine, types
  17. from sqlalchemy.ext.declarative import declarative_base
  18. from sqlalchemy.orm import scoped_session, sessionmaker
  19. from sqlalchemy.pool import QueuePool, NullPool
  20. from sqlalchemy.sql.type_api import _T
  21. from typing_extensions import Self
  22. log = logging.getLogger(__name__)
  23. log.setLevel(SRC_LOG_LEVELS["DB"])
  24. class JSONField(types.TypeDecorator):
  25. impl = types.Text
  26. cache_ok = True
  27. def process_bind_param(self, value: Optional[_T], dialect: Dialect) -> Any:
  28. return json.dumps(value)
  29. def process_result_value(self, value: Optional[_T], dialect: Dialect) -> Any:
  30. if value is not None:
  31. return json.loads(value)
  32. def copy(self, **kw: Any) -> Self:
  33. return JSONField(self.impl.length)
  34. def db_value(self, value):
  35. return json.dumps(value)
  36. def python_value(self, value):
  37. if value is not None:
  38. return json.loads(value)
  39. # Workaround to handle the peewee migration
  40. # This is required to ensure the peewee migration is handled before the alembic migration
  41. def handle_peewee_migration(DATABASE_URL):
  42. # db = None
  43. try:
  44. # Replace the postgresql:// with postgres:// to handle the peewee migration
  45. db = register_connection(DATABASE_URL.replace("postgresql://", "postgres://"))
  46. migrate_dir = OPEN_WEBUI_DIR / "apps" / "webui" / "internal" / "migrations"
  47. router = Router(db, logger=log, migrate_dir=migrate_dir)
  48. router.run()
  49. db.close()
  50. except Exception as e:
  51. log.error(f"Failed to initialize the database connection: {e}")
  52. raise
  53. finally:
  54. # Properly closing the database connection
  55. if db and not db.is_closed():
  56. db.close()
  57. # Assert if db connection has been closed
  58. assert db.is_closed(), "Database connection is still open."
  59. handle_peewee_migration(DATABASE_URL)
  60. SQLALCHEMY_DATABASE_URL = DATABASE_URL
  61. if "sqlite" in SQLALCHEMY_DATABASE_URL:
  62. engine = create_engine(
  63. SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
  64. )
  65. else:
  66. if DATABASE_POOL_SIZE > 0:
  67. engine = create_engine(
  68. SQLALCHEMY_DATABASE_URL,
  69. pool_size=DATABASE_POOL_SIZE,
  70. max_overflow=DATABASE_POOL_MAX_OVERFLOW,
  71. pool_timeout=DATABASE_POOL_TIMEOUT,
  72. pool_recycle=DATABASE_POOL_RECYCLE,
  73. pool_pre_ping=True,
  74. poolclass=QueuePool,
  75. )
  76. else:
  77. engine = create_engine(
  78. SQLALCHEMY_DATABASE_URL, pool_pre_ping=True, poolclass=NullPool
  79. )
  80. SessionLocal = sessionmaker(
  81. autocommit=False, autoflush=False, bind=engine, expire_on_commit=False
  82. )
  83. Base = declarative_base()
  84. Session = scoped_session(SessionLocal)
  85. def get_session():
  86. db = SessionLocal()
  87. try:
  88. yield db
  89. finally:
  90. db.close()
  91. get_db = contextmanager(get_session)