Spaces:
Running
Running
Download scripts/dump_schema.py from userIdc2024/creative-brain-os: direct link, hf CLI and curl.
- Browser
- Download file 4.69 kB
-
https://huggingface.co/spaces/userIdc2024/creative-brain-os/resolve/main/scripts/dump_schema.py
- Command line
-
hf download hf://spaces/userIdc2024/creative-brain-os/scripts/dump_schema.py
-
curl -L -o dump_schema.py https://huggingface.co/spaces/userIdc2024/creative-brain-os/resolve/main/scripts/dump_schema.py
4.69 kB
| """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()) | |