"""Create the Flint schema in Supabase. Run once: python scripts/setup_db.py Preferred path: set SUPABASE_DB_URL in .env (the direct Postgres URI from Supabase -> Project Settings -> Database -> Connection string). This script then applies scripts/schema.sql over that connection. Fallback path: if SUPABASE_DB_URL is not set, the SQL is printed so you can paste it into the Supabase SQL editor instead. (The anon client used by the app at runtime cannot run DDL, which is why a direct connection is needed.) """ import sys from pathlib import Path # Allow running as `python scripts/setup_db.py` from the repo root. sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from bot import config # noqa: E402 SCHEMA_PATH = Path(__file__).with_name("schema.sql") _PLACEHOLDERS = ("[YOUR-PASSWORD]", "your-project-ref") def _print_manual(schema_sql: str) -> None: print("SUPABASE_DB_URL is not configured.\n") print("Option A (recommended): put the direct Postgres URI in .env as") print("SUPABASE_DB_URL, then re-run: python scripts/setup_db.py\n") print("Option B: paste the SQL below into the Supabase SQL editor and run it:\n") print("-" * 72) print(schema_sql) print("-" * 72) def main() -> None: schema_sql = SCHEMA_PATH.read_text() db_url = config.SUPABASE_DB_URL if not db_url or any(p in db_url for p in _PLACEHOLDERS): _print_manual(schema_sql) return try: import psycopg except ImportError: print("psycopg is not installed. Run: pip install -r requirements.txt") sys.exit(1) print(f"Applying {SCHEMA_PATH.name} to the Supabase Postgres database...") try: with psycopg.connect(db_url, autocommit=True) as conn: with conn.cursor() as cur: cur.execute(schema_sql) print("✓ Schema applied. Table `ideas`, the ivfflat index, and match_ideas() are ready.") except Exception as e: # noqa: BLE001 - surface any connection/SQL failure clearly print(f"✗ Failed to apply schema: {e}\n") print("You can instead paste scripts/schema.sql into the Supabase SQL editor.") sys.exit(1) if __name__ == "__main__": main()