Repository navigation
fix(adapter-postgres): introspect composite index columns in index order (TML-2516) - #503
Conversation
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/extension-cipherstash
@prisma-next/middleware-telemetry
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughThe Postgres adapter's index introspection now preserves composite index column order using SQL's ChangesComposite Index Column Order Preservation
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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
ESLint skipped: no ESLint configuration detected in root package.json. To enable, add Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts (1)
367-378: ⚡ Quick winAlign LATERAL alias naming with repo SQL guideline
Line 377 aliases the LATERAL source as
k; please switch to the{alias}_lateralpattern 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 usingtable_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
📒 Files selected for processing (3)
packages/3-targets/6-adapters/postgres/src/core/control-adapter.tspackages/3-targets/6-adapters/postgres/test/control-adapter.test.tspackages/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]>
723ced8 to
611b64c
Compare
Summary
prisma-next db initagainst a fresh database can fail its post-init verification with a spuriousindex_mismatchwhen 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
PostgresControlAdapterordered(index, column)rows bya.attnum— each column's position within the table — instead of its position within the index. The JS loop then pushedattnamevalues intoSqlIndexIR.columnsin whatever order they came back, so:sync_run (id, started_at, source, entity)withCREATE INDEX … ON sync_run (source, entity, started_at)[started_at, source, entity](table order)verifyIndexescallsarraysEqual(idx.columns, contractIndex.columns)(order-sensitive)Table "sync_run" is missing index: source, entity, started_ateven though the index exists with exactly those columnsPK / 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 usesPRAGMA index_infoand already sorts byseqno.Fix
Read the per-index column position from
pg_index.indkeyviaLATERAL unnest(ix.indkey::int[]) WITH ORDINALITYand order by that ordinal. The JS code is unchanged — once the rows come back in index order,push-ing them yields the correctSqlIndexIR.columns.Why the existing tests didn't catch it
The unit tests in
control-adapter.test.tsfeed the mock driver pre-ordered rows, so theORDER BYclause was never exercised. The existing integration tests for index introspection only covered single-column indexes (and metadata liketype/options), so no fixture had a composite index whose index order differed from the table order.Test plan
reports composite index columns in index order, not table orderinpackages/3-targets/6-adapters/postgres/test/migrations/index-introspection.integration.test.ts— createssync_runwith the bug-report shape and assertsidx.columns === ['source', 'entity', 'started_at']. Pre-fix it failed with[started_at, source, entity]; post-fix it passes.control-adapter.test.tspass (existing multi-column index mocks updated fromattnumtoindex_positionto match the new query shape).pnpm typecheck/pnpm build/pnpm lintclean for@prisma-next/adapter-postgres.Out of scope (noted, not fixed)
Database schema does not satisfy contract (3 failures)vsIssues (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.DeprecationWarning: Calling client.query() when the client is already executing a queryfrompgis unrelated noise.Summary by CodeRabbit
Bug Fixes
Tests