58 lines
1.7 KiB
Python
58 lines
1.7 KiB
Python
#!/usr/bin/env python
|
|
"""播种入口:``./.venv/bin/python -m app.seed [--force|--fresh]``
|
|
|
|
* 无参数 幂等:已播种则跳过,只补缺失的权限/字典
|
|
* ``--force`` 强制补齐缺失数据
|
|
* ``--fresh`` 删表重建 + 重新播种(仅开发环境重置演示数据)
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import logging
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
if str(ROOT) not in sys.path: # 允许未 pip install -e . 时直接运行
|
|
sys.path.insert(0, str(ROOT))
|
|
|
|
from app.services.seed import seed_all # noqa: E402
|
|
|
|
|
|
async def rebuild() -> None:
|
|
"""删表重建(仅用于开发环境重置演示数据)。"""
|
|
from app.db.base import Base
|
|
from app.db.session import engine
|
|
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.drop_all)
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
|
|
|
|
async def prepare() -> None:
|
|
"""建缺失的表 + 补新增的可空列(幂等),使空库也能直接播种。"""
|
|
from app.core.config import settings
|
|
from app.db.schema import sync_schema
|
|
from app.db.session import engine
|
|
|
|
await sync_schema(engine, is_sqlite=settings.is_sqlite)
|
|
|
|
|
|
def main() -> int:
|
|
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
|
force = "--force" in sys.argv or "--fresh" in sys.argv
|
|
if "--fresh" in sys.argv:
|
|
asyncio.run(rebuild())
|
|
print("✔ 已重建全部数据表")
|
|
else:
|
|
asyncio.run(prepare())
|
|
report = asyncio.run(seed_all(force=force))
|
|
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|