import os import sys import argparse import subprocess from pathlib import Path # Hardcoded directories MIGRATIONS_DIR = "migrations" SEEDS_DIR = "seeds" def main(): # Connection settings are env-overridable so the script can target either a # local Postgres or the shared dcntrlized-db container (PGHOST=dcntrlized-db). user = os.environ.get("PGUSER", "postgres") password = os.environ.get("PGPASSWORD", "") dbname = os.environ.get("PGDATABASE", "postgres") host = os.environ.get("PGHOST", "localhost") port = os.environ.get("PGPORT", "5432") print("==========================================") print("Starting Database Setup & Seeding") print(f"Host: {host}:{port} | User: {user} | DB: {dbname}") print("==========================================\n") os.environ["PGUSER"] = user os.environ["PGPASSWORD"] = password os.environ["PGDATABASE"] = dbname os.environ["PGHOST"] = host os.environ["PGPORT"] = port # 1. Run SQL Migrations print("--- Running SQL Migrations ---") migrations_path = Path(MIGRATIONS_DIR) if not migrations_path.is_dir(): print(f"Warning: Migrations directory '{MIGRATIONS_DIR}' not found.") else: # Grab all .sql files and sort them (e.g., 001_..., 002_...) sql_files = sorted(migrations_path.glob("*.sql")) if not sql_files: print(f"No SQL migration files found in '{MIGRATIONS_DIR}/'.") for sql_file in sql_files: print(f"Applying: {sql_file.name}") # Run psql with ON_ERROR_STOP=1 to fail fast if SQL throws an error result = subprocess.run( ["psql", "-v", "ON_ERROR_STOP=1", "-f", str(sql_file)], check=False ) if result.returncode != 0: print(f"\nāŒ Migration failed on {sql_file.name}") sys.exit(result.returncode) # 2. Run Python Seed Scripts print("\n--- Running Python Seed Scripts ---") os.environ["PGDATABASE"] = "dcntrlized" seeds_path = Path(SEEDS_DIR) if not seeds_path.is_dir(): print(f"Warning: Seeds directory '{SEEDS_DIR}' not found.") else: # Grab all .py files and sort them py_files = sorted(seeds_path.glob("*.py")) if not py_files: print(f"No Python seed files found in '{SEEDS_DIR}/'.") for py_file in py_files: print(f"Executing: {py_file.name}") # Run the seed script using the same Python interpreter running this script result = subprocess.run( [sys.executable, str(py_file)], check=False ) if result.returncode != 0: print(f"\nāŒ Seeding failed on {py_file.name}") sys.exit(result.returncode) print("\n==========================================") print("āœ… All migrations and seeds completed successfully!") print("==========================================") if __name__ == "__main__": main()