Repository navigation
feat(mongo): temporal.createdAt() and temporal.updatedAt() fill timestamps on create and update - #30403
Merged
Conversation
Every Drive subagent dispatch in this repo runs on Opus; the model-tier calibration records the override. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…8, Binary, Json Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
ADR 198 says a target-layer module must not import adapter or driver
code. The Mongo target built its runner dependencies by importing
createMongoRunnerDeps and extractDb from the adapter and MongoDriverImpl
from the driver.
MongoRunnerDependencies and MarkerOperations now live in the family
control-adapter SPI module. MongoControlAdapter gains
createRunnerDependencies(driver), implemented by MongoControlAdapterImpl,
and MongoControlFamilyInstance forwards it. The target descriptor calls
family.createRunnerDependencies({ driver }), so the only adapter import
left in the target is the codec metadata in descriptor-meta.ts, and the
driver package moves to devDependencies.
Integration tests that built a runner from a family instance with an
empty control stack now put the adapter on the stack, since the runner
reaches the database through it.
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]>
createMongoRunnerDeps duplicated MongoControlAdapterImpl.createRunnerDependencies and carried an unused family parameter. The builder now lives only in the adapter method, which checks the control driver once and reads its db directly. runner-deps.ts is gone: extractDb and requireMongoControlDriver move to mongo-control-driver.ts, which removes the import cycle with mongo-control-adapter.ts. Test callers, including three example tests, build runner dependencies with MongoControlAdapterImpl.createRunnerDependencies(controlDriver), and the fake family instances that only fed the unused parameter are deleted. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
ADR 198 composition example now shows MongoControlAdapter.createRunnerDependencies, the family instance forwarding, and the target createRunner call. The family README lists createRunnerDependencies, MongoRunnerDependencies and MarkerOperations. The subsystem doc drops the createMongoRunnerDeps sentence. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ft recorded as open item Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The test only checked the executor type, so it passed with the executor bound to any Db. It now stubs listCollections on the fake driver db and asserts the executor returns those rows. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…rface Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The target now owns codec-ids, codecs (descriptors, mongoDescriptorById, mongoStandardCodecs, buildStandardCodecRegistry), data-types and the one CodecTypes map with the Vector brand, exported as ./codecs, ./codec-ids, ./data-types and ./codec-types. The codecs throw through mongoTargetError, which gains RUNTIME.DECODE_FAILED and RUNTIME.TYPE_PARAMS_INVALID; the adapter error union drops them. bson moves from the adapter to the target. The adapter depends on the target: its runtime descriptor still registers the standard codec registry, mongoScalarAuthoringTypes takes the ids from the target, and emitted contracts import @internal/target-mongo/codec-types. The adapter codec subpaths, tsdown entries and published shell subpaths are gone; the shells publish target/codecs, target/codec-ids, target/data-types. The target no longer depends on the adapter at all. Its five runner tests that need a real control adapter and mongodb-memory-server move to test/integration/test/mongo/target-runner, as the Postgres runner tests live outside the target. architecture.config.json registers the target src/core and src/exports/control.ts. Framework tests that named the Mongo codec-types package as sample data use a neutral name, since framework code may not name a target package. Emitted contract.d.ts files are regenerated in the next commit. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
39 files come from pnpm fixtures:emit (examples, their migration snapshots, and the integration fixtures), each changing only the codec-types import. The ORM fixture in mongo-contract comes from generate-orm-fixture.ts, which now also writes the family package copy of the same contract. The family migration-contract fixture comes from scripts/regen-mongo-end-contract-dts.mjs. Both family fixtures were older than the current emitter, so they pick up its current output (Models namespace, RelationKeys) beyond the import line. The value-objects mongo-contract.d.ts fixture is hand-written (no header, no generator; its test asserts its exact mutable shapes), so only its import specifier changes. 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]>
…s required Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…a the adapter SPI App and extension fragments for slice 1: the adapter codec subpaths (codec-types, codecs, codec-ids, data-types) move to the target, createMongoRunnerDeps is replaced by MongoControlAdapterImpl.createRunnerDependencies, the runner dependency types move to the family control-adapter module, the control adapter SPI gains createRunnerDependencies, and createRunner needs the adapter on the control stack. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ort source The detection for mongo-runner-dependency-types-move-to-family matched the bare type names, so it fired on already-migrated imports and on every use site. It now matches only an import of those names from the adapter or target control entrypoint. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
mongo/int64@1 stores a bigint as BSON long. Decode also takes the number the driver promotes a small long to; the JSON form is decimal text and a safe-integer number is accepted on the way in, as pg/int8@1 does; a decimal-text default renders as a bigint literal. mongo/decimal128@1 stores decimal text as BSON decimal. Decimal128 prints some values with an exponent; the codec rewrites them without one and keeps trailing zeros, so the text matches the Postgres numeric convention and is stable across a round trip. mongo/binary@1 stores a Uint8Array as BSON binData with unwrapped base64 as its JSON form. mongo/json@1 stores any JSON value as the BSON value it maps to and declares no BSON type. Decode checks the BSON type tag rather than instanceof, because the driver deserialises with its own load of bson. A wrong wire type throws RUNTIME.DECODE_FAILED from the target error factory, which gains RUNTIME.ENCODE_FAILED for refused application values. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
derive-json-schema dropped a field whose codec declares no targetTypes.
The validator is closed with additionalProperties: false, so the server
then rejected every document carrying that field. A known codec with no
BSON type now gets an empty schema ({}, or an array of {} for a list),
which admits any value; an unknown codec is still left out.
Contract canonicalisation drops empty objects, so the Mongo hooks now
preserve an empty schema under a jsonSchema properties map or as items.
Existing contracts have no such schema, so no hash moves.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The adapter names the PSL scalars Int64, Decimal128, Binary and Json, with nativeType long, decimal and binData, and json for Json, whose codec has no BSON type (the validator reads the codec targetTypes, not this value). The TS builder gains field.int64(), field.decimal128(), field.binary() and field.json(), and its local CodecTypes copy gains the four entries: bigint, string, Uint8Array and JsonValue. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
A PSL fixture with all four types is emitted by the real CLI (the emit script now covers test/mongo/bson-scalars), pushed through plan and apply so the collection carries the derived validator, written through the ORM, checked in raw storage as Long, Decimal128 and Binary, and read back decoded as bigint, decimal text, Uint8Array and JSON. The emitted contract.d.ts types each field through CodecTypes and the row types are asserted. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ary and Json 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]>
…s, extreme decimals Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Long.fromBigInt keeps the low 64 bits, so 2n ** 64n was stored as 0 and 2n ** 63n as -2^63 without error. Encode and encodeJson now throw RUNTIME.ENCODE_FAILED outside [-(2n ** 63n), 2n ** 63n - 1n], and decodeJson throws RUNTIME.DECODE_FAILED, so a contract default cannot hold a value the collection cannot store. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
main changed interpretPslDocumentToMongoContract to take documents: [...] for multi-file PSL (#30379). This test was added on the branch with the old document field. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
main now emits only PSL files that carry the "// use prisma-8" directive (#30379), so the branch-added fixture schema needs it. 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]>
…pers TIMESTAMP_NOW_GENERATOR_ID, timestampNowControlDescriptor, temporalAuthoringPresets, temporalCodecPreset, TEMPORAL_ON_CREATE_ARG, TEMPORAL_ON_UPDATE_ARG and temporalPhaseTemplate move to framework-components so the Mongo family can build the same temporal presets as SQL. getAuthoringFieldPreset and checkUncomposedNamespace, which use only framework types, move with them. The preset builders take the target codec storage template (PresetStorageTemplate) and carry it through, so the framework code names no storage-type field of its own; the framework vocabulary count is unchanged. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
family-sql keeps temporalCodecPresetWithPrecision, TEMPORAL_PRECISION_ARG and temporalStringAuthoringPresets and builds them from the framework pieces; its control export drops the hoisted names. The Postgres and SQLite targets and adapters import them from framework-components, and SQL contract-psl imports getAuthoringFieldPreset and checkUncomposedNamespace from there. temporalStringAuthoringPresets takes the same generic parameters as the framework pair so the two stay interchangeable. Behaviour is unchanged. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The Mongo runtime no longer depends on the target, so the slice 1 unit test that decoded a double with the real Decimal128 codec could not import it. The runtime unit test now uses a stub codec that throws the target's structured error shape, and the real codec case runs in test/integration/test/mongo/runtime/decode.integration.test.ts against a document holding a double. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
One conflict, in the MongoDB family subsystem doc's known-limitations bullet: main dropped an internal label and this branch renamed Float to Double. Kept both changes. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The test main added maps Int to mongo/int32@1; the Mongo PSL name is Int32. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Brings in origin/main through slice 1, including the eager PSL binder. Conflicts, all from the binder meeting this branch's move of the field-preset helpers to the framework: - SQL contract-psl (interpreter, psl-column-resolution, psl-field-resolution, psl-relation-resolution): kept the helpers in the framework and main's binder threading. main's new uncomposedNamespaceDiagnostic moves with them into psl-parser/interpret, and reportUncomposedNamespace builds on it as in main. - Mongo PSL interpreter: took main's binder, which now reports unknown attributes, and kept this branch's preset context and execution-defaults map beside it. The @updatedat hint that pointed to temporal.updatedAt() now lives in the binder's hint table in mongo-attribute-specs. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
wmadden
approved these changes
Sep 25, 2026
ContractSourceDiagnostic gains severity ('error' | 'warning', absent means error), and ContractSourceContext an optional reportWarning. Providers keep their Result return types: a source reports a warning through the context and still returns ok(contract). executeContractEmit and the control client collect the warnings into sourceWarnings, loadContractSource forwards them to an onWarning option, prisma contract emit prints each as 'warning <file>:<line>:<column> <code> <message>', and the language server passes a collector to interpret and shows the warnings with warning severity at their span.
Tests: a source that reports a warning emits the same contract as one that does not and returns the warning; a source whose diagnostics are all errors still fails; the CLI prints the warning; the language server shows it at its span.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Int, Float, Boolean and DateTime are registered again in mongoScalarAuthoringTypes as aliases of Int32, Double, Bool and Date, with the same codec id and native type and a deprecated: { replacement } field, which AuthoringTypeConstructorDescriptor now allows. A field typed with an alias resolves as before; the Mongo PSL interpreter reports PSL_DEPRECATED_SCALAR_NAME at the type through the context's reportWarning: Scalar type "Int" is deprecated and will be removed; use "Int32" (stored as BSON int). With no sink supplied the warning is dropped. The hard-error RENAMED_SCALARS table is gone: the alias entry is the one source.
Tests: each of the four names warns with the exact message at the type and interprets to the contract its replacement gives; through the real Mongo stack, the deprecated and current spellings serialize to byte-identical contract.json with one warning per deprecated use; the adapter pins the four aliases.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
mongo-psl-scalar-names now says the old names are still accepted with a PSL_DEPRECATED_SCALAR_NAME warning, will be removed in a later release, and should be renamed now, and tells the docs update to list only Int32, Double, Bool and Date. The detection pattern and the rewrite table are unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The codec authoring guide and the MongoDB family subsystem doc each say in one sentence that Int, Float, Boolean and DateTime are deprecated aliases that warn; the error reference gains PSL_DEPRECATED_SCALAR_NAME. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
buildMongoExecutionSection sorted refs with localeCompare, so the order of execution defaults, and therefore executionHash, depended on the process locale. It now compares namespace, entry and field by UTF-16 code unit. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
migration-contract.d.ts was stale: Order.type and Product.status are value-set references that the Mongo emitter renders as literal unions, and the namespace kind is mongo-database. regen-mongo-end-contract-dts.mjs reproduces the stale file because it calls the type generator without the stack's codec lookup, so the file is regenerated through the emitter's emit with the Mongo control stack, as prisma contract emit does. orm-contract.json beside it is a partial fixture (no capabilities, extensions or meta) that the emitter rejects; its declaration is left as it is. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…te refs An execution default is keyed by namespace, collection and field, so a preset on a field declared only on a polymorphic variant filled that field on the base model and every sibling variant too. Both authoring paths now reject it: PSL reports PSL_PRESET_ON_VARIANT_FIELD at the preset, and the TS builder throws CONTRACT.DEFAULT_INVALID with reason executionDefaults-on-variant. A preset on the base model stays allowed and fills every variant create. Two models stored in one collection can declare the same field. Identical execution defaults for it now merge into one ref; different ones report PSL_PRESET_CONFLICT (PSL) or CONTRACT.DEFAULT_INVALID with reason executionDefaults-conflict (TS). The temporal-presets integration fixture gains a polymorphic Event model with a base createdAt preset, confirming one ref and a filled createdAt on each variant create. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Scalar completion offered the four deprecated Mongo aliases beside their replacements. A scalar whose type constructor carries deprecated now sorts after every other candidate, has the Deprecated tag so editors strike it through, and its detail names the replacement. Name resolution and highlighting still treat the aliases as scalars. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
It called generateContractDts without the stack's codec lookup, so it wrote stale types. It now hydrates the contract through the Mongo family and runs the emitter's emit with the Mongo control stack. Running it on the family migration fixture reproduces the committed migration-contract.d.ts. Co-Authored-By: Claude Opus 5.5 (1M context) <[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]>
The Mongo interpreter passes both the preset context and the deprecated-scalar warner to field resolution. The SQL validators keep this branch's move of the execution schema into the framework contract package. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Main's only new commit is the squash merge of #30396, whose tree equals the slice 1 head this branch already merged, so every conflict resolves to this branch's side and the tree is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
wmadden-electric
enabled auto-merge
September 25, 2026 15:19
wmadden-electric
added a commit
that referenced
this pull request
Sep 27, 2026
Main's only new commit is the squash merge of #30403, whose tree equals the slice 3 head this branch already merged, so every conflict resolves to this branch's side and the tree is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
xb18
pushed a commit
to xb18/prisma-orm
that referenced
this pull request
Sep 27, 2026
…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]>
Thegreatsura
pushed a commit
to Thegreatsura/prisma
that referenced
this pull request
Sep 28, 2026
…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]>
This was referenced Sep 28, 2026
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.
A Mongo schema in Prisma 8 can now declare automatic timestamps, the same way a Postgres schema does:
orm.post.create({ data: { title: 'x' } })writes both timestamps. An update with a non-empty payload advancesupdatedAt; 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:@updatedAtwas 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 sameexecutionsection ({ ref: { namespace, entry, field }, onCreate, onUpdate }, hashed intoexecutionHash). 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 thetimestampNowcontrol descriptor, the PSL field-preset resolution helpers, the arktype schema for the execution section, and the TypeScript helpers that turn a pack'sauthoring.fieldnamespace into callablefield.*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'stemporalAuthoringPresetsandtemporalCodecPresetonmongo/date@1, plus thetimestampNowcontrol 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/interpretand@internal/framework-components/authoring). Diagnostics mirror SQL: a preset on an optional field, a list, or an@idfield, an unknown preset, an uncomposed namespace, or a bad argument each get the SQL code. Two refusals are Mongo-only and reportPSL_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.@updatedAtstill errors, now pointing attemporal.updatedAt().TypeScript.
field.temporal.*is composed from the packs'authoring.fieldnamespaces 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 throwCONTRACT.DEFAULT_INVALID. Both paths build theexecutionsection through one function in@internal/mongo-contractthat sorts by namespace, entry, field and computesexecutionHash; the arktype schema for the section now lives once in@internal/contractand both families' validators import it.Runtime.
createMongoExecutionContextcollectsmutationDefaultGeneratorsfrom 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 exposesapplyMutationDefaultswith 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. ThetimestampNowruntime 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
MongoMutationDefaultsinterface in@internal/mongo-contractthat the execution context satisfies;mongoOrmtakes it as amutationDefaultsoption andmongo()passes the context through; buildingmongoOrmby hand without it, for a contract that declares generators, throwsORM.MUTATION_DEFAULTS_MISSINGnaming the fix rather than silently writing documents without their timestamps.create,createAll,createAndCount, and the insert half ofupsertapplyonCreate;update,updateAll,updateAndCount, and the update half ofupsertapplyonUpdateonly when the payload is non-empty. Generated fields are optional on the create input type on both the emittedcontract.d.tspath and the no-emit TypeScript path.What you will see in the diff
@internal/family-sql/controlno longer exports the temporal builders (they are in@internal/framework-components/authoringand/control), which thetemporal-presets-move-to-frameworkupgrade fragment covers.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.test/integration/test/mongo/temporal-presets/with the same model authored in PSL and in TS. The two emit an identicalexecutionsection andexecutionHash.mongo-execution-defaults: hand-writtenMongoExecutionContextobjects must now provideapplyMutationDefaults. Application code needs no change.Alternatives considered
@default(now())and@updatedAtattributes 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.executiontype with model and field refs. Rejected after it produced over a thousand type errors; the framework ref was renamed to neutral names in refactor(contract): execution default refs name an entry and a field, not a table and a column #30399 instead.Known gaps recorded for later: PSL- and TS-authored Mongo contracts still differ in
storageHashand validators for reasons that predate this PR, and SQL sorts execution defaults without the namespace key.🤖 Generated with Claude Code
Summary by CodeRabbit
createdAt,updatedAt, and custom timestamps on create and update operations.