41 lines
1.1 KiB
Python
41 lines
1.1 KiB
Python
from sqlalchemy import create_engine, event
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
from config import get_settings
|
|
|
|
settings = get_settings()
|
|
|
|
engine = create_engine(
|
|
settings.DATABASE_URL,
|
|
connect_args={"check_same_thread": False},
|
|
)
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
Base = declarative_base()
|
|
|
|
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def create_tables():
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
|
|
def run_migrations():
|
|
"""Apply lightweight schema migrations for SQLite."""
|
|
from sqlalchemy import inspect, text
|
|
insp = inspect(engine)
|
|
|
|
# AuditLog: add username column if missing
|
|
if "audit_log" in insp.get_table_names():
|
|
audit_cols = {c["name"] for c in insp.get_columns("audit_log")}
|
|
if "username" not in audit_cols:
|
|
with engine.connect() as conn:
|
|
conn.execute(text("ALTER TABLE audit_log ADD COLUMN username TEXT"))
|
|
conn.commit()
|