"""SQLite 数据库连接与初始化""" from pathlib import Path from typing import Generator from sqlmodel import Session, SQLModel, create_engine BASE_DIR = Path(__file__).resolve().parent.parent DATA_DIR = BASE_DIR / "data" DATA_DIR.mkdir(parents=True, exist_ok=True) DB_URL = f"sqlite:///{DATA_DIR / 'vps_manager.db'}" engine = create_engine(DB_URL, echo=False, connect_args={"check_same_thread": False}) def init_db() -> None: """创建所有表(幂等,可重复调用)""" # 显式导入模型,确保其注册到 SQLModel.metadata from app.models.asset import AIAccount, Asset, DomainDetail, VPSDetail # noqa: F401 SQLModel.metadata.create_all(engine) def get_session() -> Generator[Session, None, None]: """FastAPI 依赖:提供数据库会话(请求结束后自动关闭)""" with Session(engine) as session: yield session