reset_db.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import mysql.connector
  2. import os
  3. import sys
  4. # Add parent dir to path to import db
  5. sys.path.append(os.path.dirname(os.path.abspath(__file__)))
  6. from db import DB_CONFIG
  7. def reset_and_seed():
  8. try:
  9. conn = mysql.connector.connect(**DB_CONFIG)
  10. cursor = conn.cursor()
  11. print("Dropping tables...")
  12. cursor.execute("SET FOREIGN_KEY_CHECKS = 0;")
  13. cursor.execute("DROP TABLE IF EXISTS materials;")
  14. cursor.execute("DROP TABLE IF EXISTS services;")
  15. # cursor.execute("DROP TABLE IF EXISTS order_files;") # Avoid dropping if not needed, but they depend on materials? No, orders depend on materials?
  16. cursor.execute("SET FOREIGN_KEY_CHECKS = 1;")
  17. print("Running schema.sql...")
  18. schema_path = os.path.join(os.path.dirname(__file__), "schema.sql")
  19. with open(schema_path, "r", encoding="utf-8") as f:
  20. # We need to split by semicolon, but be careful with multi-line statements
  21. sql = f.read()
  22. # A simple split by ; works if there are no semicolons inside strings
  23. sql_commands = sql.split(";")
  24. for command in sql_commands:
  25. cmd = command.strip()
  26. if cmd:
  27. try:
  28. cursor.execute(cmd)
  29. except Exception as e:
  30. # Skip database creation if exists
  31. if "database exists" not in str(e).lower():
  32. print(f"Error in command: {cmd[:50]}... -> {e}")
  33. conn.commit()
  34. print("Database reset and seeded successfully.")
  35. except Exception as e:
  36. print(f"Error: {e}")
  37. finally:
  38. if 'conn' in locals() and conn.is_connected():
  39. cursor.close()
  40. conn.close()
  41. if __name__ == "__main__":
  42. reset_and_seed()