"""Apply the Supabase Postgres schema files in the right order. Idempotent: each SQL file is written with ``IF NOT EXISTS`` / ``CREATE OR REPLACE`` / ``DROP POLICY IF EXISTS`` guards, so running this script twice in a row is safe. Order: 1. ``supabase_setup.sql`` — auth.profiles + RLS baseline 2. ``supabase_schema_full.sql`` — application tables (bots, personas, scenarios, sessions, …) 3. ``supabase_security_hardening.sql`` — RLS policies on app tables 4. ``supabase_fix.sql`` (optional) — emergency fixes; --include-fix 5. ``supabase_create_admin.sql`` (opt) — admin grant, --include-admin Connection string is read from ``--database-url`` or, by default, from the ``SUPABASE_DB_URL`` env var (falling back to ``DATABASE_URL``). For production on Supabase use the **direct connection** URL (port 5432 or the pooler 6543), NOT the REST API URL. Usage:: # Dry-run: parse + report file order, no DB connection. python scripts/apply_supabase_schema.py --dry-run # Real run against Supabase: SUPABASE_DB_URL="postgresql://postgres:...@db.xxx.supabase.co:5432/postgres" \ python scripts/apply_supabase_schema.py # Include optional files: python scripts/apply_supabase_schema.py --include-fix --include-admin Returns non-zero on any SQL error so it's safe to wire into CI/deploy. """ from __future__ import annotations import argparse import os import sys from pathlib import Path from typing import List, Optional REPO_ROOT = Path(__file__).resolve().parent.parent def _autoload_env() -> None: """Auto-load .env.production.local / .env.production if present. Convenience for `python scripts/apply_supabase_schema.py` invocations: the operator doesn't have to `source` the env file or set SUPABASE_DB_URL on the command line. Idempotent — never overrides a value already set in the process environment. """ for candidate in (".env.production.local", ".env.production"): path = REPO_ROOT / candidate if not path.exists(): continue try: from dotenv import load_dotenv # type: ignore[import-not-found] load_dotenv(path, override=False) except ImportError: for line in path.read_text(encoding="utf-8").splitlines(): stripped = line.strip() if not stripped or stripped.startswith("#") or "=" not in stripped: continue key, _, value = stripped.partition("=") os.environ.setdefault(key.strip(), value.strip().strip("'\"")) return _autoload_env() # (filename, label, default-included) SQL_FILES: List[tuple[str, str, bool]] = [ ("supabase_setup.sql", "1/3 auth.profiles + RLS baseline", True), ("supabase_schema_full.sql", "2/3 application tables", True), ("supabase_security_hardening.sql", "3/3 RLS policies", True), ("supabase_fix.sql", "(opt) emergency fixes", False), ("supabase_create_admin.sql", "(opt) admin grant", False), ] def _resolve_db_url(cli_value: Optional[str]) -> str: if cli_value: return cli_value for env_var in ("SUPABASE_DB_URL", "DATABASE_URL"): v = os.getenv(env_var, "").strip() if v: return v raise SystemExit( "no DB URL — pass --database-url or set SUPABASE_DB_URL / DATABASE_URL" ) def _mask_url(url: str) -> str: if "@" not in url: return url scheme, rest = url.split("//", 1) creds, host = rest.split("@", 1) if ":" in creds: user, _ = creds.split(":", 1) creds = f"{user}:****" return f"{scheme}//{creds}@{host}" def _normalize_url_for_psycopg2(url: str) -> str: """SQLAlchemy URLs use ``postgresql+psycopg2://``; psycopg2 wants plain ``postgresql://``. Strip the dialect suffix when present.""" return url.replace("postgresql+psycopg2://", "postgresql://", 1) def _select_files(args: argparse.Namespace) -> List[Path]: selected: List[Path] = [] for fname, label, default in SQL_FILES: if not default: if fname == "supabase_fix.sql" and not args.include_fix: continue if fname == "supabase_create_admin.sql" and not args.include_admin: continue path = REPO_ROOT / fname if not path.exists(): print(f" skip (missing): {fname} [{label}]") continue selected.append(path) return selected def _run_sql_file(conn, path: Path) -> None: """Execute the entire file in a single transaction. psycopg2 treats the payload as one big statement when passed via ``cursor.execute`` with a multi-statement string — that's what we want.""" sql = path.read_text(encoding="utf-8") if not sql.strip(): print(f" skip (empty): {path.name}") return with conn.cursor() as cur: cur.execute(sql) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument( "--database-url", default="", help="Postgres URL. Defaults to SUPABASE_DB_URL / DATABASE_URL env", ) parser.add_argument( "--dry-run", action="store_true", help="Parse and list files only, no DB connection", ) parser.add_argument("--include-fix", action="store_true") parser.add_argument("--include-admin", action="store_true") args = parser.parse_args() files = _select_files(args) print(f"\napply_supabase_schema: {len(files)} file(s) to apply\n") for path in files: print(f" - {path.name}") print() if args.dry_run: print("dry-run: not connecting to the database") return 0 db_url = _resolve_db_url(args.database_url) print(f"target: {_mask_url(db_url)}\n") try: import psycopg2 # type: ignore[import-not-found] except ImportError: print( "psycopg2 not installed. Install with:\n" " pip install psycopg2-binary", file=sys.stderr, ) return 2 try: conn = psycopg2.connect(_normalize_url_for_psycopg2(db_url)) except Exception as exc: print(f"connection failed: {exc}", file=sys.stderr) return 3 failures: List[str] = [] try: for path in files: print(f" applying {path.name} …", flush=True) try: _run_sql_file(conn, path) conn.commit() print(f" ✓ ok") except Exception as exc: conn.rollback() failures.append(f"{path.name}: {exc}") print(f" ✗ FAILED: {exc}", file=sys.stderr) finally: conn.close() print() if failures: print(f"apply_supabase_schema: FAILED on {len(failures)} file(s):") for line in failures: print(f" - {line}") return 1 print("apply_supabase_schema: all files applied successfully ✓") return 0 if __name__ == "__main__": sys.exit(main())