hospital-management/fix_db_constraints.py
2025-10-03 20:11:25 +03:00

71 lines
1.9 KiB
Python

"""
Fix database foreign key constraints before running new migrations.
"""
import os
import django
import sqlite3
# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hospital_management.settings')
django.setup()
# Connect to SQLite database
db_path = 'db.sqlite3'
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
print("Fixing database constraints...")
# Disable foreign key checks temporarily
cursor.execute("PRAGMA foreign_keys = OFF;")
# Fix operating_theatre_surgical_note_template with invalid tenant_id
print("Fixing operating_theatre_surgical_note_template...")
cursor.execute("""
DELETE FROM operating_theatre_surgical_note_template
WHERE tenant_id NOT IN (SELECT id FROM core_tenant)
""")
affected = cursor.rowcount
print(f" Deleted {affected} rows with invalid tenant_id")
# Check for other tables with similar issues
tables_to_check = [
'facility_management_maintenancerequest',
'facility_management_workorder',
'facility_management_asset',
]
for table in tables_to_check:
try:
cursor.execute(f"""
UPDATE {table}
SET tenant_id = 1
WHERE tenant_id NOT IN (SELECT id FROM core_tenant)
""")
affected = cursor.rowcount
if affected > 0:
print(f" Fixed {affected} rows in {table}")
except sqlite3.OperationalError as e:
# Table might not exist yet
print(f" Skipping {table}: {e}")
# Commit changes
conn.commit()
# Re-enable foreign key checks
cursor.execute("PRAGMA foreign_keys = ON;")
# Verify constraints
cursor.execute("PRAGMA foreign_key_check;")
violations = cursor.fetchall()
if violations:
print("\nRemaining foreign key violations:")
for violation in violations:
print(f" {violation}")
else:
print("\n✓ All foreign key constraints are now valid!")
conn.close()
print("\nDatabase constraints fixed successfully!")