Repository navigation
Duplicate index and foreign-key names refused at authoring; SqlLoweringSpec drops its unread strategy field - #30373
Conversation
…weringSpec drops its unread strategy field
The sql() stage of the TypeScript contract builder has always carried a type-level check that refuses a model whose named storage objects reuse a literal name. It never fired for constraints.index, constraints.foreignKey or the Postgres fullTextIndex helper, because each helper's Name type parameter widened to string once the call sat inside sql()'s contextually typed spec. The check compared string against string and found no duplicates.
Declaring Name as a const type parameter on those signatures keeps the literal, so the existing check now works: two indexes named the same, an index reusing the primary key name, two foreign keys named the same, and a fullTextIndex colliding with a constraints.index all resolve to a builder whose sql spec is never. Type tests in sql-contract-ts and the Postgres extension pin both the rejections and the accepted distinct-name case.
SqlLoweringSpec.strategy ('infix' | 'function') was set by every operation descriptor and read by nothing; the template alone drives lowering. The field is removed from the interface and from every descriptor, test and ADR example that set it. An upgrade fragment for extension authors records the deletion.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository: prisma/orm/.coderabbit.yml Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (38)
💤 Files with no reviewable changes (20)
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review. 📝 WalkthroughWalkthroughChangesSQL contract and lowering updates
Priority: ➖ Normal Estimated code review effort: 3 (Moderate) | ~25 minutes Change: Bug fix Suggested reviewers: Merge Risk: ⚪ Minimal · up to Duplicate constraint names are rejected during authoring, while SQL rendering retains its existing templates after removing unused metadata. The change is mergeable with normal checks. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 17 files. (1 skipped: 1 unsupported.)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Comment |
@prisma/orm-extension-arktype-json
@prisma/orm-extension-middleware-cache
@prisma/orm-extension-paradedb
@prisma/orm-extension-pgvector
@prisma/orm-extension-postgis
@prisma/orm-extension-supabase
@prisma/orm-family-mongo
@prisma/orm-family-sql
@prisma/orm-framework
@prisma/orm-mongo
@prisma/orm-postgres
@prisma/orm-sqlite
@prisma/orm-target-mongo
@prisma/orm-target-postgres
@prisma/orm-target-sqlite
@prisma/orm-toolchain
commit: |
size-limit report 📦
|
…in the duplicate-name check (prisma#30387) ## Linked issue n/a — small change. Completes the consistency fix [prisma#30373](prisma#30373) started for indexes and foreign keys. ## Skill update n/a — internal only. No new API; a mistake that already should have been a type error now is one. ## At a glance ```ts model('User', { fields }).attributes(({ fields, constraints }) => ({ uniques: [constraints.unique([fields.email], { name: 'user_email_key' })], })).sql(({ cols, constraints }) => ({ table: 'user', indexes: [constraints.index([cols.email], { name: 'user_email_key' })], })); // before: typechecks. after: defineContract reports that two named objects share a name. ``` ## Decision Every named storage object on a model now takes part in the type-level duplicate-name check, and a clash is now a compile error at `defineContract`: 1. **All name sources are compared.** The primary key (inline or in `.attributes()`), uniques (inline `.unique({ name })`, `field.sql({ unique })`, named presets, and `.attributes()`), indexes and foreign keys in `.sql()`, and foreign keys declared on relations with `belongsTo(...).sql({ fk: { name } })`. `constraints.unique` and `constraints.id` gain a `const Name` type parameter so their names stay literal. Names are grouped by where they come from, so two fields or two relations reusing a name are caught, not merged in a union. 2. **The check now reaches the user.** Before this PR, a clash resolved the model builder's spec to `never`, but `defineContract` accepted such a model, so no error was ever shown. `ContractModelBuilder` now carries a type-only `__duplicateNames` property, and every model entry point requires it to be `undefined`. A clash reports: "two ids, uniques, indexes or foreign keys on this model have the same name". This also covers clashes no stage call sees, such as duplicate inline names on a model with no `.sql()` call. ## Reviewer notes - **`.attributes()` now validates on its return type, like `.sql()`.** It used to validate its input. With the check on the input, TypeScript could not infer the factory's result after `.sql()` had run, so no attributes-stage name reached the check in that order. A clash there used to surface as a call-site error; it now resolves the attributes spec to `never`, which is how `.sql()` has always reported it. - **One shared check.** `ValidateSqlStageSpec` and `ValidateAttributesStageSpec` both call `HasDuplicateModelNames`, so the two stages cannot disagree about what counts as a clash. - **No runtime effect.** Authored names are wire-name prefixes with a content hash appended, so a reused name never produced a physical collision. This catches a copy-paste mistake at authoring time. - **prisma#30373 claimed `defineContract` rejected a model whose spec was `never`. It did not.** A review comment here caught it; `@ts-expect-error` tests on `defineContract` were all reported unused before this PR's second commit. So the check had never produced a visible error until now. - **This can surface a new compile error in an app** whose contract really does reuse a name. No example or fixture in the repo does; `pnpm typecheck` over all examples passes. - **`check({ name })` and index `map:` are not in the check.** Both are typed `string`, so they carry no literal. The runtime validator already rejects duplicate `map:` names. ## Testing performed - `packages/2-sql/2-authoring/contract-ts`: `pnpm typecheck`, `pnpm lint`, `pnpm test` pass. Every new type test and `@ts-expect-error` case was red before the change. - Examples: `pnpm typecheck --filter='./examples/**'` passes. - `pnpm typecheck:packages --concurrency=1`: pass. The parallel run is flaky on `integration-tests` for a reason unrelated to this change; see below. - `pnpm check:upgrade-coverage --mode pr --prev main --head HEAD`: pass. ## Follow-ups - `integration-tests#typecheck` typechecks `test/cli-journeys/**`, which imports `@prisma/orm-postgres`, but `integration-tests` declares no dependency on that package. Turbo therefore has no edge and can run the typecheck while tsdown is rewriting the package's `dist`, giving spurious `TS2307 Cannot find module '@prisma/orm-postgres/…'` errors. The fix is a declared dependency from `integration-tests` to `@prisma/orm-postgres`. ## Checklist - [x] All commits are signed off (`git commit -s`) per the [DCO](../CONTRIBUTING.md#developer-certificate-of-origin-dco). - [x] I read [CONTRIBUTING.md](../CONTRIBUTING.md) and the change is scoped to one logical concern. - [x] Tests are updated. - [ ] The PR title is in `TML-NNNN: <sentence-case title>` form — no ticket. - [x] The **Skill update** section above is filled in. ## Notes for the reviewer See **Reviewer notes** above. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Duplicate names are now detected across unique constraints, primary keys, indexes, and foreign keys, regardless of authoring stage. * Checks include names declared inline on fields and relations, as well as names declared in attributes and SQL stages. * Duplicate-name errors are surfaced through type checking in model builders and contract definitions. Distinct names remain valid across stages. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Linked issue
n/a — follow-ups from #30348, which has no Linear ticket. Reviewer: if a ticket exists, add it to the title.
Skill update
n/a — no user-facing surface changes.
fullTextIndexandconstraints.indexkeep their signatures; the only visible difference is a type error that was always documented and never fired.SqlLoweringSpec.strategyis an extension-author surface; the deletion is recorded inupgrade-instructions/pending/sql-lowering-spec-drops-strategy/extension/instructions.md.At a glance
Before this PR that model typechecked. The
sql()stage's duplicate-name check existed, but every name it compared had already widened tostring.Decision
Two follow-ups from the full-text search PR, both small:
sql()stage was always meant to do. The fix isconst Nameon theconstraints.index,constraints.foreignKeyandfullTextIndexsignatures, so the literal survives contextual typing insidesql().SqlLoweringSpec.strategyis deleted. Nothing read it. The template alone drives lowering.Reviewer notes
ValidateSqlStageSpec. The follow-up note from Postgres full-text search operations and a typed @@fullTextIndex, owned by the target pack #30348 guessed the check failed becauseIndexConstraint.nameis optional. It is not:NamedConstraintLiteralNamealready stripsundefined. The real cause is thatconstraints.index(..., { name: 'x' })insidesql(callback)orsql({...})is contextually typed bySqlStageSpec, whoseindexesareIndexConstraint<readonly string[], string | undefined>, and that return-type inference widenedNametostring. Aconsttype parameter stops the widening. The same thing happened tofullTextIndex, whose own test-d file had documented the check as dead. That comment is gone and the file now asserts the rejections.nameis a wire-name prefix; the storage validator compares wire names after the content hash is appended, so two indexes with the same prefix but different columns get different physical names. The type-level check is the only place a reused authored name is refused.map:duplicates are exact physical names and the runtime validator already rejects them.uniquenames are still not covered.constraints.uniquehas noNametype parameter at all, so a unique constraint reusing an index name passes the type check. Out of scope here; noted as a follow-up.strategydeletion touches 30 files but is one mechanical edit: the field is removed from the interface, from every descriptor literal, from tests that set or asserted it, and from the ADR 203 example.git diff --statis the whole story.packages/2-sql/1-core/contract/src/validators.ts(a key separator inside a template string invalidateTableScopedEntryNames). Pre-existing, not touched here, butgreptreats the file as binary, which cost time while investigating. Worth replacing with an escape sequence separately.How it fits together
ValidateSqlStageSpecinpackages/2-sql/2-authoring/contract-ts/src/contract-dsl.tswalks the tuple ofindexesandforeignKeys, collects literalnames, and resolves the model's sql spec toneveron a repeat or on a collision with the primary key name.Nameparameter widened tostringunder contextual typing, so the collected set wasstringand never repeated.const Namekeeps the literal. Four signatures incontract-dsl.ts(indexoverloads and thePackAwareIndextwin), twoforeignKeyoverloads, andfullTextIndexinpackages/3-extensions/postgres/src/contract/full-text-index.ts.contract-builder.duplicate-names.test-d.tscovers index/index, expression-index/index, index/primary-key, and foreign-key/foreign-key, plus the accepted distinct-name case.full-text-index.test-d.tscovers fullTextIndex/fullTextIndex and fullTextIndex/constraints.index.strategygoes. Removed fromSqlLoweringSpecinpackages/2-sql/1-core/operations/src/index.tsand from every site that set it. The extension upgrade fragment tells extension authors to delete the line.Behavior changes & evidence
sql()spec reuses a literal index name, reuses the primary key name for an index, or reuses a foreign-key name now has aneversql spec, which downstreamdefineContractrejects. Implementation: contract-dsl.ts. Evidence: contract-builder.duplicate-names.test-d.ts.fullTextIndexparticipates in the same check. Implementation: full-text-index.ts. Evidence: full-text-index.test-d.ts.strategy. Implementation: operations/src/index.ts, query-operations.ts. Rendered SQL is unchanged; the existing lowering tests across the adapters and extensions pass unmodified apart from dropping the field.Testing performed
pnpm typecheck:packages: all tasks pass.pnpm lintandpnpm lint:throws: pass.pnpm test:packages: 17848 pass. Two files failed in the full run under machine load,driver.buffered-release.integration.test.ts(connection timeout) andrender-typescript.roundtrip.test.ts(8s timeout); both pass when rerun alone and neither touches this change.Follow-ups
post_id,invited_by_id) the builder binds codecs correctly, and keyed by field name (postId) is a type error. The only way to reach the lowering error is to cast past the row type. A clearer build-time error for unknown column keys would be a small hardening, not a bug fix.constraints.uniquenames are outside the duplicate-name check.validators.ts.Alternatives considered
ValidateSqlStageSpecto acceptName | undefined, as the follow-up note suggested. It already does; the change would have been a no-op.nameprefixes at runtime. Rejected: the runtime validator deliberately compares wire names after hashing, and two indexes with the same prefix are physically distinct. Adding a prefix check there would have to special-case authored names against inferred ones for no runtime benefit.strategyas documentation of infix vs function lowering. Rejected: the template already shows which it is, and a field nothing reads is a field that drifts.Checklist
git commit -s) per the DCO.TML-NNNN: <sentence-case title>form — no Linear ticket exists for this slice, as with Postgres full-text search operations and a typed @@fullTextIndex, owned by the target pack #30348.Notes for the reviewer
See Reviewer notes above.
🤖 Generated with Claude Code
Summary by CodeRabbit
Changes
Documentation
Tests