reset_db.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. tables = ["order_photos", "order_files", "orders", "password_reset_tokens", "users", "services", "materials", "posts"]
  14. for table in tables:
  15. cursor.execute(f"DROP TABLE IF EXISTS {table};")
  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. # Seed portfolio images
  36. try:
  37. from seed_portfolio import seed_portfolio
  38. seed_portfolio()
  39. except Exception as e:
  40. print(f"Portfolio seeding failed: {e}")
  41. except Exception as e:
  42. print(f"Error: {e}")
  43. finally:
  44. if 'conn' in locals() and conn.is_connected():
  45. cursor.close()
  46. conn.close()
  47. if __name__ == "__main__":
  48. reset_and_seed()