Spaces:
Running
Running
File size: 1,142 Bytes
a63c61f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
from src.core.config import settings
from src.core.domain.db_models import Base
engine = create_engine(
settings.SQLALCHEMY_DATABASE_URI,
pool_recycle=300,
pool_pre_ping=True
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def init_db():
Base.metadata.create_all(bind=engine)
_run_migrations()
def _run_migrations():
"""Apply any missing schema changes that create_all won't handle (existing tables)."""
migrations = [
"ALTER TABLE chat_history ADD COLUMN IF NOT EXISTS pinned BOOLEAN DEFAULT FALSE",
"ALTER TABLE chat_history ADD COLUMN IF NOT EXISTS user_id INTEGER REFERENCES users(id) ON DELETE SET NULL",
]
with engine.connect() as conn:
for sql in migrations:
try:
conn.execute(text(sql))
except Exception:
pass # Column may already exist or constraint may differ — safe to ignore
conn.commit()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
|