Automated commit
This commit is contained in:
parent
161677e43b
commit
b33a2761a2
|
|
@ -1,19 +1,21 @@
|
||||||
import logging
|
import logging
|
||||||
from sqlalchemy import create_engine, text
|
from sqlalchemy import create_engine
|
||||||
from sqlalchemy.orm import DeclarativeBase, sessionmaker
|
from sqlalchemy.orm import DeclarativeBase, sessionmaker
|
||||||
|
|
||||||
from app.config import settings
|
from app.config import settings
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
engine = create_engine(
|
||||||
engine = create_engine(settings.database_url)
|
settings.database_url,
|
||||||
|
pool_pre_ping=True,
|
||||||
|
pool_size=5,
|
||||||
|
max_overflow=10,
|
||||||
|
pool_recycle=1800,
|
||||||
|
)
|
||||||
SessionLocal = sessionmaker(bind=engine)
|
SessionLocal = sessionmaker(bind=engine)
|
||||||
|
|
||||||
|
|
||||||
class Base(DeclarativeBase):
|
class Base(DeclarativeBase):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def get_db():
|
def get_db():
|
||||||
db = SessionLocal()
|
db = SessionLocal()
|
||||||
try:
|
try:
|
||||||
|
|
@ -21,28 +23,10 @@ def get_db():
|
||||||
finally:
|
finally:
|
||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
def init_db():
|
def init_db():
|
||||||
"""Create tables if they don't exist.
|
|
||||||
|
|
||||||
Uses an advisory lock to prevent race conditions when multiple
|
|
||||||
gunicorn workers start simultaneously.
|
|
||||||
"""
|
|
||||||
import app.models # noqa: F401
|
import app.models # noqa: F401
|
||||||
import app.rag # noqa: F401 — register vector_* tables (pgvector)
|
|
||||||
try:
|
try:
|
||||||
import app.chat # noqa: F401 — register chat models
|
import app.chat # noqa: F401
|
||||||
except ImportError:
|
except ImportError:
|
||||||
pass
|
pass
|
||||||
|
Base.metadata.create_all(bind=engine)
|
||||||
with engine.connect() as conn:
|
|
||||||
# PostgreSQL advisory lock to prevent concurrent CREATE TABLE
|
|
||||||
try:
|
|
||||||
conn.execute(text("SELECT pg_advisory_lock(42)"))
|
|
||||||
conn.execute(text("CREATE EXTENSION IF NOT EXISTS vector"))
|
|
||||||
Base.metadata.create_all(bind=engine)
|
|
||||||
conn.execute(text("SELECT pg_advisory_unlock(42)"))
|
|
||||||
conn.commit()
|
|
||||||
except Exception:
|
|
||||||
# Fallback for non-PostgreSQL (e.g. SQLite in tests)
|
|
||||||
Base.metadata.create_all(bind=engine)
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue