Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

fix(adapter-postgres): introspect composite index columns in index order (TML-2516) - #503

Merged
wmadden merged 1 commit into
mainfrom
tml-2516-bug-report-from-shane
May 14, 2026
Merged

wmadden merged 1 commit into
mainfrom
tml-2516-bug-report-from-shane

Conversation

@wmadden

@wmadden wmadden commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

prisma-next db init against a fresh database can fail its post-init verification with a spurious index_mismatch when the contract defines a composite index whose column order differs from the table's column declaration order. The runner applies the correct DDL — the index is created in the right order — but the subsequent re-introspection reads the columns back shuffled, so verification rejects a database it just built. Reported in TML-2516.

Root cause

The Postgres index introspection SQL in PostgresControlAdapter ordered (index, column) rows by a.attnum — each column's position within the table — instead of its position within the index. The JS loop then pushed attname values into SqlIndexIR.columns in whatever order they came back, so:

  • Table sync_run (id, started_at, source, entity) with CREATE INDEX … ON sync_run (source, entity, started_at)
  • Introspection returned [started_at, source, entity] (table order)
  • verifyIndexes calls arraysEqual(idx.columns, contractIndex.columns) (order-sensitive)
  • Result: Table "sync_run" is missing index: source, entity, started_at even though the index exists with exactly those columns

PK / FK / unique constraint queries weren't affected because they correctly order by information_schema.key_column_usage.ordinal_position (the column's position within the constraint). The bug was Postgres-specific; SQLite uses PRAGMA index_info and already sorts by seqno.

Fix

Read the per-index column position from pg_index.indkey via LATERAL unnest(ix.indkey::int[]) WITH ORDINALITY and order by that ordinal. The JS code is unchanged — once the rows come back in index order, push-ing them yields the correct SqlIndexIR.columns.

Why the existing tests didn't catch it

The unit tests in control-adapter.test.ts feed the mock driver pre-ordered rows, so the ORDER BY clause was never exercised. The existing integration tests for index introspection only covered single-column indexes (and metadata like type / options), so no fixture had a composite index whose index order differed from the table order.

Test plan

  • New integration test reports composite index columns in index order, not table order in packages/3-targets/6-adapters/postgres/test/migrations/index-introspection.integration.test.ts — creates sync_run with the bug-report shape and asserts idx.columns === ['source', 'entity', 'started_at']. Pre-fix it failed with [started_at, source, entity]; post-fix it passes.
  • All 5 tests in that file pass.
  • All 47 tests in control-adapter.test.ts pass (existing multi-column index mocks updated from attnum to index_position to match the new query shape).
  • pnpm typecheck / pnpm build / pnpm lint clean for @prisma-next/adapter-postgres.

Out of scope (noted, not fixed)

  • The summary Database schema does not satisfy contract (3 failures) vs Issues (showing 1 of 1) mismatch is a UI artifact (count of failing tree nodes vs count of issues in the flat list). Worth tightening separately; not the root cause here.
  • The DeprecationWarning: Calling client.query() when the client is already executing a query from pg is unrelated noise.

Summary by CodeRabbit

  • Bug Fixes

    • PostgreSQL index introspection now preserves the column order of composite indexes, preventing order-sensitive mismatches during schema verification.
  • Tests

    • Added/updated tests to ensure composite index column ordering is correctly detected and maintained during introspection.

Review Change Stack

@wmadden
wmadden requested a review from a team as a code owner May 14, 2026 13:35
@pkg-pr-new

pkg-pr-new Bot commented May 14, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/mongo-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-runtime@503

@prisma-next/family-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-mongo@503

@prisma-next/sql-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-runtime@503

@prisma-next/family-sql

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-sql@503

@prisma-next/extension-arktype-json

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-arktype-json@503

@prisma-next/extension-cipherstash

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-cipherstash@503

@prisma-next/middleware-telemetry

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/middleware-telemetry@503

@prisma-next/mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo@503

@prisma-next/extension-paradedb

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-paradedb@503

@prisma-next/extension-pgvector

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-pgvector@503

@prisma-next/extension-postgis

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-postgis@503

@prisma-next/postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/postgres@503

@prisma-next/sql-orm-client

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-orm-client@503

@prisma-next/sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sqlite@503

@prisma-next/target-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-mongo@503

@prisma-next/adapter-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-mongo@503

@prisma-next/driver-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-mongo@503

@prisma-next/contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract@503

@prisma-next/utils

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/utils@503

@prisma-next/config

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/config@503

@prisma-next/errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/errors@503

@prisma-next/framework-components

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/framework-components@503

@prisma-next/operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/operations@503

@prisma-next/ts-render

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ts-render@503

@prisma-next/contract-authoring

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract-authoring@503

@prisma-next/ids

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ids@503

@prisma-next/psl-parser

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-parser@503

@prisma-next/psl-printer

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-printer@503

@prisma-next/cli

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/cli@503

@prisma-next/emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/emitter@503

@prisma-next/migration-tools

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/migration-tools@503

prisma-next

npm i https://pkg.pr.new/prisma/prisma-next@503

@prisma-next/vite-plugin-contract-emit

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/vite-plugin-contract-emit@503

@prisma-next/mongo-codec

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-codec@503

@prisma-next/mongo-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract@503

@prisma-next/mongo-value

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-value@503

@prisma-next/mongo-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-psl@503

@prisma-next/mongo-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-ts@503

@prisma-next/mongo-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-emitter@503

@prisma-next/mongo-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-schema-ir@503

@prisma-next/mongo-query-ast

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-ast@503

@prisma-next/mongo-orm

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-orm@503

@prisma-next/mongo-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-builder@503

@prisma-next/mongo-lowering

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-lowering@503

@prisma-next/mongo-wire

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-wire@503

@prisma-next/sql-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract@503

@prisma-next/sql-errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-errors@503

@prisma-next/sql-operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-operations@503

@prisma-next/sql-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-schema-ir@503

@prisma-next/sql-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-psl@503

@prisma-next/sql-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-ts@503

@prisma-next/sql-contract-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-emitter@503

@prisma-next/sql-lane-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-lane-query-builder@503

@prisma-next/sql-relational-core

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-relational-core@503

@prisma-next/sql-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-builder@503

@prisma-next/target-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-postgres@503

@prisma-next/target-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-sqlite@503

@prisma-next/adapter-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-postgres@503

@prisma-next/adapter-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-sqlite@503

@prisma-next/driver-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-postgres@503

@prisma-next/driver-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-sqlite@503

commit: 611b64c

@coderabbitai

coderabbitai Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: ad3c48ad-7765-4ce8-99c2-df9411dbb540

📥 Commits

Reviewing files that changed from the base of the PR and between 723ced8 and 611b64c.

📒 Files selected for processing (3)
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/postgres/test/control-adapter.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/index-introspection.integration.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/3-targets/6-adapters/postgres/test/control-adapter.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts

📝 Walkthrough

Walkthrough

The Postgres adapter's index introspection now preserves composite index column order using SQL's WITH ORDINALITY to derive position from the index definition. The core query, unit test mocks, and a new integration test are aligned to ensure columns appear in index-definition order rather than table attribute order.

Changes

Composite Index Column Order Preservation

Layer / File(s) Summary
Index introspection query with ordinal positioning
packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
The PostgresControlAdapter.introspect query now unnests pg_index.indkey with WITH ORDINALITY to compute ordinal position, joins pg_attribute by that position, and orders results by ordinal to preserve composite index column order when building SqlIndexIR.
Unit test mock updates for index_position field
packages/3-targets/6-adapters/postgres/test/control-adapter.test.ts
Three unit tests update mocked pg_indexes rows to use index_position instead of attnum: single-column indexes, multi-column indexes, and the null attname skipping case all align with the new query shape.
Composite index column order regression test
packages/3-targets/6-adapters/postgres/test/migrations/index-introspection.integration.test.ts
New integration test creates a composite index and asserts that introspected columns match the index definition order (source, entity, started_at) rather than table layout order.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Composite columns, once in a tangle,
Now skip and unnest at the perfect angle,
ORDINALITY brings order divine,
Index columns align, just fine! 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main fix: resolving composite index column introspection to use index order rather than table column order, directly addressing the root cause of the TML-2516 bug.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2516-bug-report-from-shane

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts (1)

