reseed.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import mysql.connector
  2. import os
  3. from db import DB_CONFIG
  4. def reseed_database():
  5. try:
  6. conn = mysql.connector.connect(**DB_CONFIG)
  7. cursor = conn.cursor()
  8. # Disable foreign key checks to truncate properly
  9. cursor.execute("SET FOREIGN_KEY_CHECKS = 0;")
  10. cursor.execute("TRUNCATE TABLE materials;")
  11. cursor.execute("TRUNCATE TABLE services;")
  12. cursor.execute("SET FOREIGN_KEY_CHECKS = 1;")
  13. # Re-run schema.sql seeds
  14. schema_path = os.path.join(os.path.dirname(__file__), "schema.sql")
  15. with open(schema_path, "r", encoding="utf-8") as f:
  16. sql_commands = f.read().split(";")
  17. for command in sql_commands:
  18. cmd = command.strip()
  19. if cmd.startswith("INSERT"):
  20. try:
  21. cursor.execute(cmd)
  22. except mysql.connector.Error as e:
  23. print(f"Error seeding: {e}")
  24. conn.commit()
  25. print("Database re-seeded successfully with localized keys")
  26. except mysql.connector.Error as err:
  27. print(f"Error: {err}")
  28. finally:
  29. if 'conn' in locals() and conn.is_connected():
  30. cursor.close()
  31. conn.close()
  32. if __name__ == "__main__":
  33. reseed_database()