This commit is contained in:
丹尼尔
2026-03-12 19:35:06 +08:00
commit ad96272ab6
40 changed files with 2645 additions and 0 deletions

38
backend/app/db.py Normal file
View File

@@ -0,0 +1,38 @@
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, DeclarativeBase
class Base(DeclarativeBase):
"""Base class for all ORM models."""
def get_database_url() -> str:
"""
DATABASE_URL is configurable via env, default to local SQLite file.
Example: sqlite:///./data/ops_core.db
"""
return os.getenv("DATABASE_URL", "sqlite:///./data/ops_core.db")
DATABASE_URL = get_database_url()
# For SQLite, check_same_thread=False is required when used with FastAPI / threads.
engine = create_engine(
DATABASE_URL,
connect_args={"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {},
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db():
"""
FastAPI dependency to provide a DB session.
"""
db = SessionLocal()
try:
yield db
finally:
db.close()