Repository navigation
fix(pg-meta): order primary key columns by key position and exclude INCLUDE columns - #382
Merged
Merged
Conversation
…ey-order # Conflicts: # packages/mcp-server-supabase/src/server.test.ts
Collaborator
|
I pushed two commits to your branch:
The SQL logic is unchanged. Both cases still fail on main and pass here. |
mattrossman
approved these changes
Oct 26, 2026
Collaborator
|
(tests failing in CI is expected due to lack of secrets in your fork, I ran locally and they behave normally) |
barryroodt
approved these changes
Oct 26, 2026
Merged
4 tasks
mattrossman
added a commit
that referenced
this pull request
Oct 28, 2026
array_agg in coalesceRowsToArray followed heap scan order, which is not guaranteed. ALTER COLUMN rewrites a column's pg_attribute row and moves it to the end of the heap, so list_tables could return columns out of order. Add an optional orderBy argument to coalesceRowsToArray and use columns.ordinal_position when building the table columns. Adds a test that alters columns and checks the order stays the same. ## What kind of change does this PR introduce? Bug fix ## What is the current behavior? Fixes #496 `list_tables` (verbose) builds each table's `columns` with `array_agg(row_to_json(columns))` and no `ORDER BY`, so the order follows `pg_attribute` scan order. `ALTER COLUMN ... SET NOT NULL` / `SET DEFAULT` / `TYPE` write a new `pg_attribute` row version at the end of the heap, so that column is returned last. `ordinal_position` is stripped from the output, so the agent can't recover the real order. ## What is the new behavior? Columns are returned in `ordinal_position` order. `coalesceRowsToArray` takes an optional `orderBy`, and `listTablesSql` passes `columns.ordinal_position`. When `orderBy` is omitted, the generated SQL is unchanged. No change to tool names, descriptions, input/output schemas or output shape. This is a server-only fix, so the published `tools/list` contract is untouched. ## How to Review <!-- A reviewer should understand what this PR does within 15-30 seconds, then know where to start reading. Non-trivial or multi-file PRs must fill in the reading path below. Trivial single-file changes may delete this section when the review path is obvious. - Start from the main public entrypoint or request handler, and follow the actual execution path before reading tests. - Use bold numbered areas, each with one or two indented bullets: the exact files, then what to inspect. - Use exact repository-relative paths, and avoid line numbers while the branch is still changing. - Prefer project-facing language such as `interface`, `extension point`, or `contract` over internal design jargon. - Don't repeat the PR purpose or the verification commands here. Keep the section scannable. --> 1. **Column aggregation** - `packages/mcp-server-supabase/src/pg-meta/index.ts` - `coalesceRowsToArray` gains an optional `orderBy` placed inside `array_agg(...)` before `FILTER`. `listTablesSql` is its only caller. 2. **Tests** - `packages/mcp-server-supabase/src/server.database.test.ts` - `list tables returns columns in ordinal position order after ALTER COLUMN` checks the observable column order from the `list_tables` tool after the ALTERs that reorder the heap. **Review questions** <!-- Four to six short questions covering the reviewer's judgment calls. --> - [ ] Is the public contract minimal and intentional? - [ ] Do the main execution paths preserve existing behavior? - [ ] Do failures stop safely? - [ ] Do tests protect observable behavior rather than implementation details? ## Verification - Regression test without the fix fails: ``` × tools > list tables returns columns in ordinal position order after ALTER COLUMN - Expected + Received Array [ - "id", - "email", "name", "age", + "email", + "id", ] ``` - With the fix it passes. - `pnpm --filter @supabase/mcp-server-supabase test:unit --run`: 34 files, 736 tests passed. - `pnpm --filter @supabase/mcp-server-supabase test:integration --run` (stdio, after a fresh build): 7/7 passed. - `biome check`, `tsc --noEmit` and the package build are clean. I reviewed the diff and ran the tests above locally. ## Additional context Same class of issue as #381 / #382 (primary key column order). --------- Co-authored-by: Matt Rossman <[email protected]>
Rodriguespn
pushed a commit
that referenced
this pull request
Oct 29, 2026
🤖 I have created a release *beep* *boop* --- <details><summary>mcp-server-supabase: 0.15.0</summary> ## [0.15.0](mcp-server-supabase-v0.14.0...mcp-server-supabase-v0.15.0) (2026-10-29) ### Features * `submit_feedback` and `delete_feedback` tools ([#474](#474)) ([f50318a](f50318a)) * mark client-caused tool errors as ToolCallerError ([#480](#480)) ([4a619c1](4a619c1)) * **mcp-server-supabase:** detect instant elicitation cancels ([#483](#483)) ([5ad1a2a](5ad1a2a)) ### Bug Fixes * **mcp-server-supabase:** return a tool error when a confirmation expires ([#490](#490)) ([5ab9a98](5ab9a98)) * **mcp-server-supabase:** use POSIX path resolution for edge function filenames ([#393](#393)) ([55d2d24](55d2d24)) * **mcp:** don't split an UPDATE on a semicolon inside a dollar-quoted value ([#482](#482)) ([9f07410](9f07410)) * **mcp:** don't split an UPDATE on a semicolon inside a quoted value ([#459](#459)) ([6d93b50](6d93b50)) * **pg-meta:** order list_tables columns by ordinal position ([c242e63](c242e63)) * **pg-meta:** order primary key columns by key position and exclude INCLUDE columns ([#382](#382)) ([25d357c](25d357c)) </details> --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). Co-authored-by: supabase-releaser[bot] <223506987+supabase-releaser[bot]@users.noreply.github.com>
4 tasks
barryroodt
pushed a commit
that referenced
this pull request
Nov 4, 2026
…tables (#508) Closes #507 ## What kind of change does this PR introduce? Bug fix, plus an optional `partition_of` output field. ## What is the current behavior? `list_tables` reports the FK clones Postgres creates for partitions as separate foreign keys, so one FK is listed once per partition. Nothing in the output marks a partition's parent. ## What is the new behavior? The relationships subquery filters `conparentid = 0`, the predicate `pg_dump` uses, so each FK is reported once. FKs declared directly on a partition are still reported. Partitions carry `partition_of`, their immediate parent in the same `schema.name` format as `name`, in both compact and verbose output: ```jsonc { "name": "public.events_2025", "rls_enabled": false, "rows": 0, "partition_of": "public.events" } ``` A sub-partition points to its own parent, not the root. Other tables omit the field, including `INHERITS` children. A partition still names its parent when the parent's schema isn't in `schemas`, as `target_table` already does. No change to tool names, descriptions or input schemas. `partition_of` is optional in the output schema. Databases without partitioned tables get identical output. ## How to Review 1. **Query** - `packages/mcp-server-supabase/src/pg-meta/tables.sql` - One predicate in the relationships subquery. `conparentid` rather than `relispartition`, which would also hide FKs declared on or pointing at a partition. - One scalar subquery for `partition_of`. It filters the parent on `relkind = 'p'`, because `INHERITS` children also have `pg_inherits` rows. 2. **Output** - `packages/mcp-server-supabase/src/pg-meta/types.ts`, `packages/mcp-server-supabase/src/tools/database-operation-tools.ts` - `partition_of` is omitted when null, like `comment`. 3. **Tests** - `packages/mcp-server-supabase/src/server.database.test.ts`, next to the composite-FK tests: - Clones on both sides of an FK are dropped, while an FK declared on a partition is kept. - `partition_of` in both modes for a root, a partition, a sub-partition, a partition in another schema, an `INHERITS` parent and its child. **Review questions** - [ ] Is the immediate parent, rather than the root, what you want in `partition_of`? - [ ] Is the public contract minimal and intentional? - [ ] Do the main execution paths preserve existing behavior? - [ ] Do tests protect observable behavior rather than implementation details? ## Verification Without the fix, the FK test fails (trimmed): ``` × tools > partition clones of an FK are not reported as separate constraints AssertionError: expected [ { …(5) }, { …(5) }, { …(5) } ] to deeply equal [ { …(5) } ] + "name": "order_items_order_id_fkey1", + "target_table": "public.orders_p0", + "name": "order_items_order_id_fkey2", + "target_table": "public.orders_p1", ``` Without `partition_of`, the `partition_of` test fails with `expected undefined to be 'public.events'`. It also fails if `INHERITS` children are marked, if `partition_of` points to the root, or if it uses the partition's schema instead of the parent's. With the fix, the CI steps pass locally: - `biome ci .`: clean - Management API types regenerated: no diff - `pnpm run build` and `pnpm run test:packed-platform-consumer`: 3/3 - `vitest --coverage --project unit --project integration`: 752 passed - `typecheck`: clean - `tables.sql` on PostgreSQL 15.19 and 17.11 with the schema from #507, plus sub-, default and cross-schema partitions, a detached partition and `INHERITS` children: each FK reported once, `partition_of` set only on partitions The `test` job's 5 e2e tests need `ANTHROPIC_API_KEY`, which fork PRs don't receive (same as #382 and #497). I reviewed the diff and ran the checks above locally. I used AI tooling while developing it. ## Additional context Same class of fix as #382 and #497. `partition_of` follows the suggestion in #507.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #381
What kind of change does this PR introduce?
Bug fix: data-integrity issue in
list_tables(verbose) primary key output.What is the current behavior?
primary_keysis sorted by each column's physical position in the table rather than its position in the key, and it includes the non-keyINCLUDEpayload columns of the backing index.membership(user_id, org_id)["org_id","user_id"]inc(a) INCLUDE (b)["a","b"]Root cause in
pg-meta/tables.sql:a.attnum = any (i.indkey)is a set-membership test, so each column's position within the key is discarded and the enclosingjsonb_agghas noorder by.indkeyalso spansindnatts, which includes theINCLUDEpayload, rather thanindnkeyatts.This is the same defect #317 fixed in the foreign key subquery immediately below, which walks columns with
unnest(...) with ordinalityand aggregatesorder by cols.ord. The primary key subquery was not updated at the time.What is the new behavior?
indkeyis unnestedwith ordinalityand the aggregate is ordered by that ordinal, so columns come back in constraint-definition order - not attnum, not alphabetical.indnkeyatts, soINCLUDEpayload columns are excluded.to_jsonb(_pk) - 'ord'emits exactly the same keys as before.= any (indkey)is wrong, so it doesn't get "simplified" back.Two regression tests, both using a key order that is deliberately the reverse of the physical column order so any regression to attnum ordering fails immediately - the same shape as the FK ordering test added in #317.
Verification
Windows 11, Node 22 LTS, pnpm 10:
Both new tests pass:
The 5 failures are pre-existing and unrelated to this change. They are all
normalizeFilename:edge-function.tsimportsresolvefromnode:path, which is platform-dispatched, but strips a hardcoded POSIX prefix (/tmp/user_fn_.../), so on Windows the strip never matches and the fullC:\tmp\...path is returned. 3 direct failures inedge-function.test.tsplus 2 downstream inserver.test.ts(list edge functions,get edge function). I confirmed the identical 5 failures on cleanupstream/mainwith nothing applied, so they are the baseline, not a regression. Happy to file that separately -node:path/posixlooks like the one-line fix, and every caller already forces POSIX semantics withfileURLToPath(..., { windows: false }).End to end against a real MCP client and server (
createSupabaseMcpServeroverStreamTransport, PostgreSQL 16.4 via PGlite), callinglist_tableswithverbose: true:Single-column primary keys and the composite foreign key output from #317 are unchanged on both builds.
On whether this actually misleads a model
I tested it rather than asserting it, and the result is mostly negative, so it's worth stating plainly: across 18 runs (3 models × 3 questions × before/after, one replicate per cell) 17 answered correctly on both builds. Models generally did not trust
primary_keys- 17 of 18 runs calledexecute_sqland readpg_index/pg_constraintdirectly. Two runs spontaneously flagged the output as wrong, e.g. "list_tables reports the primary key as ["a","b"], which is misleading: it lumps the INCLUDE column in with the real key column."The one failure was a weaker model on "what's the primary key on membership?" against the unfixed build, which answered
org_id, user_id. Notably its own verification query usedinformation_schema.key_column_usagewithoutorder by ordinal_position, so it confirmed the wrong answer.So the case for this fix is not "agents give wrong answers". It's that
primary_keyscontradicts the database, that models are paying for a catalog round-triplist_tablesexists to save, and that a non-agent consumer of the published package has no fallback at all.What I did not test
indnkeyattsrequires PG 11+.list_tablesmore than these did.