Spaces:
Sleeping
Sleeping
| """資料庫連線與初始化(SQLite via SQLModel)。 | |
| - engine:從 .env 的 DATABASE_URL 建立連線。 | |
| - init_db():建表,若資料表是空的,把 40 筆假資料寫入(首次啟動用)。 | |
| - get_session():FastAPI 依賴注入用的 session。 | |
| """ | |
| from sqlmodel import Session, SQLModel, create_engine, select | |
| from app.config import settings | |
| from app.fake_data import get_raw_customers | |
| from app.models import Customer | |
| # SQLite 需要 check_same_thread=False 才能在 FastAPI 多執行緒下使用 | |
| connect_args = {"check_same_thread": False} if settings.database_url.startswith("sqlite") else {} | |
| engine = create_engine(settings.database_url, echo=False, connect_args=connect_args) | |
| def init_db() -> None: | |
| """建表 + 首次填入種子資料。""" | |
| SQLModel.metadata.create_all(engine) | |
| with Session(engine) as session: | |
| existing = session.exec(select(Customer)).first() | |
| if existing is None: | |
| for raw in get_raw_customers(): | |
| # 去掉 fake_data 自帶的 id,讓資料庫自動編號 | |
| raw = {k: v for k, v in raw.items() if k != "id"} | |
| session.add(Customer(**raw)) | |
| session.commit() | |
| def get_session(): | |
| with Session(engine) as session: | |
| yield session | |