#!/usr/bin/env python3 """清空本应用写入的 PostgreSQL 业务表(开发用;表结构保留)。 直接执行即可:``uv run python scripts/start_fresh.py`` ``./start_fresh.sh`` 与 ``./start.sh`` 一致,仅在启动 uvicorn 前多执行本脚本。 """ from __future__ import annotations import asyncio import os import sys # 允许从任意 cwd 以 `uv run python scripts/start_fresh.py` 运行 _REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) if _REPO_ROOT not in sys.path: sys.path.insert(0, _REPO_ROOT) from sqlalchemy import text from app.config import settings from app.database import engine, init_db_schema # 与 app/db/models.py 一致;有 FK 时子表排前面 _TABLES = ( "surgery_result_details", "surgery_final_results", "voice_confirmation_audits", ) _TRUNCATE_SQL = text( "TRUNCATE TABLE " + ", ".join(_TABLES) + " RESTART IDENTITY" ) async def _run() -> None: # 确保新库也有表 await init_db_schema() async with engine.begin() as conn: await conn.execute(_TRUNCATE_SQL) dsn = settings.sqlalchemy_database_url safe = dsn if "@" in dsn: # 隐藏 user:pass at = dsn.rfind("@") if "://" in dsn: parts = dsn.split("://", 1) safe = f"{parts[0]}://***@{dsn[at + 1:]}" print("已清空表:", ", ".join(_TABLES)) print("数据库:", safe) def main() -> None: asyncio.run(_run()) print("完成。") if __name__ == "__main__": main()