Repository navigation
refactor(contract): execution default refs name an entry and a field, not a table and a column - #30399
Conversation
…xecution defaults slice 3 Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…olumn
ExecutionMutationDefault.ref in the framework contract becomes
{ namespace, entry, field }. The values are unchanged: SQL still writes the
table name into entry and the column name into field. The framework type
now carries no SQL vocabulary, so another family can use it as is.
SQL follows: the arktype execution schema, the contract-ts assembly and
its sort, the runtime match in applyMutationDefaults, the ORM client
create-input check and HasExecutionCreateDefault, and every test that
builds or reads a ref. MutationDefaultsOptions keeps its table key: the
match reads mutationDefault.ref.entry !== options.table, which is clear
as it stands.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Emitted contract.json and contract.d.ts files and the example migration snapshots come from pnpm fixtures:emit. The Prisma 7 reader expected contracts come from UPDATE_PRISMA7_FIXTURES=1 and the package formatter. Only execution refs and executionHash change. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…instructions
ADR 158 shows the { namespace, entry, field } ref. The framework
vocabulary count drops from 275 to 274, so the threshold follows. App and
extension upgrade fragments declare the rename with detection for JSON
refs, TypeScript ref literals, and .ref.table / .ref.column reads.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ON schema A standalone ref constant in the temporal-codec interpreter test still used table and column. The checked-in data-contract-sql-v1.json schema is regenerated with pnpm schemas:generate. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The multi-line ref literal kept table/column, so the test input had two defects instead of only the bad generator id it is named for. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Renames table/column to entry/field in the execution-default refs of the 47 snapshots regeneration does not rewrite: the prisma7-adoption snapshot refs/db.json points at, the prisma-8-demo fixture snapshots, and the two unreferenced prisma-8-demo snapshots. Keys are written in the emitted order (entry, field, namespace); nothing else in the files changes. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Step 2 now says to write the ref keys as entry, field, namespace and to leave a snapshot's executionHash alone, since the snapshot loader re-hashes only storage. The "after" example uses the same order. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…-names Main bumped every workspace package to 8.0.0-rc.12 and archived the pending upgrade fragments it shipped. Merged cleanly; this branch's execution-ref-entry-field fragments stay pending. 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 ignored due to path filters (131)
📒 Files selected for processing (165)
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review. 📝 WalkthroughWalkthroughMutation default references now identify targets by namespace, entry, and field instead of table and column. The contract type, validation, authoring, runtime matching, generated contracts, snapshots, tests, and upgrade instructions reflect the new reference shape. ChangesMutation default reference contract
Priority: ➖ Normal Estimated code review effort: 3 (Moderate) | ~25 minutes Merge Risk: ⚪ Minimal · up to No actionable issue is established; the change is mergeable after normal checks. Security Architecture ReviewSecurity architecture risk: 🟡 Moderate · up to The new reference format is consistent across the updated writer and readers, but contracts and readers using different versions may not work together during deployment or rollback. No new attacker-controlled access path was identified. Retained concerns
Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 5❌ Failed checks (1 inconclusive)
✅ Passed checks (5 passed)
✨ Finishing Touches📝 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 📦
|
|
@CodeRabbit review |
✅ Action performedReview finished.
|
main renamed the keys of an execution default's ref from table and column to entry and field (#30399). The printer and its tests read the new keys. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The project spec, plan and design notes take main's five-slice version from #30399. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…tamps on create and update (prisma#30403) > Stacked on prisma#30396 (Mongo target owns its codecs) and prisma#30399 (execution ref rename). Until those merge, their commits appear in this diff; the slice 3 work starts at commit 80ac5d7. A Mongo schema in Prisma 8 can now declare automatic timestamps, the same way a Postgres schema does: ```prisma model Post { id ObjectId @id title String createdAt temporal.createdAt() updatedAt temporal.updatedAt() } ``` ```ts const Post = model('Post', { fields: { title: field.string(), createdAt: field.temporal.createdAt(), updatedAt: field.temporal.updatedAt(), }, }); ``` `orm.post.create({ data: { title: 'x' } })` writes both timestamps. An update with a non-empty payload advances `updatedAt`; an empty payload writes nothing. Both fields are optional on the create input type. Until this PR, Mongo had no way to declare a write-time default at all: `@updatedAt` was a hard error and the ORM never filled anything in. ## The decision Mongo reuses the framework's field-preset machinery and the same `temporal.*` presets Postgres registers, and its contract carries the same `execution` section (`{ ref: { namespace, entry, field }, onCreate, onUpdate }`, hashed into `executionHash`). The pieces that were SQL-local but not SQL-specific move up into the framework so both families call one implementation: the temporal preset builders and the `timestampNow` control descriptor, the PSL field-preset resolution helpers, the arktype schema for the execution section, and the TypeScript helpers that turn a pack's `authoring.field` namespace into callable `field.*` helpers. The runtime generator registry and apply loop stay Mongo-local in this PR, as a deliberate short-lived duplicate of the SQL runtime's; the next PR hoists both into the framework. ## How the pieces fit **Registration.** The Mongo target descriptor contributes `authoring.field.temporal.{createdAt, updatedAt, timestamp}` built from the framework's `temporalAuthoringPresets` and `temporalCodecPreset` on `mongo/date@1`, plus the `timestampNow` control descriptor. A runtime-only descriptor meta keeps the authoring surface out of the runtime bundle, as Postgres does. There is no precision argument: Mongo dates have none. **PSL.** The Mongo interpreter resolves a namespaced call in type position (`temporal.createdAt()`) against the composed field presets before the bare scalar lookup, using the same helpers SQL uses (now in `@internal/psl-parser/interpret` and `@internal/framework-components/authoring`). Diagnostics mirror SQL: a preset on an optional field, a list, or an `@id` field, an unknown preset, an uncomposed namespace, or a bad argument each get the SQL code. Two refusals are Mongo-only and report `PSL_UNSUPPORTED_FIELD_TYPE`: a preset on a composite-type field, and a preset that contributes a storage default, id, or unique, which Mongo cannot represent. `@updatedAt` still errors, now pointing at `temporal.updatedAt()`. **TypeScript.** `field.temporal.*` is composed from the packs' `authoring.field` namespaces through helpers hoisted from SQL into `@internal/contract-authoring`, so PSL and TS instantiate one registry entry. A field builder carries the preset's phases as a type parameter; execution defaults on a nullable field, a list, a value object, or a model with no collection throw `CONTRACT.DEFAULT_INVALID`. Both paths build the `execution` section through one function in `@internal/mongo-contract` that sorts by namespace, entry, field and computes `executionHash`; the arktype schema for the section now lives once in `@internal/contract` and both families' validators import it. **Runtime.** `createMongoExecutionContext` collects `mutationDefaultGenerators` from target, adapter, and extensions, refuses duplicate ids naming both owners, and refuses to build when the contract requires a generator no component provides, with the SQL error codes and message. It exposes `applyMutationDefaults` with SQL semantics: an empty update payload applies nothing, explicit values win, `'row'` stability yields one value per row per call and `'query'` one per operation. The `timestampNow` runtime generator (`new Date()`, query stability) lives in the Mongo family package and the adapter registers it, as the Postgres adapter registers SQL's. **ORM and facade.** The ORM sits below the runtime layer, so it depends on a `MongoMutationDefaults` interface in `@internal/mongo-contract` that the execution context satisfies; `mongoOrm` takes it as a `mutationDefaults` option and `mongo()` passes the context through; building `mongoOrm` by hand without it, for a contract that declares generators, throws `ORM.MUTATION_DEFAULTS_MISSING` naming the fix rather than silently writing documents without their timestamps. `create`, `createAll`, `createAndCount`, and the insert half of `upsert` apply `onCreate`; `update`, `updateAll`, `updateAndCount`, and the update half of `upsert` apply `onUpdate` only when the payload is non-empty. Generated fields are optional on the create input type on both the emitted `contract.d.ts` path and the no-emit TypeScript path. ## What you will see in the diff - **Hoists.** SQL packages change import paths for the temporal preset builders, the PSL preset-resolution helpers and argument mapping, and the TS field-helper composition. Each is a pure move; SQL tests are unchanged in intent and green. `@internal/family-sql/control` no longer exports the temporal builders (they are in `@internal/framework-components/authoring` and `/control`), which the `temporal-presets-move-to-framework` upgrade fragment covers. - **Runtime tests relocated.** The Mongo runtime package dev-depended on the family, target, adapter, and mongodb-memory-server so its tests could build a real stack; SQL's runtime has no such dependencies, and they made it impossible for the family to depend on the runtime without a package cycle. The tests that need a real stack (17 files plus a fixture) moved to `test/integration/test/mongo/runtime/` with bodies intact; two files were split so an internal hash function is not exported for tests. The runtime package keeps 100% coverage through new in-package unit tests built from plain descriptor objects. - **New integration fixture** `test/integration/test/mongo/temporal-presets/` with the same model authored in PSL and in TS. The two emit an identical `execution` section and `executionHash`. - **Upgrade fragment** `mongo-execution-defaults`: hand-written `MongoExecutionContext` objects must now provide `applyMutationDefaults`. Application code needs no change. ## Alternatives considered - **Prisma 6 style `@default(now())` and `@updatedAt` attributes on Mongo.** Rejected: Mongo in Prisma 8 mirrors Postgres and reuses framework primitives; a second grammar would need a second printer rule and its own type-blind validation. - **A Mongo-specific `execution` type with model and field refs.** Rejected after it produced over a thousand type errors; the framework ref was renamed to neutral names in prisma#30399 instead. - **Hoisting the runtime registry into the framework in this PR.** Deferred to its own PR to keep this one reviewable. - **Omitting a precision argument versus ignoring it.** Mongo dates have no precision, so the argument does not exist. Known gaps recorded for later: PSL- and TS-authored Mongo contracts still differ in `storageHash` and validators for reasons that predate this PR, and SQL sorts execution defaults without the namespace key. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added MongoDB timestamp presets for `createdAt`, `updatedAt`, and custom timestamps on create and update operations. * Generated timestamps are shared across an ORM operation, preserve explicitly supplied values, and allow generated-on-create fields to be omitted from create inputs. * MongoDB reports clear errors when required default generators are missing or duplicated. * **Compatibility** * Execution-default references now identify fields by entry and field rather than table and column. * **Documentation** * Updated contract, MongoDB usage, and upgrade guidance for timestamp defaults and field references. <!-- 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 Fable 5.1 <[email protected]>
…the contract source (prisma#30405) > Stacked on prisma#30403 (Mongo execution defaults), which is stacked on prisma#30396 and prisma#30399. Until those merge, their commits appear in this diff; the slice 5 work starts at commit e33782e. A Prisma 6 MongoDB project can point Prisma 8 at its existing `schema.prisma` and get a contract without rewriting anything: ```ts // prisma.config.ts import { definePrismaConfig } from 'prisma/config'; import { defineConfig as ormConfig, prisma6Schema } from '@prisma/orm-mongo/config'; export default definePrismaConfig({ orm: ormConfig({ contract: prisma6Schema('prisma/schema.prisma'), db: { connection: process.env['DATABASE_URL']! }, }), }); ``` ```prisma // prisma/schema.prisma, unchanged Prisma 6 model Post { id String @id @default(auto()) @Map("_id") @db.ObjectId title String views BigInt meta Json authorId String @db.ObjectId author User @relation(fields: [authorId], references: [id]) createdAt DateTime @default(now()) updatedAt DateTime @updatedat @@index([authorId]) } ``` `prisma contract emit` produces the same contract Prisma 8 PSL would for the equivalent model written with `ObjectId`, `Int64`, `Json`, `temporal.createdAt()`, and `temporal.updatedAt()`, and `prisma db sign` verifies it against the database Prisma 6 built with zero findings. ## The decision The Prisma 6 MongoDB dialect is a first-class contract source, read by its own package (`@internal/mongo-contract-prisma6`, published as `@prisma/orm-family-mongo/provider`) that mirrors the Prisma 7 Postgres reader shipped in prisma#30287. It parses with the Prisma 8 parser in its Prisma 7 grammar mode and builds the Mongo contract directly from the family's exported building blocks, so the storage hash and execution hash come from the same code the Prisma 8 interpreter uses. Everything the reader cannot express is a hard error with a `PSL.PRISMA6_MONGO_*` code and a span; nothing is silently dropped or approximated (ADR 252). The function is named `prisma6Schema` because Prisma 7 has no MongoDB connector, so the dialect it reads is Prisma 6's. ## How the pieces fit **Binding.** The Mongo target supplies a `Prisma6TargetBinding` (accepted providers, the scalar-to-codec map, the ObjectId codec, the timestamp generator id). The reader holds no target facts, matching the Prisma 7 reader's `Prisma7TargetBinding`. **What maps.** `String`, `Int`, `Float`, `Boolean`, `DateTime` to the existing codecs; `BigInt`, `Decimal`, `Bytes`, `Json` to the codecs prisma#30396 added; `String @db.ObjectId` to the ObjectId codec; `DateTime @default(now())` to an on-create `timestampNow` generator and `@updatedAt` (with or without `@default(now())`) to on-create plus on-update, which is what `temporal.createdAt()` and `temporal.updatedAt()` from prisma#30403 produce; composite `type` blocks to value objects; enums with member `@map` storage values; to-one `@relation(fields, references)`; `@unique`, `@@unique`, `@@index` with sort order; `@@fulltext` to a text index; `@map` and `@@map`; `@ignore` and `@@ignore` omitted. Index names are dropped: Mongo verify matches indexes by keys and options, never by name. **What is a hard error, expected to flip later as the Mongo family gains each capability.** Composite ids, `@map` on a composite-type field, referential actions on `@relation`, the scalar-list many-to-many shape, `@default` values other than `now()` and `auto()` on `_id` (Mongo has no storage defaults and registers no id generators), optional generated fields, `@updatedAt` on a non-`DateTime`, other `@db.*` types, `Unsupported(...)`, `view`, and `@@schema` (which has no Mongo meaning and stays an error). **No validators.** The Prisma 8 Mongo PSL interpreter emits a strict `$jsonSchema` validator per collection; a Prisma 6 database has none, and Mongo verify fails on a declared-but-missing validator. The reader emits none, which the TypeScript builder already does, so `db sign` passes against the database as Prisma 6 left it. The parity test shows validators are the only storage difference from the equivalent Prisma 8 PSL contract. **Facade.** `defineConfig` in `@prisma/orm-mongo/config` accepts `contract: string | ContractConfig`, exactly as the Postgres facade does, and exports `prisma6Schema`. **Also in this PR.** The Prisma 8 Mongo PSL interpreter now reports unknown top-level blocks (`view`, `datasource`, `generator`) with `PSL_UNSUPPORTED_TOP_LEVEL_BLOCK` instead of dropping them silently, mirroring SQL. The storage builder and back-relation pairing the reader shares with the interpreter were hoisted into the family packages so there is one implementation of each. ## What you will see in the diff - **Fixtures.** One case per rule-table row and per error code under `packages/2-mongo-family/2-authoring/contract-prisma6/test/fixtures/`, in the Prisma 7 reader's layout (`schema.prisma` or a `schema/` directory, `expected-contract.json` or `expected-diagnostics.json`, regenerated with `UPDATE_PRISMA6_FIXTURES=1`), plus a parity test against the equivalent Prisma 8 PSL schema. - **CLI journey.** `test/integration/test/cli-journeys/prisma6-source.e2e.test.ts` creates the collections and indexes Prisma 6 `db push` would create (no validators, Prisma 6 index names, unique indexes for `@unique`), then runs `contract emit`, `db sign`, and `db verify` through the CLI: zero findings in lenient and strict mode. An extra undeclared index is a warning in lenient mode and a failure in strict mode, as expected. - **Shared building blocks.** `buildMongoStorage` and `encodeMongoValueSets` now live in `@internal/mongo-contract`, and `pairMongoBackRelations` in `@internal/mongo-contract-psl`; the Prisma 8 interpreter and the reader both call them, and `fixtures:check` shows no hash moved. - **Docs.** `prisma6Schema` section in the Mongo facade README, the `PSL.PRISMA6_MONGO_*` codes in `docs/reference/error-reference.md`, and notes in the Prisma 8 skill references. The superseded slice spec under the Prisma 7 contract-source project is deleted and that project's deferred-gaps entries for Mongo defaults and codecs are marked filled. ## Alternatives considered - **Rewriting the Prisma 6 file into Prisma 8 syntax and running the Prisma 8 interpreter.** Rejected: several Prisma 6 facts have no channel through the interpreter (composite `@map`, enum member `@map`, the ObjectId codec on a `String` field), and every rewrite would be a lossy rule. The Postgres reader builds the contract directly for the same reason. - **Emitting validators and asking users to apply them before signing.** Rejected for the adoption story: `db sign` must pass against the database Prisma 6 built; validators come with the switch to Prisma 8 PSL. - **Warnings for unsupported constructs.** Rejected by ADR 252: a construct the reader cannot express is a hard error, and each error is a signal to build the feature. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Use Prisma 6 MongoDB schemas from a file or directory as contract sources. * Schema interpretation supports models, relations, indexes, enums, composite types, lists, and timestamps. * Mongo configuration accepts either a contract source path or a contract configuration. * Sign and verify MongoDB databases against emitted contracts; verification reports undeclared indexes. * **Bug Fixes** * `contract emit` identifies unsupported indexes on composite-type fields and suggests indexing a top-level field or removing the index. * **Documentation** * Added guidance on supported schemas, configuration, and database ownership during migration. <!-- 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 Fable 5.1 <[email protected]>
…work, for SQL and Mongo (prisma#30406) > Stacked on prisma#30405, which is stacked on prisma#30403, prisma#30396 and prisma#30399. Until those merge, their commits appear in this diff; the slice 4 work starts at commit 7795377. Both database families now run the same write-time default machinery. The SQL runtime and the Mongo runtime each call three framework functions instead of carrying their own registry, availability check, and apply loop: ```ts import { applyMutationDefaults, assertMutationDefaultGeneratorsAvailable, collectMutationDefaultGenerators, } from '@internal/framework-components/runtime'; const generators = collectMutationDefaultGenerators([target, adapter, ...extensions]); assertMutationDefaultGeneratorsAvailable(contract.execution, generators); // per ORM operation: applyMutationDefaults(contract.execution, generators, { op: 'create', namespace, entry, values, defaultValueCache }); ``` A generator is `{ id, generate(params?), stability: 'field' | 'row' | 'query' }`, typed once in the framework; the SQL and Mongo `timestampNow` generators and the Postgres Temporal generators all use that type. ## The decision The mutation-default runtime is framework-owned. It was written for SQL and lived in `@internal/sql-runtime`; prisma#30403 gave Mongo a deliberate short-lived copy so the Mongo work could land without touching SQL. This PR deletes both copies and moves the code, with the SQL semantics verbatim, into `framework-components/src/execution/mutation-defaults.ts`. Nothing in it was ever SQL-specific except the option key names, and prisma#30399 had already made the contract reference neutral; this PR finishes the rename in the runtime options (`table` becomes `entry`, `column` becomes `field`). ## How the pieces fit **Semantics, unchanged from SQL.** A duplicate generator id refuses context creation naming both owners; a contract that requires a generator no component provides refuses context creation listing the ids; a key present in the values is explicit whatever its value; an update with no keys applies nothing; `'row'` stability gives one value per row per call, `'query'` one per operation through the caller's cache, `'field'` none; a reference is applied once per call. The unit tests moved from the SQL runtime package to the framework and run against plain contributor objects; the SQL package keeps only its wiring tests. **SQL.** The runtime calls the framework in the same place it ran its own code, after codec collection. The lanes' `ExecutionContext` extends the framework `MutationDefaults` interface. The ORM client, the mutation executor, and the SQL builder lane follow the option and result key rename. A new SQL builder test pins the existing rule that a key present with an `undefined` value counts as explicit. **Mongo.** The runtime copy from prisma#30403 is deleted; `MongoExecutionContext` extends the same `MutationDefaults` interface and the Mongo ORM depends on it. The Mongo `undefined`-as-absent behaviour is a caller rule and its tests moved to the ORM level. **One execution-section builder.** `buildExecutionSection` in `@internal/contract` sorts defaults by namespace, entry, field and computes `executionHash`; both families' authoring paths use it. SQL previously sorted without the namespace key, so two multi-namespace fixtures re-hash; everything else is byte-identical. **ADR and docs.** ADR 255, "Mutation-default generators are a framework runtime concern", records the generator contract, the three stabilities and their caches, the availability check and its two error codes, the explicit-key rule and why `namespace` is required, the neutral reference and the sort order, and why each family keeps its own check position. ADR 158's example is updated; subsystem 4 (Runtime & Middleware Framework) gains a mutation-defaults section and subsystem 10 points at it. ## What you will see in the diff - **Deleted code.** The registry, availability check, apply loop, and generator types are gone from `packages/2-sql/5-runtime/src/sql-context.ts` and `packages/2-mongo-family/7-runtime/src/mongo-execution-stack.ts`; both keep only the wiring. `mongo-contract`'s `mutation-defaults.ts` and `build-execution-section.ts` are deleted. - **Renamed keys in SQL callers.** `table` → `entry` and `column` → `field` in the SQL ORM client, the mutation executor, the SQL builder lane, and their test stubs. Nothing else in those files changes. - **Moved tests.** The SQL runtime's generator tests now live in `framework-components/test/mutation-defaults.test.ts` and run against plain contributor objects; the SQL and Mongo runtime packages keep wiring tests only (including a new test per family pinning where the check runs relative to codec collection). The Mongo ORM gains tests that it strips `undefined` before calling the framework. - **Dependencies.** `family-sql` no longer depends on `sql-runtime` and `family-mongo` no longer depends on `mongo-runtime`; neither had a source import left. - **Fixtures.** Two multi-namespace SQL fixtures re-hash (`test/integration/test/ports/prisma/functional/multi-schema/_fixture/{different-names,no-map}`), the only contracts whose execution defaults span more than one namespace and were not already in namespace order. - **Upgrade instructions.** `upgrade-instructions/pending/mutation-default-runtime-in-framework/extension/instructions.md` covers the moved SQL and Mongo types, the renamed option and result keys, and `buildMongoExecutionSection` → `buildExecutionSection`. ## Alternatives considered - **Keep two copies and let them drift.** Rejected: the caching rule and the error contract are exactly the kind of thing that diverges silently, and the two copies had already diverged in `undefined` handling and check placement. - **Hoist before building the Mongo half.** Rejected during shaping: the framework reference still carried SQL names then, and the Mongo work would have blocked on a SQL-wide rename. Doing it in this order kept each PR reviewable. - **Treat `undefined` as absent inside the framework.** Rejected: that would change the SQL builder lane's behaviour; callers that want it (both ORMs) already filter before calling. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Generated mutation defaults are now handled consistently across SQL and MongoDB operations, with shared support for create and update defaults. * Defaults can be scoped to a specific entry and field, with configurable value reuse and checks for missing or duplicate generators. * Execution defaults are sorted consistently before hashing, supporting stable contract results across environments. * **Documentation** * Added guidance on mutation-default behavior, generator stability, and execution-section construction. <!-- 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 Fable 5.1 <[email protected]>
…cript instead of by hand (prisma#30453) ## At a glance Step 2 of the `8.0.0-rc.12` to `8.0.0-rc.13` upgrade guide, run instead of done by hand: $ pnpm exec tsx <skill>/upgrading/app/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/scripts/execution-ref-entry-field/rename-execution-ref-keys.ts --check 19 file(s) under migrations/ scanned, 19 need the rename. $ pnpm exec tsx <skill>/upgrading/app/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/scripts/execution-ref-entry-field/rename-execution-ref-keys.ts 19 file(s) under migrations/ scanned, 19 got the rename. One reference in a snapshot, before and after: ```json { "ref": { "namespace": "public", "table": "user", "column": "updated_at" } } { "ref": { "entry": "user", "field": "updated_at", "namespace": "public" } } ``` ## What this PR changes 1. The published rc.12-to-rc.13 guides, app and extension, gain a script for the `execution-ref-entry-field` change, and step 2 tells the reader to run it. 2. Step 2 also names the intermediate contracts inside migration packages, says the old key order varies between files, and names the command that shows whether the rewrite worked. ## What the change is Since prisma#30399 the emitted contract names the target of a generated default (`temporal.updatedAt()`, `@default(uuid())` and the like) as `ref: { entry, field, namespace }` where it used to say `{ table, column, namespace }`. The values are the same; only the keys changed, because Mongo is gaining write-time defaults and the shared types must not use SQL words. The toolchain refuses the old keys. A project's live `contract.json` is fixed by `prisma contract emit`. Its migration snapshots are not: every migration keeps a copy of the contract as it was, under `migrations/snapshots/<hash>/contract.json` and `contract.d.ts`, and those copies were written by the old release. Any command that loads one of them, such as `prisma db migrate --to <hash>`, fails: CONTRACT.VALIDATION_FAILED: … contract.json failed to deserialize: execution.mutations.defaults[0].ref.entry must be a string (was missing); execution.mutations.defaults[0].ref.column must be removed … The rc.13 guide's `execution-ref-entry-field` entry says to rename the keys in every snapshot and leave the hashes alone: only `executionHash` would change, nothing compares it, and the storage hash that names the directory does not move. That instruction is right. It just had no script, so it meant hand-editing every snapshot in the project. prisma#30399 renamed this repository's own 104 snapshot files with a script that was never committed. ## What the script does `rename-execution-ref-keys.ts` sits beside each guide under `scripts/execution-ref-entry-field/`, as byte-identical copies for the app and extension audiences, run with `pnpm exec tsx` from the project root (the extension package root for an extension). It uses only Node built-ins. - It reads every `.json` and `.d.ts` file under any `migrations/` directory, skipping `node_modules`, `.git` and `dist`, and changes only files that hold `execution.mutations.defaults[].ref` entries. `migration.json`, `ops.json` and `refs/*.json` are left byte-for-byte alone. - In JSON it renames the keys and writes them sorted (`entry`, `field`, `namespace`). A file in canonical form is written the way `writeContractSnapshot` writes it, so the result matches a fresh emit apart from `executionHash`. An indented file, such as a hand-written `intermediate.json`, keeps its indentation. - In `.d.ts` it walks the declaration once, skipping quoted strings and comments, and rewrites only the `ref` blocks that are elements of `execution` → `mutations` → `defaults`. It renames `table` and `column` and sorts the members, whatever order they were in, keeping single-line and multi-line layouts. A `}` inside a quoted name does not end the block, and a `readonly ref` anywhere else, such as a model field named `ref`, is left alone. - It replaces each file by writing a temporary file in the same directory and renaming it over the target. - It leaves `executionHash`, `storageHash`, `profileHash` and directory names alone. - A second run changes nothing. `--check` lists what would change and exits 1 if anything would. - A `.json` file that does not parse is listed as `NOT JSON`, left untouched, and makes the run exit 1, with or without `--check`. ## The three prose additions Applying the guide by hand in prisma/asks, on a dev build that carried this change before rc.13 shipped, showed three things a reader needs that the entry did not say: - **Intermediate contracts.** A migration package can import a hand-written contract (`migrations/app/<dir>/intermediate.json` and `intermediate.d.ts`) with the same references. The entry's detection patterns match them, but the prose named only `migrations/snapshots/`. Step 2 now names both. - **The old key order varies.** Older `.d.ts` files say `namespace, table, column`; newer ones `column, namespace, table`. A hand edit or a search-and-replace that assumes one order misses the rest. Step 2 says so; the script sorts, so it does not care. - **How to confirm it.** In an app, `prisma migration plan --from <dir> --to <dir>`, naming one migration directory as both ends, loads that snapshot without touching the database. It fails before the rewrite with the error above and prints `No changes detected` after it. `prisma db migrate --to <hash>` is no check: on a database already past that snapshot it has no route back and fails either way. `prisma migration check` and `prisma db verify` pass either way for app snapshots. In an extension package, no command reads the package's own `migrations/snapshots/`, and the CLI loads an extension space only at its head, so the extension guide uses `--check` and names `prisma migration check --space <space-id>` in an app that installs the extension. ## Tests The repository's rule for upgrade scripts is validation by execution. In a disposable worktree of the branch head I restored the 104 snapshot files prisma#30399 changed to their state before that PR, and added a synthetic migration, `test/synthetic-execution-ref/migrations/app/20260930T0000_synthetic/`, with an indented `intermediate.json` and an `intermediate.d.ts`. Between them they hold references in both old key orders, a single-line reference, a quoted table name containing `}`, comments holding a quote and braces, and an unrelated model-field block `readonly ref: { readonly column: 'ref' }` outside the execution defaults. Then I ran the script from the worktree root: $ tsx rename-execution-ref-keys.ts --check # exit 1 319 file(s) under migrations/ scanned, 106 need the rename. $ tsx rename-execution-ref-keys.ts 319 file(s) under migrations/ scanned, 106 got the rename. $ tsx rename-execution-ref-keys.ts 319 file(s) under migrations/ scanned, 0 got the rename. $ tsx rename-execution-ref-keys.ts --check # exit 0 319 file(s) under migrations/ scanned, 0 need the rename. - The 94 files prisma#30399 had renamed by script came out byte-identical to the branch. The other 10 are the 5 snapshots prisma#30399 regenerated by emit instead; masking `executionHash` in both versions, every one matched. That is the documented outcome, and it shows a rewritten `contract.json` matches a fresh emit apart from that hash. - Both synthetic files matched their expected output exactly: every reference came out `entry, field, namespace`, the quoted `}` name was renamed, the indentation and the single-line layout survived, and the unrelated `ref` block was untouched. No temporary files were left behind. - A truncated `contract.json` holding `"table"` and `"column"` made `--check` and a write run both print `NOT JSON …` and exit 1; the file was left unchanged. - After the run, the entry's detection regexes match one file under a `migrations/` directory: the synthetic `intermediate.json`, whose unrelated `"ref": { "column": "ref" }` block the detection pattern also matches. The script leaves that block alone, as it should. - The CLI built from this branch, on `examples/prisma-8-demo` with the restored snapshots: `prisma migration plan --from 20260810T1108_add_post_engagement_counters --to 20260810T1108_add_post_engagement_counters` failed before the script with `CONTRACT.VALIDATION_FAILED … execution.mutations.defaults[0].ref.entry must be a string` and printed `No changes detected` after it. `prisma migration check` passed before the script. - Extension space: with an old-key execution default added to the demo's pgvector head snapshot, `prisma migration check --space pgvector` failed with `MIGRATION.CHECK_CONTRACT_UNREADABLE`, and passed after the script. From `packages/3-extensions/pgvector`, `prisma migration plan --from <head hash> --to <head hash>` answers `MIGRATION.SNAPSHOT_MISSING … the graph is empty`, which is why the extension guide offers no command there. Checks on the branch: `pnpm check:upgrade-coverage --mode dev` and `--mode pr` against `origin/main`, `pnpm lint:skills`, `biome check` on both guide directories, strict `tsc` on both script copies, `pnpm lint:casts` and `pnpm lint:throws` (no increase), and `--check` on the branch tree (317 files, 0 to rename) all pass. ## History of this branch It opened as an addition to the pending fragment `upgrade-instructions/pending/execution-ref-entry-field/`. While it was open, rc.13 shipped (prisma#30457) and release preparation archived that fragment and synthesized it into the published guides. A plain merge of `main` followed the move and put the edits into the archived originals, which must stay as shipped. The second commit restores the archive and moves the script and prose into the published guides, so against `main` the PR now changes only the two rc.13 `instructions.md` files and adds the two script copies. That makes it a correction to published guidance, which `upgrade-instructions/README.md` says goes through an ordinary reviewed PR. ## Alternatives considered - **Make the toolchain read the old `{ table, column }` shape.** Rejected by the ORM owner: the toolchain should not parse an obsolete representation. The upgrade step is the fix. - **Tell readers to re-emit each snapshot.** Impossible: a snapshot is the contract as it was at that migration, and emit only produces the current one. - **Leave step 2 as a hand edit.** Rejected: a project has one snapshot per migration, the old key order differs between files, and prisma#30399 itself needed a script for 104 files. - **Confirm with `prisma db migrate --to` against a fresh, empty database.** Not needed: `prisma migration plan --from <dir> --to <dir>` loads the same snapshot offline. - **Fixing the misleading "Predecessor contract" wording for a failed `--to` target.** Out of scope here; a separate follow-up. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Upgrade Guidance** * Updated the Prisma 8.0.0-rc.12 to 8.0.0-rc.13 upgrade instructions with guidance for updating and validating migration snapshots and intermediate contracts. * **Migration Tooling** * Added a tool to update reference keys in migration contracts. It can check for required changes without modifying files and reports invalid migration files. <!-- 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 Fable 5.1 <[email protected]>
Every contract that declares a write-time default carries a reference to the field it applies to. Before this PR that reference was written in SQL vocabulary; now it uses the framework's own storage words:
{ "ref": { "namespace": "app", "entry": "users", "field": "updated_at" }, "onUpdate": { "kind": "generator", "id": "timestampNow" } }entrywastableandfieldwascolumn. The values are unchanged: a SQL contract still stores the table and column names there.executionHashchanges for every contract with generators, because the canonical JSON changed;storageHashandprofileHashdo not.The decision
The framework contract type
ExecutionMutationDefault.refis{ namespace, entry, field }. The framework already calls the tables and collections of a storage namespace itsentries, soentryis the existing generic word for "the thing in storage that holds fields", andfieldis the stored field or column. SQL puts table and column names in those slots; the MongoDB family will put collection and field names in the same slots and reuse the framework type unchanged.Why now
Mongo is about to get write-time defaults (
temporal.createdAt()andtemporal.updatedAt(), the same presets Postgres has). The first attempt gave the Mongo contract its ownexecutiontype with Mongo-named refs. That produced over a thousand type errors: every emittedcontract.d.tsderives its type from the frameworkContract, and the Mongo control-plane interfaces extend framework interfaces written against it. Renaming the framework field once is far smaller than teaching every family to carry its own copy, and the framework rules forbid SQL vocabulary in shared types anyway. Doing it in its own PR keeps the Mongo change reviewable.What changed
packages/1-framework/0-foundation/contract): the ref type, with a type test that fails on the old shape.ref.entryagainst the operation's table), the ORM client's create-input optionality check, and the checked-in JSON schemadata-contract-sql-v1.json. The SQL PSL interpreter shares the TS assembly path, so it needed no separate change.MutationDefaultsOptions.tablein the SQL lanes layer keeps its name: it is SQL-side API and reads clearly againstref.entry.contract.jsonandcontract.d.tsfiles (integration fixtures, example contracts, example migration snapshots, the Supabase contract) plus two Prisma 7 reader expected contracts. The only diff in each is the ref keys andexecutionHash.refs/db.jsonpoints at, and the prisma-8-demo migration-graph fixtures, most of which were already recorded as invalid for other reasons ingotchas.md). Only the ref keys changed, written in sorted order; theirexecutionHashvalues are stale on purpose, because the snapshot loader re-hashes storage only and nothing can regenerate a past snapshot. This is the same instruction the upgrade fragment gives users.upgrade-instructions/pending/execution-ref-entry-field/{app,extension}/instructions.mddetect JSON refs withtable/columnkeys underexecutionand TypeScript that reads.ref.tableor.ref.column. Step 1 is re-emit; step 2 renames the keys in past migration snapshots and leaves theirexecutionHashalone. Validated by execution against this repo's examples: after the fragment runs, the only leftover difference is theexecutionHashin the five snapshots this PR regenerated, which is the documented expectation.Alternatives considered
executiontype and an emitter hook to shape it. Rejected: large churn across emitted types and control interfaces that a later hoist would undo.Contractfor the ref shape. Rejected: churn at everyContractuse site for a two-key rename.tableandcolumn. Rejected: that is the vocabulary leak the framework rules exist to prevent.🤖 Generated with Claude Code
Summary by CodeRabbit