This commit is contained in:
2025-10-06 17:49:09 +02:00
parent 97a678ef4a
commit 4cbf44c9c9
4 changed files with 422 additions and 0 deletions

91
find_empty_tables.py Normal file
View File

@@ -0,0 +1,91 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import fdb
from pathlib import Path
# ================== CONFIG ==================
DB_PATH = r"u:\MEDICUS 3\data\medicus.FDB"
HOST = "localhost"
USER = "sysdba"
PASSWORD = "masterkey"
LOG_FILE = Path("dropped_tables_with_deps.txt")
# ============================================
con = fdb.connect(
host=HOST,
database=DB_PATH,
user=USER,
password=PASSWORD,
charset="WIN1250",
)
cur = con.cursor()
print("🔍 Checking tables for emptiness and dependencies...")
# All user tables
cur.execute("""
SELECT TRIM(rdb$relation_name)
FROM rdb$relations
WHERE rdb$system_flag = 0
ORDER BY 1
""")
tables = [r[0] for r in cur.fetchall()]
dropped = []
skipped = []
def drop_fk_constraints_referring_to(table_name: str):
# Find all FKs that reference this table (PK or UNIQUE)
cur.execute(f"""
SELECT TRIM(rc.rdb$relation_name), TRIM(rc.rdb$constraint_name)
FROM rdb$relation_constraints rc
JOIN rdb$ref_constraints ref ON ref.rdb$constraint_name = rc.rdb$constraint_name
JOIN rdb$relation_constraints pk ON pk.rdb$constraint_name = ref.rdb$const_name_uq
WHERE rc.rdb$constraint_type = 'FOREIGN KEY'
AND UPPER(pk.rdb$relation_name) = '{table_name.upper()}'
""")
for fk_table, fk_name in cur.fetchall():
stmt = f'ALTER TABLE {fk_table} DROP CONSTRAINT {fk_name}'
try:
print(f" 🔧 Dropping FK {fk_name} in {fk_table}")
con.execute_immediate(stmt)
con.commit() # commit each FK drop
except Exception as e:
print(f" ⚠️ Could not drop FK {fk_name} in {fk_table}: {e}")
con.rollback()
for t in tables:
try:
# Count rows
cur.execute(f"SELECT COUNT(*) FROM {t}")
count = cur.fetchone()[0]
if count > 0:
continue
print(f"\n🧹 {t} → empty")
# 1) Drop FKs that reference this table
drop_fk_constraints_referring_to(t)
# 2) Try to drop the table itself
try:
con.execute_immediate(f"DROP TABLE {t}")
con.commit() # commit this table drop
dropped.append(t)
print(f" ✅ Dropped table {t}")
except Exception as e:
print(f" ⚠️ Could not drop {t}: {e}")
con.rollback()
skipped.append(t)
except Exception as e:
print(f"⚠️ Skipping {t}: {e}")
con.close()
LOG_FILE.write_text("\n".join(dropped), encoding="utf-8")
print("\n✅ Done.")
print(f"Total dropped: {len(dropped)}")
print(f"Skipped: {len(skipped)}")
print(f"List saved to {LOG_FILE.resolve()}")