2026-11-10 23:56:50 +08:00
|
|
|
"""Read-only by default. Existing baseline may be stamped only after exact preflight.
|
|
|
|
|
Run from backend: .venv/bin/python ../scripts/schema_preflight.py [--stamp-legacy]
|
|
|
|
|
No credentials are accepted on the command line; use protected environment.
|
|
|
|
|
"""
|
2026-11-14 14:07:26 +08:00
|
|
|
|
|
|
|
|
import argparse, asyncio, importlib.util, sys
|
2026-11-10 23:56:50 +08:00
|
|
|
from pathlib import Path
|
2026-11-14 14:07:26 +08:00
|
|
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
sys.path.insert(0, str(ROOT / "backend"))
|
|
|
|
|
from app.core.config import Settings
|
|
|
|
|
from app.core.schema import schema_preflight
|
2026-11-10 23:56:50 +08:00
|
|
|
from sqlalchemy.ext.asyncio import create_async_engine
|
|
|
|
|
from sqlalchemy import inspect
|
|
|
|
|
|
2026-11-14 14:07:26 +08:00
|
|
|
|
2026-11-10 23:56:50 +08:00
|
|
|
def legacy_metadata():
|
2026-11-14 14:07:26 +08:00
|
|
|
spec = importlib.util.spec_from_file_location(
|
|
|
|
|
"legacy_preflight", ROOT / "backend/alembic/legacy_schema.py"
|
|
|
|
|
)
|
|
|
|
|
module = importlib.util.module_from_spec(spec)
|
|
|
|
|
spec.loader.exec_module(module)
|
2026-11-10 23:56:50 +08:00
|
|
|
return module.Base.metadata
|
|
|
|
|
|
2026-11-14 14:07:26 +08:00
|
|
|
|
2026-11-10 23:56:50 +08:00
|
|
|
async def inspect_schema(settings):
|
2026-11-14 14:07:26 +08:00
|
|
|
engine = create_async_engine(settings.sqlalchemy_url)
|
2026-11-10 23:56:50 +08:00
|
|
|
async with engine.connect() as c:
|
2026-11-14 14:07:26 +08:00
|
|
|
diff = await c.run_sync(schema_preflight, legacy_metadata())
|
|
|
|
|
existing = await c.run_sync(
|
|
|
|
|
lambda conn: "alembic_version" in inspect(conn).get_table_names()
|
|
|
|
|
)
|
2026-11-10 23:56:50 +08:00
|
|
|
await engine.dispose()
|
2026-11-14 14:07:26 +08:00
|
|
|
return diff, existing
|
|
|
|
|
|
2026-11-10 23:56:50 +08:00
|
|
|
|
|
|
|
|
def main():
|
2026-11-14 14:07:26 +08:00
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
|
parser.add_argument("--stamp-legacy", action="store_true")
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
diff, versioned = asyncio.run(inspect_schema(Settings.from_env()))
|
|
|
|
|
for item in diff.differences:
|
|
|
|
|
print(item)
|
|
|
|
|
if not diff.matches:
|
|
|
|
|
raise SystemExit("Schema mismatch: refusing stamp")
|
2026-11-10 23:56:50 +08:00
|
|
|
print("Legacy six-table schema matches")
|
|
|
|
|
if args.stamp_legacy:
|
2026-11-14 14:07:26 +08:00
|
|
|
if versioned:
|
|
|
|
|
raise SystemExit("Already versioned: refusing baseline stamp")
|
2026-11-10 23:56:50 +08:00
|
|
|
from alembic.config import Config
|
|
|
|
|
from alembic import command
|
2026-11-14 14:07:26 +08:00
|
|
|
|
|
|
|
|
command.stamp(Config(str(ROOT / "backend/alembic.ini")), "001")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
main()
|