Files
supabase/packages/pg-meta/README.md
Andrew Valleteau 768ea1001b fix(studio): scope table editor introspection CTEs to target table OID (#47894)
## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

## What kind of change does this PR introduce?

Bug fix (performance), plus a regression-guard test suite and docs.

## What is the current behavior?

Studio's introspection queries in `@supabase/pg-meta` do `O(catalog)`
work for per-table requests. On databases with very large catalogs
(hundreds of thousands of relations/constraints — real deployments reach
this) they take tens of seconds per dashboard interaction, trip
`statement_timeout`, and create heavy CPU/memory pressure when several
tabs open concurrently. Two instances of the same bug class:

**1. Table Editor query (`getTableEditorSql`)** — fetches metadata for
ONE table by OID, but five catalog scans are unscoped and only filtered
at the top-level join:

- `primary_keys` CTE — scans all of `pg_index` (`where i.indisprimary`)
- `index_cols` CTE — scans all unique indexes
- `relationships` CTE — scans every FK in `pg_constraint` (and is
scanned twice by the two subplans)
- `uniques` subquery (inside `columns`) — scans all single-column unique
constraints
- `check_constraints` subquery (inside `columns`) — scans all
single-column check constraints

The planner cannot push the outer join qual into grouped / `distinct on`
subqueries, so each is computed over the full catalog and thrown away.
`tables-paginated.ts` was previously rewritten to avoid exactly this
pattern; the single-table query never got the same treatment.

**2. Entity definitions (`getTableDefinitionSql` /
`getEntityDefinitionsSql`)** — the vendored `pg_get_tabledef` plpgsql
function scans the entire `information_schema.columns` view once **per
column** (plus `information_schema.tables` once per call) just to decide
whether a name needs double-quoting — a pure string property of a name
it already holds — and its per-index partial-index lookup casts
`relnamespace::regnamespace::text` across every `pg_class` row. On a
12K-table catalog this makes a single entity's DDL cost ~3.7s and a
default 100-entity definitions page ~6 minutes.

## What is the new behavior?

**Fix 1 — scope the Table Editor CTEs to the requested OID** (`id` is
validated non-null and interpolated via `literal()`, same as the
existing `base_table_info` filter):

- `primary_keys` / `index_cols`: `and i.indrelid = <id>`
- `relationships`: `and (c.conrelid = <id> or c.confrelid = <id>)`
- `uniques` / `check_constraints`: `and conrelid = <id>`

Semantics are unchanged: the top-level select already filtered every CTE
to the target table, so rows for other tables were computed and
discarded. The `pg_index`/`pg_constraint` lookups become index scans
returning a handful of rows. One residual scan is structural: PostgreSQL
has no index on `pg_constraint.confrelid`, so the incoming-FK half of
`relationships` is a single filtered seq scan of `pg_constraint` — still
one cheap pass instead of materializing every FK row twice.

**Fix 2 — remove the O(catalog) scans inside `pg_get_tabledef`**: the
information_schema uppercase checks are replaced with direct regex tests
on the name in hand (preserving the original's `quote_ident` behavior
for schemas that need quoting), and the partial-index lookup is scoped
by the already-resolved table OID. Original statements are kept as
comments, matching the vendored file's convention.

**Regression guard** — so this bug class stays out:

- `test/db/stress-catalog.ts` builds a synthetic catalog (default 2,000
tables with PKs, unique + check constraints, FK chains and an FK hub;
`PG_META_STRESS_TABLES` scales it to incident size).
- `test/db/plan-guard.ts` provides `EXPLAIN (ANALYZE, FORMAT
JSON)`-based budget assertions: a query's plan may only seq-scan a
scaling catalog if its budget entry carries a written structural
justification (e.g. no index on `pg_constraint.confrelid`; no index on
`pg_class.relnamespace` for per-schema listings), plus a per-query time
bound (the only guard available for opaque plpgsql internals like
`pg_get_tabledef`).
- `test/sql/studio/catalog-plan-guard.test.ts` applies budgets to the
hot-path studio queries: table editor, constraints, FK listing, entity
types, tables-paginated, columns, indexes, table/entity definitions,
views. Reverting either fix makes the suite fail immediately with the
offending scans listed.
- `test/sql/studio/table-editor.test.ts` (new — none existed) asserts
the Table Editor query's semantics: primary keys, unique indexes, both
FK directions, `is_unique`, check definitions, column comments.
- A new package `README.md` documents the plan-guard budget entry as a
requirement for any new introspection query.

### Validation (synthetic 12,000-table catalog, PostgreSQL 17.6)

- **Output equivalence, fix 1:** for 12 relation types (regular,
composite PK, partitioned parent + partition, view, materialized view,
constraint-free table, FK hub/chain/tail, and a fixture with
enums/domains/generated/identity columns and duplicate check
constraints), the `entity` jsonb from the old and new query is
byte-identical.
- **Output equivalence, fix 2:** byte-identical DDL across 13 fixture
combinations (serial/identity/generated/array columns, case-sensitive
and keyword names, mixed-case schemas, partitions, unlogged +
reloptions, partial/expression indexes, external PK/FK/comments/trigger
variants).
- **Performance, fix 1:** Table Editor query `EXPLAIN ANALYZE` ~1,630ms
→ ~30ms (~50×); the gap grows with catalog size since the old query is
O(catalog) per call.
- **Performance, fix 2:** single entity definition 3,672ms → 63ms; a
100-entity definitions page ~6min → 0.87s. The plan-guard bound for
`getEntityDefinitionsSql` tightens accordingly from 15s/25 entities to
3s/100 entities (330ms measured at default test scale).

Verified locally: `catalog-plan-guard` (12 tests), `table-editor`,
`tables-paginated` (16 tests) pass; `typecheck` clean.

### Rollout

Per review, the new behavior ships **dark** behind the
`pgMetaScopedIntrospection` ConfigCat flag (default off = legacy SQL,
kept as full duplicated templates in pg-meta and verified byte-identical
to the pre-PR queries). Studio reads the flag in the query hooks and
threads it through (flag state is part of the React Query keys). The
rollout is staged in the ConfigCat dashboard via user-email targeting
(like every other ConfigCat flag): target the reporting user's email
first, then a percentage rollout, then 100%. Server-side AI callers of
`getEntityDefinitionsSql` stay on the legacy path. Once fully rolled
out, delete the legacy templates + flag in a cleanup PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Closes: PGMETA-122

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Bug Fixes**
- Improved table editor SQL to correctly scope primary keys, indexes,
uniques, checks, and relationships to the selected table.
- Optimized table definition SQL to reduce unnecessary catalog scanning
for uppercase-name detection and partial-index detection.

- **Tests**
- Added SQL generator tests for table editor metadata (keys, indexes,
relationships, comments, and constraints).
- Added catalog query plan guard coverage with a stress catalog and
EXPLAIN-based scoping/performance budgets.

- **Documentation**
- Expanded documentation on catalog query plan safeguards and how to
keep new introspection queries properly scoped.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 13:16:11 +02:00

4.2 KiB
Raw Permalink Blame History

@supabase/pg-meta

SQL builders for Postgres catalog introspection, shared by Supabase Studio and postgres-meta. Each builder in src/sql/ returns a safe, parameterized SQL fragment (SafeSqlFragment) that a caller executes against a user's live database to read schema metadata — tables, columns, constraints, indexes, relationships, entity definitions, and so on.

The studio/ subtree holds the queries the Studio dashboard runs on every page open (Table Editor, Database pages, entity lists, definitions).

Catalog query plan guard

Why this exists

These queries run against the user's live catalog, whose size we don't control. A real production catalog had ~267K pg_class rows. Before #47894, several CTEs in the Table Editor query were unscoped: they scanned pg_index/pg_constraint across the whole catalog regardless of which table was being opened. That turned a single Table Editor open into O(catalog) sequential scans — 3058s of work, tripping statement timeouts, on large catalogs.

The fix scoped those CTEs to the requested table OID. To keep that class of regression out for good, the package has a plan guard: a test suite that builds a large synthetic catalog and asserts, via EXPLAIN (ANALYZE, FORMAT JSON), that each hot-path query's plan stays scoped.

  • test/db/stress-catalog.ts — builds a synthetic stress schema (default 2000 tables, plus a view, a materialized view, and a partitioned table).
  • test/db/plan-guard.tsexplainAnalyze() + assertPlanWithinBudget() and the tolerated tiny-catalog set.
  • test/sql/studio/catalog-plan-guard.test.ts — one budget per covered query.

THE RULE for new queries

Every new introspection query added under src/sql/ that runs on a user's live catalog must get a budget entry in test/sql/studio/catalog-plan-guard.test.ts.

Sequential scans over catalogs that scale with schema sizepg_class, pg_attribute, pg_index, pg_constraint, pg_attrdef, pg_description, pg_depend, pg_policy, pg_trigger, pg_rewrite, … — are only acceptable with a written structural justification. An unscoped scan with no such justification is a bug: scope the query to the requested OID/schema so it uses an index instead.

How to add a budget entry

Run the query through the harness against the stress catalog and set a budget:

test('getMyNewSql: plan stays scoped', async () => {
  const result = await explainAnalyze(db, getMyNewSql({ id: someTableId }))
  assertPlanWithinBudget(result, {
    // Omit allowedSeqScans entirely for a per-object query that must be fully
    // index-scoped. Add an entry only for a structurally unavoidable scan:
    allowedSeqScans: {
      pg_constraint: {
        max: 2,
        reason: 'no index on pg_constraint.confrelid — incoming-FK lookup',
      },
    },
    maxExecutionTimeMs: 1000, // default; loosen only with a comment
  })
})

What's tolerated

  • Tiny, fixed-size catalogs (pg_namespace, pg_foreign_table, pg_foreign_server, pg_foreign_data_wrapper, pg_enum, pg_proc) are always tolerated. The planner full-scans them because they hold a handful of rows and don't grow with table count. See TINY_NON_SCALING_CATALOGS.
  • Justified structural scans on scaling catalogs — e.g. there is no index on pg_constraint.confrelid, so the incoming-FK half of a relationships lookup must seq scan; a per-schema listing can't prune pg_class because there is no index on relnamespace alone. Each such scan carries a reason string and a max node count.

Budget judgment:

  • Per-object queries (single id/table) allow no seq scans on scaling catalogs except structurally unavoidable ones (each with a reason).
  • Per-schema / list queries may need one structural scan (e.g. pg_class has no relnamespace-only index) — allow it with a reason and keep a time bound.

Reproduce at scale locally

The default of 2000 tables keeps CI fast. To investigate closer to real incident scale, crank the table count:

PG_META_STRESS_TABLES=12000 pnpm --filter @supabase/pg-meta test catalog-plan-guard