CONTRACT_ENV=test обязывает: база оканчивается на _test.db (не «содержит _test»), ссылка и жёсткая ссылка на боевую базу отвергаются, DATA_DIR — явный абсолютный каталог вне боевых (и их предков). Проверка стоит при импорте db.py — до первого соединения; скрипт миграции admin v2 проверяет свой --db тем же правилом и отвергает неизвестный маркер. Проверки: tests/test_contract_env.py (14), мутации (суффикс, ссылка, жёсткая ссылка, предок каталога, пустой и относительный DATA_DIR, скрипт миграции) краснеют. Co-Authored-By: Claude Code <noreply@anthropic.com>
114 lines
4.8 KiB
Python
114 lines
4.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Тяжёлые индексы admin v2 — отдельной командой, НЕ в init_db.
|
|
|
|
Зачем отдельно: `init_db()` выполняется на каждом старте, а `DROP INDEX` не отменяется
|
|
рестартом. Индексы создаются один раз на копии/в окно тишины, замеряются и только потом
|
|
применяются на проде (P2.0).
|
|
|
|
Запуск:
|
|
python3 scripts/migrate_admin_v2.py --db /tmp/copy.db [--dry-run] [--json]
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import os
|
|
import json
|
|
import sqlite3
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
import contract_env
|
|
|
|
INDEXES = [
|
|
("idx_messages_user_role_ts", "messages", "username, role, timestamp"),
|
|
("idx_audit_user_ts", "audit_log", "username, timestamp"),
|
|
("idx_audit_action_ts", "audit_log", "action, timestamp"),
|
|
("idx_topups_status_ts", "topups", "status, ts"),
|
|
]
|
|
# Старые одиночные индексы: их создавал прежний init_db и больше не удаляет никто.
|
|
LEGACY_DROPS = ["idx_messages_user_ts", "idx_audit_user"]
|
|
|
|
|
|
def _has_table(conn, name: str) -> bool:
|
|
return bool(conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
|
|
(name,)).fetchone())
|
|
|
|
|
|
def _has_index(conn, name: str) -> bool:
|
|
return bool(conn.execute("SELECT 1 FROM sqlite_master WHERE type='index' AND name=?",
|
|
(name,)).fetchone())
|
|
|
|
|
|
def run(db_path: Path, dry_run: bool = False) -> dict:
|
|
if not db_path.exists():
|
|
return {"ok": False, "code": 2, "errors": [f"нет базы: {db_path}"], "indexes": []}
|
|
conn = None
|
|
out = []
|
|
try:
|
|
conn = sqlite3.connect(str(db_path))
|
|
conn.execute("PRAGMA busy_timeout=5000")
|
|
for name, table, columns in INDEXES:
|
|
if not _has_table(conn, table):
|
|
out.append({"name": name, "table": table, "status": "skip-no-table"})
|
|
continue
|
|
if _has_index(conn, name):
|
|
out.append({"name": name, "table": table, "status": "exists"})
|
|
continue
|
|
if dry_run:
|
|
out.append({"name": name, "table": table, "status": "would-create"})
|
|
continue
|
|
started = time.perf_counter()
|
|
# IF NOT EXISTS: окно тишины не гарантирует, что второй migrate не стартует.
|
|
conn.execute(f"CREATE INDEX IF NOT EXISTS {name} ON {table}({columns})")
|
|
conn.commit()
|
|
out.append({"name": name, "table": table, "status": "created",
|
|
"ms": round((time.perf_counter() - started) * 1000, 1)})
|
|
for name in LEGACY_DROPS:
|
|
had = _has_index(conn, name)
|
|
if dry_run:
|
|
out.append({"name": name, "status": "would-drop" if had else "absent"})
|
|
continue
|
|
conn.execute(f"DROP INDEX IF EXISTS {name}")
|
|
conn.commit()
|
|
out.append({"name": name, "status": "dropped" if had else "absent"})
|
|
if dry_run:
|
|
return {"ok": True, "integrity": "not-run", "indexes": out}
|
|
integrity = conn.execute("PRAGMA integrity_check").fetchone()[0]
|
|
if integrity != "ok":
|
|
return {"ok": False, "code": 3, "integrity": integrity,
|
|
"errors": [f"integrity_check: {integrity}"], "indexes": out}
|
|
return {"ok": True, "integrity": integrity, "indexes": out}
|
|
except sqlite3.Error as e:
|
|
return {"ok": False, "code": 2, "errors": [f"база: {e}"], "indexes": out}
|
|
finally:
|
|
if conn is not None:
|
|
conn.close()
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
ap = argparse.ArgumentParser(description="индексы admin v2 на копии")
|
|
ap.add_argument("--db", required=True)
|
|
ap.add_argument("--dry-run", action="store_true")
|
|
ap.add_argument("--json", action="store_true")
|
|
args = ap.parse_args(argv)
|
|
if contract_env.mode() == "test":
|
|
# R-05: в тестовом контуре скрипт обязан отказаться от не-тестовой базы.
|
|
contract_env.check_db_path(args.db)
|
|
result = run(Path(args.db), args.dry_run)
|
|
if args.json:
|
|
print(json.dumps(result, ensure_ascii=False))
|
|
else:
|
|
print("migrate_admin_v2:", "ok" if result["ok"] else "FAIL",
|
|
"integrity=" + str(result.get("integrity")))
|
|
for item in result.get("indexes", []):
|
|
print(" -", item)
|
|
for e in result.get("errors", []):
|
|
print(" !", e)
|
|
return 0 if result["ok"] else int(result.get("code", 1))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|