Spaces:
Running
Running
File size: 4,686 Bytes
6272eef | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | """Generate the schema baseline from the live database, via PostgREST's OpenAPI spec.
Run: python scripts/dump_schema.py > migrations/0001_baseline.sql
Why the OpenAPI spec and not pg_dump: the only credential this project holds is the
Supabase URL + service-role key, which reach PostgREST but not Postgres itself. The
spec carries every table, column, type, nullability and primary key — enough for a
baseline that records what the code expects.
What it CANNOT see, and what therefore has to come from a real `pg_dump` when the
database connection string is available (Supabase dashboard -> Settings -> Database):
indexes (including the pgvector ones the retrieval path depends on), foreign keys,
check constraints, RLS policies, triggers, functions, and exact column defaults.
Those are listed as TODO comments in the output rather than silently omitted, so the
gap is visible in the file instead of being discovered later.
"""
from __future__ import annotations
import os
import sys
import httpx
# PostgREST spells the primary key into each column's description.
_PK_MARKER = "<pk/>"
def fetch_spec(url: str, key: str) -> dict:
response = httpx.get(
f"{url.rstrip('/')}/rest/v1/",
headers={"apikey": key, "Authorization": f"Bearer {key}", "Accept": "application/json"},
timeout=60.0,
)
response.raise_for_status()
return response.json()
def column_sql(name: str, spec: dict, required: set[str]) -> str:
# `format` is the real Postgres type; `type` is the JSON-schema approximation.
pg_type = spec.get("format") or "text"
parts = [f" {name} {pg_type}"]
if _PK_MARKER in (spec.get("description") or ""):
parts.append("PRIMARY KEY")
elif name in required:
# PostgREST marks a column required when it is NOT NULL without a default.
parts.append("NOT NULL")
default = spec.get("default")
if default is not None:
parts.append(f"DEFAULT {default}")
return " ".join(parts)
def main() -> int:
url = os.environ.get("SUPABASE_URL", "")
key = os.environ.get("SUPABASE_SERVICE_ROLE_KEY", "")
if not url or not key:
print("SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY must be set", file=sys.stderr)
return 2
spec = fetch_spec(url, key)
definitions = spec.get("definitions") or {}
if not definitions:
print("no table definitions in the spec", file=sys.stderr)
return 1
out: list[str] = [
"-- Schema baseline, generated by scripts/dump_schema.py from the live database.",
"-- Records what the code expects. Idempotent: safe to run against a database",
"-- that already has these tables.",
"--",
"-- INCOMPLETE BY CONSTRUCTION. Derived from PostgREST's OpenAPI spec, which",
"-- does not expose indexes, foreign keys, check constraints, RLS policies,",
"-- triggers, functions, or exact defaults. Replace this file with a real",
"-- `pg_dump --schema-only` once the database connection string is to hand;",
"-- until then the TODOs below mark what is missing.",
"",
"-- pgvector must exist before any embedding column can be created.",
"create extension if not exists vector with schema extensions;",
"",
"create table if not exists schema_migrations (",
" version text primary key,",
" applied_at timestamptz not null default now()",
");",
"",
]
for table in sorted(definitions):
table_spec = definitions[table]
properties = table_spec.get("properties") or {}
if not properties:
continue
required = set(table_spec.get("required") or [])
out.append(f"-- {'-' * 72}")
out.append(f"create table if not exists {table} (")
columns = [column_sql(n, s, required) for n, s in properties.items()]
out.append(",\n".join(columns))
out.append(");")
# The type comes back namespaced ("extensions.vector(1536)"), so match on
# the word rather than equality — checking for "vector" exactly found none.
vectors = [n for n, s in properties.items() if "vector" in (s.get("format") or "")]
if vectors:
out.append(
f"-- TODO(index): {table}.{', '.join(vectors)} needs its pgvector index; "
"retrieval falls back to lexical ranking without it."
)
out.append("")
out.append("insert into schema_migrations (version) values ('0001_baseline')")
out.append(" on conflict (version) do nothing;")
print("\n".join(out))
return 0
if __name__ == "__main__":
raise SystemExit(main())
|