AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Pg-Meta Composite Foreign Key Introspection Returns Cartesian Product Of Columns

pg-meta incorrectly introspects composite foreign keys by combining every source column with every target column instead of pairing them by ordinal position, leading to phantom relationships in metadata consumers.

highConfidence 95%Supabase/pg-Meta

Origin Analysis

The relationship introspection query joins source and target attributes using ANY(conkey) and ANY(confkey) independently without matching the array indices of pg_constraint.conkey and pg_constraint.confkey, causing PostgreSQL to produce a Cartesian product for composite foreign keys.
1. Create tables with a composite foreign key:\n```sql\nCREATE TABLE public.ctgt (x INT, y INT, PRIMARY KEY (x, y));\nCREATE TABLE public.csrc (a INT, b INT, FOREIGN KEY (a, b) REFERENCES public.ctgt (x, y));\n```\n2. Retrieve table metadata using pg-meta:\n```ts\nconst table = await pgMeta.tables.retrieve({ schema: "public", name: "csrc" });\nconsole.log(table.relationships);\n```\n3. Observe that the output contains four relationships (a->x, a->y, b->x, b->y) instead of the expected two (a->x, b->y).

Fixing Code Block

Edge Case Audit

This fix assumes the PostgreSQL version supports multi-array unnest with WITH ORDINALITY (available since 9.4). For older versions, a custom function using generate_subscripts would be required. Additionally, if conkey or confkey contain NULL or mismatched lengths (which should not happen for valid foreign keys), the unnest might produce unexpected rows; ensure constraints are valid before running. Rollback: if any regression occurs, revert to the original ANY() query, but note that the original query only manifests the bug for composite keys and does not cause crashes.

Ecosystem Topology