367-378: ⚡ Quick win

Align LATERAL alias naming with repo SQL guideline

Line 377 aliases the LATERAL source as k; please switch to the {alias}_lateral pattern and reference columns via that alias in Line 367 and Line 387 for consistency with the adapter SQL style rules.

Suggested diff
-           k.ord AS index_position,
+           index_key_lateral.index_position AS index_position,
@@
-         JOIN LATERAL unnest(ix.indkey::int[]) WITH ORDINALITY AS k(attnum, ord) ON true
-         LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum AND a.attnum > 0
+         JOIN LATERAL unnest(ix.indkey::int[]) WITH ORDINALITY
+           AS index_key_lateral(attnum, index_position) ON true
+         LEFT JOIN pg_attribute a
+           ON a.attrelid = t.oid
+          AND a.attnum = index_key_lateral.attnum
+          AND a.attnum > 0
@@
-         ORDER BY i.tablename, i.indexname, k.ord`,
+         ORDER BY i.tablename, i.indexname, index_key_lateral.index_position`,

As per coding guidelines: “When using LATERAL joins in PostgreSQL adapters, use different aliases for the table alias and column alias: table alias as {alias}_lateral, column alias as {alias}, and select using table_alias.column_alias.”

Also applies to: 387-387

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts` around
lines 367 - 378, Rename the LATERAL alias from k to k_lateral and update all
uses to follow the repo pattern: change "LATERAL unnest(ix.indkey::int[]) WITH
ORDINALITY AS k(attnum, ord)" to "AS k_lateral(attnum, ord)", change the select
"k.ord AS index_position" to "k_lateral.ord AS index_position", and update the
pg_attribute join predicate "a.attnum = k.attnum" to "a.attnum =
k_lateral.attnum" (also update any other k.* references, e.g., k.ord, to
k_lateral.*).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts`:
- Around line 367-378: Rename the LATERAL alias from k to k_lateral and update
all uses to follow the repo pattern: change "LATERAL unnest(ix.indkey::int[])
WITH ORDINALITY AS k(attnum, ord)" to "AS k_lateral(attnum, ord)", change the
select "k.ord AS index_position" to "k_lateral.ord AS index_position", and
update the pg_attribute join predicate "a.attnum = k.attnum" to "a.attnum =
k_lateral.attnum" (also update any other k.* references, e.g., k.ord, to
k_lateral.*).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: f62036f7-3449-4571-8355-3ba23fb16e18

📥 Commits

Reviewing files that changed from the base of the PR and between 655d794 and 723ced8.

📒 Files selected for processing (3)
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/postgres/test/control-adapter.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/index-introspection.integration.test.ts

…der (TML-2516)

The Postgres index introspection SQL ordered the (index, column) rows
by `a.attnum` — the column's position within the *table* — instead of
its position within the *index*. For any composite index whose column
order in the index definition differs from the table column order, the
resulting `SqlIndexIR.columns` came back shuffled. Schema verification
compares against the contract using order-sensitive equality and
reported a spurious `index_mismatch`, breaking `prisma-next db init`
postcondition checks on a fresh database.

Switch to `unnest(ix.indkey) WITH ORDINALITY` so each row carries its
position within the index, and order by that. Add an integration
regression where the index column order (source, entity, started_at)
differs from the table column order (started_at, source, entity); pre-
fix the test reports `[started_at, source, entity]`.

Signed-off-by: Will Madden <[email protected]>
@wmadden
wmadden force-pushed the tml-2516-bug-report-from-shane branch from 723ced8 to 611b64c Compare May 14, 2026 14:01
@wmadden
wmadden merged commit bfcb8e9 into main May 14, 2026
16 checks passed
@wmadden
wmadden deleted the tml-2516-bug-report-from-shane branch May 14, 2026 14:05
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant