Fix import script: auto-detect FK tables before truncate

This commit is contained in:
Pierre & Lumière 2026-04-14 13:31:00 +02:00
parent 338c0ecc0f
commit 42fb16d67e

View File

@ -58,16 +58,22 @@ def main():
with engine.begin() as conn: with engine.begin() as conn:
if args.truncate: if args.truncate:
print("[INFO] Nettoyage des tables dépendantes + TRUNCATE servers") print("[INFO] Nettoyage des tables référençant servers")
if not args.dry_run: if not args.dry_run:
for tbl in ("server_ips", "qualys_assets", "audits", fk_tables = conn.execute(text("""
"session_servers", "planning_sessions", SELECT DISTINCT tc.table_name
"patch_history", "ref_correspondance"): FROM information_schema.table_constraints tc
try: JOIN information_schema.constraint_column_usage ccu
conn.execute(text(f"DELETE FROM {tbl}")) ON tc.constraint_name = ccu.constraint_name
except Exception as e: WHERE tc.constraint_type = 'FOREIGN KEY'
print(f" [WARN] DELETE {tbl}: {e}") AND ccu.table_name = 'servers'
AND tc.table_name != 'servers'
""")).fetchall()
for (tbl,) in fk_tables:
conn.execute(text(f"DELETE FROM {tbl}"))
print(f" [OK] cleared {tbl}")
conn.execute(text("TRUNCATE servers RESTART IDENTITY CASCADE")) conn.execute(text("TRUNCATE servers RESTART IDENTITY CASCADE"))
print(" [OK] servers truncated")
inserted = 0 inserted = 0
skipped = 0 skipped = 0