The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix(pg-meta): pair composite foreign key columns correctly (#41080)
Vaibhavc427615234ee
diff --git a/packages/pg-meta/src/sql/tables.ts b/packages/pg-meta/src/sql/tables.tsindex 88db7ce6784..f30796135db 100644--- a/packages/pg-meta/src/sql/tables.ts+++ b/packages/pg-meta/src/sql/tables.ts@@ -15,10 +15,10 @@ import { safeSql, type SafeSqlFragment } from '../pg-format'* the outgoing/incoming FK rows the unscoped query would have matched by name.** When `targetOid` is omitted the injected fragments are empty and the rendered- * SQL is the legacy full-catalog query -- `TABLES_SQL` below is exactly that- * rendering, so every existing consumer is unaffected. Behavioral equivalence- * between the scoped and unscoped forms is enforced by execution-based tests in- * test/tables.test.ts, not by a byte-for-byte SQL snapshot.+ * SQL is the full-catalog query used by existing consumers. Shared correctness+ * fixes belong in this builder so scoped and unscoped consumers stay+ * behaviorally equivalent; execution-based tests in test/tables.test.ts enforce+ * that equivalence.*/export const getTablesSql = (targetOid?: SafeSqlFragment) => {const mainScope = targetOid@@ -34,9 +34,9 @@ export const getTablesSql = (targetOid?: SafeSqlFragment) => {and (c.conrelid = ${targetOid} or c.confrelid = ${targetOid})`: safeSql``// Scoped path only: deterministic relationships order (plan-order dependent- // otherwise). A composite FK expands to one entry per source×target column- // pair sharing constraint_name, so tie-break on the column names. Empty for- // legacy, keeping TABLES_SQL byte-for-byte unchanged.+ // otherwise). A composite FK expands to one entry per ordinal column pair+ // sharing constraint_name, so tie-break on the column names. Empty for+ // unscoped consumers, preserving their existing plan-dependent order.const relOrder = targetOid? safeSql` order by relationships.constraint_name, relationships.source_column_name, relationships.target_column_name`: safeSql``@@ -103,16 +103,17 @@ FROMta.attname as target_column_namefrompg_constraint c+ cross join lateral unnest(c.conkey, c.confkey) with ordinality as cols(source_attnum, target_attnum, ord)join (pg_attribute sajoin pg_class csa on sa.attrelid = csa.oidjoin pg_namespace nsa on csa.relnamespace = nsa.oid- ) on sa.attrelid = c.conrelid and sa.attnum = any (c.conkey)+ ) on sa.attrelid = c.conrelid and sa.attnum = cols.source_attnumjoin (pg_attribute tajoin pg_class cta on ta.attrelid = cta.oidjoin pg_namespace nta on cta.relnamespace = nta.oid- ) on ta.attrelid = c.confrelid and ta.attnum = any (c.confkey)+ ) on ta.attrelid = c.confrelid and ta.attnum = cols.target_attnumwherec.contype = 'f'${relScope}) as relationships@@ -140,8 +141,7 @@ group by`}-// FROZEN legacy path: the unscoped rendering served while the-// pgMetaScopedIntrospection flag is off. Do not edit its shape -- it must keep-// matching production behavior until the flag cleanup deletes it. The scoped-// form is getTablesSql(targetOid) (used by tables.retrieve).+// Unscoped full-catalog rendering served while the pgMetaScopedIntrospection+// flag is off. Scope-specific changes belong behind targetOid; shared+// correctness fixes apply to both this path and scoped tables.retrieve.export const TABLES_SQL = getTablesSql()diff --git a/packages/pg-meta/test/db/stress-catalog.ts b/packages/pg-meta/test/db/stress-catalog.tsindex 7da50902084..f3e62fe618f 100644--- a/packages/pg-meta/test/db/stress-catalog.ts+++ b/packages/pg-meta/test/db/stress-catalog.ts@@ -27,10 +27,12 @@ export const STRESS_TABLE_COUNT = Number(* non-table relations (a view, a materialized view, and a partitioned table* with one partition) so relkind-filtering queries have something to hit.*- * Per table: a PK index, a unique constraint+index, a check constraint, and an- * FK to the previous table. Every 10th table also FKs to t_0, making t_0 a hub- * with many incoming FKs (the structurally unavoidable pg_constraint seq scan,- * since there is no index on pg_constraint.confrelid).+ * Per table: a composite PK index, a unique constraint+index, a check+ * constraint, and a composite FK to the previous table. Every 10th table also+ * has a composite FK to t_0, making t_0 a hub with many incoming FKs (the+ * structurally unavoidable pg_constraint seq scan, since there is no index on+ * pg_constraint.confrelid). Using composite FKs exercises ordinal column+ * pairing across the full stress catalog.** The catalog is built via a server-side procedure with batched commits every* 100 tables -- a single transaction creating thousands of tables/indexes/@@ -48,10 +50,10 @@ export async function buildStressCatalog(beginfor i in 0..n-1 loopexecute format(- 'create table stress.t_%s (id int primary key, u int unique, c int check (c > 0)%s%s)',+ 'create table stress.t_%s (id int, tenant_id int, u int unique, c int check (c > 0), primary key (id, tenant_id)%s%s)',i,- case when i > 0 then format(', fk int references stress.t_%s(id)', i - 1) else '' end,- case when i > 0 and i % 10 = 0 then ', hub int references stress.t_0(id)' else '' end+ case when i > 0 then format(', fk_id int, fk_tenant_id int, foreign key (fk_id, fk_tenant_id) references stress.t_%s(id, tenant_id)', i - 1) else '' end,+ case when i > 0 and i % 10 = 0 then ', hub_id int, hub_tenant_id int, foreign key (hub_id, hub_tenant_id) references stress.t_0(id, tenant_id)' else '' end);if i % 100 = 99 then commit; end if;end loop;diff --git a/packages/pg-meta/test/sql/studio/catalog-plan-guard.test.ts b/packages/pg-meta/test/sql/studio/catalog-plan-guard.test.tsindex beeb163d76b..a1a7b8f1098 100644--- a/packages/pg-meta/test/sql/studio/catalog-plan-guard.test.ts+++ b/packages/pg-meta/test/sql/studio/catalog-plan-guard.test.ts@@ -470,3 +470,27 @@ test('tables.retrieve: scoped plan stays scoped for a single table by name+schem)assertPlanWithinBudget(result, TABLES_RETRIEVE_BUDGET)}, 60_000)++test('tables.retrieve: scoped plan stays scoped for a composite-FK hub', async () => {+ const result = await explainAnalyze(db, tables.retrieve({ id: hubTableId, scoped: true }).sql)+ assertPlanWithinBudget(result, TABLES_RETRIEVE_BUDGET)+}, 60_000)++test('tables.retrieve: composite FKs stay ordinally paired at stress scale', async () => {+ const { sql, zod } = tables.retrieve({ id: midChainTableId, scoped: true })+ const row = zod.parse((await db.executeQuery(sql))[0])+ const chainRelationships = row.relationships.filter(+ ({ source_table_name, target_table_name }) =>+ source_table_name === 't_1000' && target_table_name === 't_999'+ )++ expect(+ chainRelationships.map(({ source_column_name, target_column_name }) => [+ source_column_name,+ target_column_name,+ ])+ ).toEqual([+ ['fk_id', 'id'],+ ['fk_tenant_id', 'tenant_id'],+ ])+}, 60_000)diff --git a/packages/pg-meta/test/tables.test.ts b/packages/pg-meta/test/tables.test.tsindex 49144fa4823..1a839694873 100644--- a/packages/pg-meta/test/tables.test.ts+++ b/packages/pg-meta/test/tables.test.ts@@ -38,7 +38,7 @@ const withTestDatabase = (name: string, fn: (db: TestDb) => Promise<void>) => {// Legacy relationships come out in plan-dependent order (frozen TABLES_SQL has// no ORDER BY; proven by the adversarial-FK test below), so canonicalize ONLY// the legacy side to the scoped ORDER BY: constraint_name, then the column names-// (a composite FK expands to one entry per source×target column pair).+// (a composite FK expands to one entry per ordinal column pair).const sortRels = (rels: any[]) =>[...rels].sort((a, b) =>@@ -145,31 +145,29 @@ withTestDatabase()// Composite (multi-column) FK: the relationships subquery expands it to one-// entry per source×target column pair, all sharing constraint_name, so the+// entry per ordinal column pair, all sharing constraint_name, so the// scoped ORDER BY tie-breaks on the column names to stay deterministic.withTestDatabase('scoped tables.retrieve orders composite-FK relationship entries deterministically',async ({ executeQuery }) => {await executeQuery(`create table public.ctgt (x int, y int, primary key (x, y));- create table public.csrc (a int, b int, foreign key (a, b) references public.ctgt (x, y));+ create table public.csrc (a int, b int, foreign key (b, a) references public.ctgt (x, y));`)const scoped = pgMeta.tables.retrieve({ name: 'csrc', schema: 'public', scoped: true })const legacy = pgMeta.tables.retrieve({ name: 'csrc', schema: 'public' })const scopedRow: any = scoped.zod.parse((await executeQuery(scoped.sql))[0])const legacyRow: any = legacy.zod.parse((await executeQuery(legacy.sql))[0])- // Four entries (2 source cols × 2 target cols), all one constraint_name.- expect(scopedRow.relationships).toHaveLength(4)+ // Two ordinal pairs, both sharing one constraint_name.+ expect(scopedRow.relationships).toHaveLength(2)expect(new Set(scopedRow.relationships.map((r: any) => r.constraint_name)).size).toBe(1)// Scoped is already ordered by (name, source col, target col), raw.expect(scopedRow.relationships.map((r: any) => [r.source_column_name, r.target_column_name])).toEqual([- ['a', 'x'],['a', 'y'],['b', 'x'],- ['b', 'y'],])legacyRow.relationships = sortRels(legacyRow.relationships)expect(scopedRow).toEqual(legacyRow)