Repository navigation
TML-2888: Mongo migration DDL lowers through the adapter; executor retired - #816
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR centralizes codec-descriptor lookup via resolveCodecDescriptorOrThrow and implements end-to-end Mongo DDL support: query-builder DDL APIs, DDL AST shape changes, DDL lowering to wire commands, adapter/driver execution paths, migration factory updates, utilities, and extensive tests. ChangesMongoDB DDL Infrastructure and Codec Resolution
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
size-limit report 📦
|
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts (1)
35-41: ⚡ Quick winReplace bare cast in production code.
Line 40 uses
undefined as never; usecastAs<never>(undefined)to follow repo casting rules.As per coding guidelines, production TS/JS must not use bare
ascasts; useblindCast<T, "Reason">orcastAs<T>instead.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts` around lines 35 - 41, In next() replace the bare TypeScript cast "undefined as never" with the repo casting helper—call castAs<never>(undefined) (or blindCast<never, "Reason">(undefined) if a reason is required) so the return becomes { done: true, value: castAs<never>(undefined) }; update the line in the async next() implementation that references started and start() accordingly to remove the bare "as" cast.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts`:
- Around line 230-231: The current executeCollModCommand builds the command with
{ collMod: cmd.collection, ...cmd.options } which allows cmd.options.collMod to
override the target; fix by ensuring collMod cannot be overridden: construct the
command by copying cmd.options into a new object, delete newOptions.collMod if
present (or build via Object.assign with collMod as the target first), then call
this.db.command({ collMod: cmd.collection, ...newOptions }); reference:
executeCollModCommand, CollModWireCommand, cmd.collection, cmd.options.
- Around line 30-44: The lazyDdlIterable currently declares the started flag
inside the async iterator factory so each call to
iterable[Symbol.asyncIterator]() re-runs start(), causing duplicate DDL; move
the started state (and preferably the pending start Promise) out to the
lazyDdlIterable closure so it is shared across all iterators, ensure you call
the provided start() only once by checking/setting the shared started flag or
awaiting the shared start Promise before returning { done: true }, and keep
references to lazyDdlIterable, the start() callback, the started flag and the
[Symbol.asyncIterator] implementation when making this change.
In `@packages/3-mongo-target/3-mongo-driver/test/mongo-driver.test.ts`:
- Around line 350-364: The test currently advances the same iterator twice, so
change it to start a fresh async iteration to verify the DDL iterable is not
re-executed: after calling iterator.next() for the first pass, obtain a new
iterator from iterable via iterable[Symbol.asyncIterator]() (e.g., const
secondIterator = iterable[Symbol.asyncIterator]()) and call
secondIterator.next() and assert that returns { done: true, value: undefined };
update the test that uses CreateCollectionWireCommand, MongoDriverImpl.fromDb
and driver.execute to use the new iterator rather than reusing the original one.
---
Nitpick comments:
In `@packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts`:
- Around line 35-41: In next() replace the bare TypeScript cast "undefined as
never" with the repo casting helper—call castAs<never>(undefined) (or
blindCast<never, "Reason">(undefined) if a reason is required) so the return
becomes { done: true, value: castAs<never>(undefined) }; update the line in the
async next() implementation that references started and start() accordingly to
remove the bare "as" cast.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 164dd812-d392-4f51-ad5c-8d5b825df502
⛔ Files ignored due to path filters (8)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/migrate-marker-ledger-to-typed-query-ast-commands/design-notes.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/mongo-planner-create-collection-and-index-adoption/dispatches/01-adapter-lowering-and-runner-unification.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/mongo-planner-create-collection-and-index-adoption/dispatches/02-builder-terminals-and-construction.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/mongo-planner-create-collection-and-index-adoption/dispatches/03-codec-resolution-dedup.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/mongo-planner-create-collection-and-index-adoption/plan.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/mongo-planner-create-collection-and-index-adoption/reviews/code-review.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/mongo-planner-create-collection-and-index-adoption/spec.mdis excluded by!projects/**
📒 Files selected for processing (25)
packages/1-framework/1-core/framework-components/src/control/control-stack.tspackages/1-framework/1-core/framework-components/src/exports/codec.tspackages/1-framework/1-core/framework-components/src/shared/resolve-codec.tspackages/1-framework/1-core/framework-components/test/control-stack.test.tspackages/2-mongo-family/4-query/query-ast/src/filter-expressions.tspackages/2-mongo-family/5-query-builders/query-builder/src/contract-free/collection.tspackages/2-mongo-family/5-query-builders/query-builder/test/collection-ddl.test.tspackages/2-mongo-family/6-transport/mongo-lowering/src/adapter-types.tspackages/2-mongo-family/6-transport/mongo-lowering/src/exports/index.tspackages/2-mongo-family/6-transport/mongo-wire/src/exports/index.tspackages/2-mongo-family/6-transport/mongo-wire/src/wire-commands.tspackages/2-sql/5-runtime/src/codecs/ast-codec-resolver.tspackages/3-mongo-target/1-mongo-target/package.jsonpackages/3-mongo-target/1-mongo-target/src/core/migration-factories.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-runner.tspackages/3-mongo-target/1-mongo-target/test/mongo-runner.test.tspackages/3-mongo-target/2-mongo-adapter/src/core/command-executor.tspackages/3-mongo-target/2-mongo-adapter/src/core/inspection-executor.tspackages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.tspackages/3-mongo-target/2-mongo-adapter/src/exports/control.tspackages/3-mongo-target/2-mongo-adapter/src/mongo-adapter.tspackages/3-mongo-target/2-mongo-adapter/test/command-executor.test.tspackages/3-mongo-target/2-mongo-adapter/test/ddl-lowering-oracle.test.tspackages/3-mongo-target/3-mongo-driver/src/mongo-driver.tspackages/3-mongo-target/3-mongo-driver/test/mongo-driver.test.ts
💤 Files with no reviewable changes (1)
- packages/3-mongo-target/2-mongo-adapter/src/core/command-executor.ts
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
packages/3-mongo-target/3-mongo-driver/test/mongo-driver.test.ts (1)
479-493:⚠️ Potential issue | 🟠 Major | ⚡ Quick winThe double-iteration laziness test doesn’t validate a second iteration pass.
At Line 488–492, this advances the same iterator twice, which only checks iterator exhaustion. It doesn’t prove that re-iterating
iterableavoids re-executing DDL.Proposed fix
- const iterator = iterable[Symbol.asyncIterator](); - - await iterator.next(); - const second = await iterator.next(); - expect(second).toEqual({ done: true, value: undefined }); + await collect(iterable); + await expect(collect(iterable)).resolves.toEqual([]);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-mongo-target/3-mongo-driver/test/mongo-driver.test.ts` around lines 479 - 493, The test currently advances the same iterator twice so it only checks exhaustion; change it to obtain a fresh async iterator from the iterable for the second pass (call iterable[Symbol.asyncIterator]() again) and advance that new iterator to ensure re-iterating the iterable does not re-execute the DDL. Update the assertions to verify the second iterator immediately yields { done: true, value: undefined } after the first pass, keeping references to CreateCollectionWireCommand, driver.execute, iterable and Symbol.asyncIterator to locate the code.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/3-mongo-target/3-mongo-driver/test/mongo-driver.test.ts`:
- Around line 436-456: The test "applies collMod options to the collection"
currently only asserts the collection exists but not that the
validator/validationLevel were applied; update the test after calling
driver.execute(new CollModWireCommand(col, {...})) to retrieve the collection
metadata (e.g., call db.listCollections({ name: col }).toArray() or db.command({
listCollections: 1, filter: { name: col } }) and inspect the returned collection
options) and add assertions that the returned collection object contains the
validator and validationLevel fields matching the values sent, or alternatively
perform a behavioral check by attempting an insert that violates the validator
and asserting it is rejected; reference CollModWireCommand, driver.execute,
MongoDriverImpl.fromDb, and the collection name 'driver_collmod' when making the
changes.
---
Duplicate comments:
In `@packages/3-mongo-target/3-mongo-driver/test/mongo-driver.test.ts`:
- Around line 479-493: The test currently advances the same iterator twice so it
only checks exhaustion; change it to obtain a fresh async iterator from the
iterable for the second pass (call iterable[Symbol.asyncIterator]() again) and
advance that new iterator to ensure re-iterating the iterable does not
re-execute the DDL. Update the assertions to verify the second iterator
immediately yields { done: true, value: undefined } after the first pass,
keeping references to CreateCollectionWireCommand, driver.execute, iterable and
Symbol.asyncIterator to locate the code.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 3d7ea925-f1f9-496f-9360-58a0460b0c8d
📒 Files selected for processing (1)
packages/3-mongo-target/3-mongo-driver/test/mongo-driver.test.ts
wmadden
left a comment
There was a problem hiding this comment.
Good start but there are some areas which need improemvement
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts (1)
574-580:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winFinish migrating planner assertions to
cmd.options.Line 576-580 and Line 1348 still read removed top-level properties (
weights,default_language,language_override,collation,wildcardProjection, andchangeStreamPreAndPostImages). With the new DDL command shape, this test file no longer typechecks. These assertions need to read fromcmd.optionsinstead.Suggested fix
- expect(cmd.weights).toEqual({ bio: 10 }); - expect(cmd.default_language).toBe('english'); - expect(cmd.language_override).toBe('lang'); - expect(cmd.collation).toEqual({ locale: 'en' }); - expect(cmd.wildcardProjection).toEqual({ bio: 1 }); + expect(cmd.options?.weights).toEqual({ bio: 10 }); + expect(cmd.options?.default_language).toBe('english'); + expect(cmd.options?.language_override).toBe('lang'); + expect(cmd.options?.collation).toEqual({ locale: 'en' }); + expect(cmd.options?.wildcardProjection).toEqual({ bio: 1 });- expect(cmd.changeStreamPreAndPostImages).toEqual({ enabled: false }); + expect(cmd.options.changeStreamPreAndPostImages).toEqual({ enabled: false });Also applies to: 1347-1348
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts` around lines 574 - 580, The test is still asserting removed top-level properties on the CreateIndexCommand; update the expectations to read from the new options object. Replace references like cmd.weights, cmd.default_language, cmd.language_override, cmd.collation, cmd.wildcardProjection with cmd.options.weights, cmd.options.default_language, cmd.options.language_override, cmd.options.collation, cmd.options.wildcardProjection respectively (and similarly change cmd.changeStreamPreAndPostImages to cmd.options.changeStreamPreAndPostImages at the other occurrence), ensuring assertions use the CreateIndexCommand instance named cmd and its options field.packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts (1)
494-556:⚠️ Potential issue | 🟠 MajorTighten the new DDL option narrowing.
CreateIndexJson/CreateCollectionJson/CollModJsondefinewildcardProjection?,weights?,timeseries?,changeStreamPreAndPostImages?, andclusteredIndex?asRecord<string, unknown>, so the only thing making them concrete option types happens via the rawascasts indeserializeDdlCommand(e.g.,wildcardProjection as Record<string, 0 | 1> | undefined,weights as Record<string, number> | undefined, etc.). This bypasses the arktype boundary and can let malformed ops through (e.g., non-numericweights, invalidwildcardProjectionvalues).Update the arktype schemas to validate these fields precisely (preferred) or replace the raw
ascasts with the repo cast helpers (blindCast/castAsfrom@prisma-next/utils/casts).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts` around lines 494 - 556, deserializeDdlCommand currently narrows fields like wildcardProjection, weights, timeseries, changeStreamPreAndPostImages, and clusteredIndex via raw TypeScript casts which bypass arktype validation and can allow malformed DDL; update the corresponding arktype schemas (CreateIndexJson, CreateCollectionJson, CollModJson) to precisely validate these properties (e.g., wildcardProjection values are 0|1, weights are numeric, timeseries shape, changeStreamPreAndPostImages and clusteredIndex shapes) so validate(...) returns correctly typed values, or if you prefer not to touch schemas, replace the raw casts in deserializeDdlCommand with the repo cast helpers blindCast/castAs from `@prisma-next/utils/casts` for each field (references: function deserializeDdlCommand and types CreateIndexJson/CreateCollectionJson/CollModJson and their properties wildcardProjection, weights, timeseries, changeStreamPreAndPostImages, clusteredIndex).Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts`:
- Around line 70-74: Replace the bare `as` casts in the exhaustive default/error
branches with the repo helper `blindCast` (already imported) to satisfy the
no-bare-casts rule: instead of `(_exhaustive as { kind: string }).kind` call
`blindCast<{ kind: string }, "Unknown wire command">(wireCommand).kind` (or
equivalent `blindCast` typing) when building the error message in the
`default`/exhaustive cases that reference `wireCommand`; apply the same
replacement for the second occurrence of the bare `as` in the other exhaustive
branch so both error-throwing branches use `blindCast` and not `as`.
In `@packages/3-mongo-target/3-mongo-driver/test/mongo-driver.test.ts`:
- Around line 460-467: The test currently only asserts that
MongoDriverImpl.fromDb(db).run(new
DropCollectionWireCommand('nonexistent_collection_xyz')) rejects; change it to
assert the specific MongoServerError is propagated (and optionally its
code/codeName) instead of a generic rejection: catch the rejection using Jest's
.rejects.toThrow or .rejects.toMatchObject targeting MongoServerError and assert
expected fields (e.g., name === 'MongoServerError' and code/codeName) so the
test verifies that run() passes the original server error through unchanged.
---
Outside diff comments:
In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts`:
- Around line 494-556: deserializeDdlCommand currently narrows fields like
wildcardProjection, weights, timeseries, changeStreamPreAndPostImages, and
clusteredIndex via raw TypeScript casts which bypass arktype validation and can
allow malformed DDL; update the corresponding arktype schemas (CreateIndexJson,
CreateCollectionJson, CollModJson) to precisely validate these properties (e.g.,
wildcardProjection values are 0|1, weights are numeric, timeseries shape,
changeStreamPreAndPostImages and clusteredIndex shapes) so validate(...) returns
correctly typed values, or if you prefer not to touch schemas, replace the raw
casts in deserializeDdlCommand with the repo cast helpers blindCast/castAs from
`@prisma-next/utils/casts` for each field (references: function
deserializeDdlCommand and types CreateIndexJson/CreateCollectionJson/CollModJson
and their properties wildcardProjection, weights, timeseries,
changeStreamPreAndPostImages, clusteredIndex).
In `@packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts`:
- Around line 574-580: The test is still asserting removed top-level properties
on the CreateIndexCommand; update the expectations to read from the new options
object. Replace references like cmd.weights, cmd.default_language,
cmd.language_override, cmd.collation, cmd.wildcardProjection with
cmd.options.weights, cmd.options.default_language,
cmd.options.language_override, cmd.options.collation,
cmd.options.wildcardProjection respectively (and similarly change
cmd.changeStreamPreAndPostImages to cmd.options.changeStreamPreAndPostImages at
the other occurrence), ensuring assertions use the CreateIndexCommand instance
named cmd and its options field.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: d63e1eb8-f347-4696-a168-0b4ca35c4b3c
📒 Files selected for processing (21)
packages/1-framework/0-foundation/utils/src/defined.tspackages/1-framework/0-foundation/utils/src/exports/defined.tspackages/1-framework/0-foundation/utils/test/defined.test.tspackages/2-mongo-family/4-query/query-ast/src/ddl-commands.tspackages/2-mongo-family/4-query/query-ast/test/ddl-commands.test.tspackages/2-mongo-family/5-query-builders/query-builder/test/collection-ddl.test.tspackages/2-mongo-family/6-transport/mongo-lowering/src/adapter-types.tspackages/2-mongo-family/6-transport/mongo-lowering/src/driver-types.tspackages/2-mongo-family/6-transport/mongo-wire/src/exports/index.tspackages/2-mongo-family/6-transport/mongo-wire/src/wire-commands.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-runner.tspackages/3-mongo-target/1-mongo-target/test/migration-factories.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-ops-serializer.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-planner.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-runner.test.tspackages/3-mongo-target/2-mongo-adapter/src/core/mongo-control-adapter.tspackages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.tspackages/3-mongo-target/2-mongo-adapter/src/mongo-adapter.tspackages/3-mongo-target/3-mongo-driver/src/mongo-driver.tspackages/3-mongo-target/3-mongo-driver/test/mongo-driver.test.ts
✅ Files skipped from review due to trivial changes (1)
- packages/1-framework/0-foundation/utils/src/exports/defined.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- packages/2-mongo-family/5-query-builders/query-builder/test/collection-ddl.test.ts
- packages/2-mongo-family/6-transport/mongo-lowering/src/adapter-types.ts
- packages/3-mongo-target/2-mongo-adapter/src/mongo-adapter.ts
- packages/3-mongo-target/1-mongo-target/test/mongo-runner.test.ts
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts (1)
574-580:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winFinish migrating planner assertions to
cmd.options.Line 576-580 and Line 1348 still read removed top-level properties (
weights,default_language,language_override,collation,wildcardProjection, andchangeStreamPreAndPostImages). With the new DDL command shape, this test file no longer typechecks. These assertions need to read fromcmd.optionsinstead.Suggested fix
- expect(cmd.weights).toEqual({ bio: 10 }); - expect(cmd.default_language).toBe('english'); - expect(cmd.language_override).toBe('lang'); - expect(cmd.collation).toEqual({ locale: 'en' }); - expect(cmd.wildcardProjection).toEqual({ bio: 1 }); + expect(cmd.options?.weights).toEqual({ bio: 10 }); + expect(cmd.options?.default_language).toBe('english'); + expect(cmd.options?.language_override).toBe('lang'); + expect(cmd.options?.collation).toEqual({ locale: 'en' }); + expect(cmd.options?.wildcardProjection).toEqual({ bio: 1 });- expect(cmd.changeStreamPreAndPostImages).toEqual({ enabled: false }); + expect(cmd.options.changeStreamPreAndPostImages).toEqual({ enabled: false });Also applies to: 1347-1348
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts` around lines 574 - 580, The test is still asserting removed top-level properties on the CreateIndexCommand; update the expectations to read from the new options object. Replace references like cmd.weights, cmd.default_language, cmd.language_override, cmd.collation, cmd.wildcardProjection with cmd.options.weights, cmd.options.default_language, cmd.options.language_override, cmd.options.collation, cmd.options.wildcardProjection respectively (and similarly change cmd.changeStreamPreAndPostImages to cmd.options.changeStreamPreAndPostImages at the other occurrence), ensuring assertions use the CreateIndexCommand instance named cmd and its options field.packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts (1)
494-556:⚠️ Potential issue | 🟠 MajorTighten the new DDL option narrowing.
CreateIndexJson/CreateCollectionJson/CollModJsondefinewildcardProjection?,weights?,timeseries?,changeStreamPreAndPostImages?, andclusteredIndex?asRecord<string, unknown>, so the only thing making them concrete option types happens via the rawascasts indeserializeDdlCommand(e.g.,wildcardProjection as Record<string, 0 | 1> | undefined,weights as Record<string, number> | undefined, etc.). This bypasses the arktype boundary and can let malformed ops through (e.g., non-numericweights, invalidwildcardProjectionvalues).Update the arktype schemas to validate these fields precisely (preferred) or replace the raw
ascasts with the repo cast helpers (blindCast/castAsfrom@prisma-next/utils/casts).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts` around lines 494 - 556, deserializeDdlCommand currently narrows fields like wildcardProjection, weights, timeseries, changeStreamPreAndPostImages, and clusteredIndex via raw TypeScript casts which bypass arktype validation and can allow malformed DDL; update the corresponding arktype schemas (CreateIndexJson, CreateCollectionJson, CollModJson) to precisely validate these properties (e.g., wildcardProjection values are 0|1, weights are numeric, timeseries shape, changeStreamPreAndPostImages and clusteredIndex shapes) so validate(...) returns correctly typed values, or if you prefer not to touch schemas, replace the raw casts in deserializeDdlCommand with the repo cast helpers blindCast/castAs from `@prisma-next/utils/casts` for each field (references: function deserializeDdlCommand and types CreateIndexJson/CreateCollectionJson/CollModJson and their properties wildcardProjection, weights, timeseries, changeStreamPreAndPostImages, clusteredIndex).Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts`:
- Around line 70-74: Replace the bare `as` casts in the exhaustive default/error
branches with the repo helper `blindCast` (already imported) to satisfy the
no-bare-casts rule: instead of `(_exhaustive as { kind: string }).kind` call
`blindCast<{ kind: string }, "Unknown wire command">(wireCommand).kind` (or
equivalent `blindCast` typing) when building the error message in the
`default`/exhaustive cases that reference `wireCommand`; apply the same
replacement for the second occurrence of the bare `as` in the other exhaustive
branch so both error-throwing branches use `blindCast` and not `as`.
In `@packages/3-mongo-target/3-mongo-driver/test/mongo-driver.test.ts`:
- Around line 460-467: The test currently only asserts that
MongoDriverImpl.fromDb(db).run(new
DropCollectionWireCommand('nonexistent_collection_xyz')) rejects; change it to
assert the specific MongoServerError is propagated (and optionally its
code/codeName) instead of a generic rejection: catch the rejection using Jest's
.rejects.toThrow or .rejects.toMatchObject targeting MongoServerError and assert
expected fields (e.g., name === 'MongoServerError' and code/codeName) so the
test verifies that run() passes the original server error through unchanged.
---
Outside diff comments:
In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts`:
- Around line 494-556: deserializeDdlCommand currently narrows fields like
wildcardProjection, weights, timeseries, changeStreamPreAndPostImages, and
clusteredIndex via raw TypeScript casts which bypass arktype validation and can
allow malformed DDL; update the corresponding arktype schemas (CreateIndexJson,
CreateCollectionJson, CollModJson) to precisely validate these properties (e.g.,
wildcardProjection values are 0|1, weights are numeric, timeseries shape,
changeStreamPreAndPostImages and clusteredIndex shapes) so validate(...) returns
correctly typed values, or if you prefer not to touch schemas, replace the raw
casts in deserializeDdlCommand with the repo cast helpers blindCast/castAs from
`@prisma-next/utils/casts` for each field (references: function
deserializeDdlCommand and types CreateIndexJson/CreateCollectionJson/CollModJson
and their properties wildcardProjection, weights, timeseries,
changeStreamPreAndPostImages, clusteredIndex).
In `@packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts`:
- Around line 574-580: The test is still asserting removed top-level properties
on the CreateIndexCommand; update the expectations to read from the new options
object. Replace references like cmd.weights, cmd.default_language,
cmd.language_override, cmd.collation, cmd.wildcardProjection with
cmd.options.weights, cmd.options.default_language,
cmd.options.language_override, cmd.options.collation,
cmd.options.wildcardProjection respectively (and similarly change
cmd.changeStreamPreAndPostImages to cmd.options.changeStreamPreAndPostImages at
the other occurrence), ensuring assertions use the CreateIndexCommand instance
named cmd and its options field.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: d63e1eb8-f347-4696-a168-0b4ca35c4b3c
📒 Files selected for processing (21)
packages/1-framework/0-foundation/utils/src/defined.tspackages/1-framework/0-foundation/utils/src/exports/defined.tspackages/1-framework/0-foundation/utils/test/defined.test.tspackages/2-mongo-family/4-query/query-ast/src/ddl-commands.tspackages/2-mongo-family/4-query/query-ast/test/ddl-commands.test.tspackages/2-mongo-family/5-query-builders/query-builder/test/collection-ddl.test.tspackages/2-mongo-family/6-transport/mongo-lowering/src/adapter-types.tspackages/2-mongo-family/6-transport/mongo-lowering/src/driver-types.tspackages/2-mongo-family/6-transport/mongo-wire/src/exports/index.tspackages/2-mongo-family/6-transport/mongo-wire/src/wire-commands.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-runner.tspackages/3-mongo-target/1-mongo-target/test/migration-factories.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-ops-serializer.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-planner.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-runner.test.tspackages/3-mongo-target/2-mongo-adapter/src/core/mongo-control-adapter.tspackages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.tspackages/3-mongo-target/2-mongo-adapter/src/mongo-adapter.tspackages/3-mongo-target/3-mongo-driver/src/mongo-driver.tspackages/3-mongo-target/3-mongo-driver/test/mongo-driver.test.ts
✅ Files skipped from review due to trivial changes (1)
- packages/1-framework/0-foundation/utils/src/exports/defined.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- packages/2-mongo-family/5-query-builders/query-builder/test/collection-ddl.test.ts
- packages/2-mongo-family/6-transport/mongo-lowering/src/adapter-types.ts
- packages/3-mongo-target/2-mongo-adapter/src/mongo-adapter.ts
- packages/3-mongo-target/1-mongo-target/test/mongo-runner.test.ts
🛑 Comments failed to post (2)
packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts (1)
70-74:
⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAvoid bare casts in the exhaustive error paths.
Line 73 and Line 93 introduce bare
ascasts in production code. This repo’s TypeScript rule requiresblindCast<T, "Reason">orcastAs<T>instead, andblindCastis already imported here. Based on learnings, use the repo’s no-bare-casts rule: “No bareasin production code. UseblindCast<T, "Reason">orcastAs<T>from@prisma-next/utils/casts.”Proposed fix
default: { const _exhaustive: never = wireCommand; - throw new Error(`Unknown wire command kind: ${(_exhaustive as { kind: string }).kind}`); + throw new Error( + `Unknown wire command kind: ${blindCast<{ kind: string }, 'exhaustive diagnostic access'>( + _exhaustive, + ).kind}`, + ); } @@ default: { const _exhaustive: never = wireCommand; - throw new Error(`Unknown DDL wire command kind: ${(_exhaustive as { kind: string }).kind}`); + throw new Error( + `Unknown DDL wire command kind: ${blindCast< + { kind: string }, + 'exhaustive diagnostic access' + >(_exhaustive).kind}`, + ); }Also applies to: 90-94
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts` around lines 70 - 74, Replace the bare `as` casts in the exhaustive default/error branches with the repo helper `blindCast` (already imported) to satisfy the no-bare-casts rule: instead of `(_exhaustive as { kind: string }).kind` call `blindCast<{ kind: string }, "Unknown wire command">(wireCommand).kind` (or equivalent `blindCast` typing) when building the error message in the `default`/exhaustive cases that reference `wireCommand`; apply the same replacement for the second occurrence of the bare `as` in the other exhaustive branch so both error-throwing branches use `blindCast` and not `as`.Source: Coding guidelines
packages/3-mongo-target/3-mongo-driver/test/mongo-driver.test.ts (1)
460-467:
⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAssert the propagated Mongo error, not just “some rejection.”
Line 465 only checks that
run()rejects, so this still passes if the driver starts wrapping server failures in a genericError. If this test is meant to pin the propagation contract, assertMongoServerError(and ideally its code/codeName) directly.Proposed fix
describe('run() error propagation', () => { it('rejects when the server returns an error', async () => { const db = seedClient.db(dbName); const driver = MongoDriverImpl.fromDb(db); - await expect( - driver.run(new DropCollectionWireCommand('nonexistent_collection_xyz')), - ).rejects.toThrow(); + await expect( + driver.run(new DropCollectionWireCommand('nonexistent_collection_xyz')), + ).rejects.toBeInstanceOf(MongoServerError); }); });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-mongo-target/3-mongo-driver/test/mongo-driver.test.ts` around lines 460 - 467, The test currently only asserts that MongoDriverImpl.fromDb(db).run(new DropCollectionWireCommand('nonexistent_collection_xyz')) rejects; change it to assert the specific MongoServerError is propagated (and optionally its code/codeName) instead of a generic rejection: catch the rejection using Jest's .rejects.toThrow or .rejects.toMatchObject targeting MongoServerError and assert expected fields (e.g., name === 'MongoServerError' and code/codeName) so the test verifies that run() passes the original server error through unchanged.
ebcb9d6 to
86a0724
Compare
…ign notes Slice 6 (Mongo planner DDL through the adapter) — design settled with the operator: mirror the SQL adapter interface (lower() accepts DDL kinds → wire commands), unify the runner's DDL dispatch onto the data-transform path, retire MongoCommandExecutor, and construct in-scope ops through the contract-free collection() builder. Lowering happens at the runner boundary (execute-time) because Mongo serializes the typed node into ops.json, unlike PG which serializes the lowered sql. Carries the slice-7-deferred codec-resolution dedup as D3 on this branch (operator directive). 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]>
…, wire types, lowering oracle Extends the mongo wire-command union with five DDL members: CreateCollectionWireCommand, CreateIndexWireCommand, DropCollectionWireCommand, DropIndexWireCommand, CollModWireCommand. MongoAdapterImpl.lower dispatches all five DDL command kinds, producing typed wire structs instead of raw Document values. InspectionExecutor replaces the removed command-executor for the listCollections/listIndexes introspection path. Adds a 29-case DDL lowering oracle covering all five kinds, including option mapping, name placement, and undefined-omission. 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]>
…CommandExecutor MongoRunner now calls adapter.lower → driver.execute for DDL steps, using the same path as DML. MongoCommandExecutor is deleted. MongoDriverImpl.execute handles all five DDL wire-command kinds via eager async helpers wrapped in voidToAsyncIterable. Adds behavioral DDL test (command-executor.test.ts) against mongodb-memory-server covering all five kinds, including error fidelity for missing-index and missing-collection cases. Dispatch artifact: dispatches/01-adapter-lowering-and-runner-unification.md 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]>
…reateIndex (+ filter .and combinator) Add `.createCollection(options?)` and `.createIndex(keys, options?)` terminals to `CollectionBuilder` in `@prisma-next/mongo-query-builder/contract-free`. Both return canonical frozen nodes and reuse the existing `CreateCollectionOptions` / `CreateIndexOptions` / `MongoIndexKey` vocabulary. Add `MongoFilterExpr.and(other)` combinator alongside the existing `.not()` in filter-expressions.ts. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…s via field accessor
`createCollection()` and `createIndex()` in `migration-factories.ts` now build their execute-step
commands through `collection(name).createCollection(options)` / `.createIndex(keys, options)` rather
than `new CreateCollectionCommand(...)` / `new CreateIndexCommand(...)`. Check filters use
`createFieldAccessor<IndexInfoDocShape>()` / `createFieldAccessor<CollectionInfoDocShape>()` with
`f.rawPath('key._fts')` for the text-index sub-path, and `filter.and(f.unique.eq(true))` for the
unique postcheck fold. `rg` for the retired constructors in factories + op-factory-call is empty.
D2 dispatch artifact and spec DoD ticks (D1+D2 boxes) also included.
Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…olution onto the shared core Both forCodecRef implementations (framework extractCodecLookup and the SQL runtime createAstCodecResolver) independently did find-descriptor + throw-CODEC_DESCRIPTOR_MISSING + materialize. The find+throw half moves to resolveCodecDescriptorOrThrow in the shared resolver core; both call sites pass their existing descriptor index by reference. The two indexes themselves stay put (opposite sides of the framework/SQL plane split) — recorded in dispatches/03-codec-resolution-dedup.md. Carried from slice 7 (pg-add-column-pioneer) per operator directive. 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]>
…arms in the driver (review M1+M3) M1: Switch oracle from toMatchObject to exact toEqual on wire.options (and wire.key / wire.name where applicable), so an unintended extra option field causes a test failure rather than silently passing. The "omits undefined options" createIndex case is simplified to a single toEqual instead of three spot-checks. No parity gap was exposed — the lowering already emitted exactly the expected fields. M3: Replace voidToAsyncIterable (eager — started the promise at execute() call time) with lazyDdlIterable (a thunk-based AsyncIterable that only calls the DB method when the caller pumps the iterator). All five DDL switch arms now pass a () => this.executeX(cmd) thunk; the execute*Command methods remain plain async. Two new driver tests pin the contract: calling execute() without iterating performs no DB action, and iterating a second time is a no-op. 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]>
Add driver-package tests for createCollection, createIndex, dropCollection, dropIndex, and collMod wire commands, including options-carrying branches. Clears statements ≥95%, branches ≥91%, functions =100%. Signed-off-by: willbot <[email protected]> Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…od target + tests (CodeRabbit) Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Reverts the CodeRabbit-suggested spread reorder: MongoDB reads the command name from the first key, so spreading options first made the server reject the command (CommandNotFound: 'validator'). The override the reorder guarded against is unrepresentable — CollModOptions is typed and has no collMod key. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…aming masquerade Split AnyMongoWireCommand into AnyMongoDmlWireCommand + AnyMongoDdlWireCommand with an isDdlWireCommand predicate. Added MongoDriver.run(AnyMongoDdlWireCommand): Promise<void> (the DDL analog of SQL's driver.query). Implemented run() in MongoDriverImpl as a plain switch over the five DDL kinds; removed lazyDdlIterable and all DDL arms from execute(). MongoAdapter.lower() gains an overload so lower(MongoDdlPlan) resolves to AnyMongoDdlWireCommand, giving the runner a typed path without casts. The runner DDL loop now calls driver.run(wire) directly. Tests updated to use driver.run() for all DDL cases; laziness tests removed (construct is gone); rejection test added. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Will Madden <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…tions carrier; runner-test fixes in flight) Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…uteDdl/run) Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…nExecutor doc, preview reads options, DefinedProps) — mongo-wire utils dep still missing Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…t, mongo-wire/execution-plan ripple (gates not yet green) Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…er serialization 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]>
…drop toJSON; restore ops.json byte-parity Replace the nested this.options field + toJSON() hack on CreateIndexCommand, CreateCollectionCommand, and CollModCommand with flat readonly own-properties (identical field order to origin/main). Expose an options() prototype method (non-enumerable, never serialized) for typed access in the lowering layer. JSON.stringify now produces the canonical flat shape directly — no toJSON hook required. Fixtures are byte-identical to origin/main. Update all call-sites (lowering, operation-preview, test files) accordingly. Co-Authored-By: Claude Sonnet 4.6 <[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]>
…ind casts Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ontract + schema IR - mongo-contract/mongo-index.ts: collation field typed CollationOptions (was Record<string,unknown>) - mongo-schema-ir/schema-index.ts + schema-collection-options.ts: same - contract-psl/interpreter.ts: parseCollation returns CollationOptions directly (no cast needed) - family-mongo/contract-to-schema.ts: build CollationOptions explicitly from MongoCollationOptions fields to strip IR kind; collation from MongoIndex flows through directly - family-mongo/canonicalize-introspection.ts: add typed stripCollationFields wrapper; uses blindCast once at the Record<string,unknown>→CollationOptions boundary - introspect-schema.ts: blindCast at the BSON listIndexes/listCollections boundary (two entry points) Packages gaining mongodb dep: mongo-contract, mongo-schema-ir, family-mongo, mongo-contract-psl. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ort order (lint)
- op-factory-call.ts: remove the two blindCast<CollationOptions> wrappers; collation now flows
directly from MongoSchemaIndex/MongoSchemaCollectionOptions (both typed CollationOptions).
Also replace bare `{ _id: 1 } as Record<string,number>` with blindCast<Record<string,number>>.
Remove now-unused CollationOptions import.
- mongo-ops-serializer.ts: biome import-order auto-fix (CollationOptions import reordered).
Net change: lint:casts delta -5 vs merge-base. Zero blindCast<CollationOptions> in op-factory.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Add a `@prisma-next/mongo-value/mongodb-types` entrypoint that re-exports the mongodb option interfaces used across mongo packages (CollationOptions, CreateCollectionOptions, CreateIndexesOptions, IndexSpecification). All mongo packages import from this single entry point rather than directly from 'mongodb'. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…n interfaces; drop options()/DefinedProps/casts Each DDL command node (CreateIndexCommand, CreateCollectionCommand, CollModCommand) and its corresponding wire command now directly implements the mongodb driver option interface (CreateIndexesOptions, CreateCollectionOptions). Fields are truly optional (declared with ?) and assigned only when defined, so JSON.stringify produces flat canonical JSON without any toOptions() conversion step. Deletes: - options() / toOptions() method on command nodes - DefinedProps<> wire command wrapper - definedProps() lowering call in mongo-adapter - blind casts in op-factory-call.ts and contract-to-schema.ts that worked around the former type mismatch - stripCollationFields in canonicalize-introspection (now unnecessary since CollationOptions is typed through the schema IR) Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…Defined cleanups - Extract CONTRACT_CODEC_DESCRIPTOR_MISSING constant; replace inline string literal in control-stack.ts - Delete DefinedProps<T> type and definedProps() function from @prisma-next/utils/defined — both are now unused since command nodes satisfy option interfaces directly - Fix exactOptionalPropertyTypes violations in migration-factories.ts, mongo-ops-serializer.ts, and op-factory-call.ts using ifDefined spreads instead of | undefined object properties - Fix import ordering in several mongo packages (biome organizeImports) Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
c4dcf62 to
9385529
Compare
… shapes; drop deserialization casts Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…shold) Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Merge origin/main tip 90d93bd (PR #816 Mongo migration DDL, PR #817 enum-as-domain-concept native machinery deletion) into tml-2890-uniform-kind-dispatch. Conflicts resolved: - validators.ts: took HEAD's version (main's changes were comment-only tweaks in lines HEAD had already deleted). - postgres-schema.ts: took main's version. HEAD's typeEntityKind referenced PostgresEnumType, which PR #817 deleted; retaining typeEntityKind would reference a non-existent type. - postgres-contract-serializer.ts: took main's version (no typeEntityKind import, plain super(storageTypesHydrators) call matching main). Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…substrate; delete workspace (prisma#867) ## Linked issue Close-out of [Marker/ledger via typed query AST](https://linear.app/prisma-company/project/markerledger-via-typed-query-ast-dc62ab25d151). Phase-2 op porting + the project's deferred ADR migrate into the new project [Typed DDL migration ops — complete the conversion](https://linear.app/prisma-company/project/typed-ddl-migration-ops-complete-the-conversion-9a86e44d4c38) (TML-2919/2920/2921/2922/2923/2925/2927/2866). ## At a glance ``` 137 files changed, 9067 deletions(-) ``` Removes `projects/migrate-marker-ledger-to-typed-query-ast-commands/` after the final retro, and migrates the durable design notes (the seven design principles, the DDL visitor + dispatch model, the table-level constraint shape, the codec-handling split, the planner-lowering mechanism, the Mongo runner-boundary lowering) into the successor project's workspace as draft material for **TML-2923**'s ADR. No source-code changes. External-reference scan was clean before the delete. The design notes land at [`projects/typed-ddl-migration-ops/typed-ddl-design-notes.md`](projects/typed-ddl-migration-ops/typed-ddl-design-notes.md) — the workspace of the successor "Typed DDL migration ops" project, whose `spec.md`/`plan.md` arrive on `main` with PR [prisma#840](prisma#840) (in flight). The notes are voice-rewritten to strip the project-shaping framing (the close-out workflow's Step 4.5 disposition) and banner-marked as draft-for-TML-2923 — its ADR slice absorbs/replaces this file when it lands. ## Decision Project closes; workspace is deleted. The project's DoD is met or explicitly-deferred-with-ticket: 1. All 11 slices merged. 2. Final retro recorded (commit `36279033f` immediately preceding the delete). 3. Long-lived methodology — the seven design principles + the DDL-as-target-contributed-AST model + the table-constraint shape + codec-handling split + planner lowering mechanism — migrated to the successor project's workspace as draft material that TML-2923's ADR absorbs. The canonical ADR ("DDL as a target-contributed query-AST kind + adapter DDL-lowering seam") + Adapters & Targets / Migration System subsystem-doc updates are owned by TML-2923 in the successor project, where the dust from Phase-2's remaining design decisions has to settle first. 4. No external references to the project dir; nothing to re-point or remove. ## Project DoD verification (acceptance criteria in [spec.md](https://github.com/prisma/prisma-next/blob/fbcda64af/projects/migrate-marker-ledger-to-typed-query-ast-commands/spec.md)) | AC | Status | Evidence | |---|---|---| | Team-DoD floor | ✅ met | repo-wide gates green on every merged slice; Linear close-out via this PR; ADR audit covered by AC prisma#9 (deferred) | | SQL query AST represents `CREATE TABLE` + `CREATE SCHEMA` as target-contributed nodes | ✅ met | Slice 1 (TML-2761, foundational) — merged | | All in-scope marker/ledger ops execute via `adapter.lower()` → driver; zero `db.collection()` in `marker-ledger.ts` | ✅ met | Slice 2 (TML-2753 SQL) + Slice 3 (TML-2825 Mongo) — both merged | | Each family's marker CRUD behind one control-adapter SPI; duplicate read paths + `parseContractMarkerRow` + raw-SQL write builders collapsed | ✅ met | TML-2753 outcome (sql-marker-ops-through-adapter) | | `SqlControlAdapter` exposes marker-write methods symmetric with `MongoControlAdapter` | ✅ met | TML-2753 | | Contract-free construction surface per family; no in-scope op hand-builds nodes by object literal or concatenates raw SQL | ✅ met | TML-2761 (SQL DDL surface) + TML-2825 corrective round 2 (Mongo). Phase-2 op-porting tracked by TML-2919/2920/2921/2922 in the successor project. | | Two `as` casts in Mongo `marker-ledger.ts` eliminated; cast ratchet not regressed | ✅ met | TML-2825 | | Invariant-merge converges on accumulate-dedupe across PG + SQLite; test pins for both dialects | ✅ met | TML-2753 | | Migration planner adopts typed AST across all three targets (or residual deferred with tracked follow-ups) | ✅ met | Phase 1 closed: Slice 5 SQLite ([prisma#768](prisma#768) / TML-2859), Slice 7 PG ALTER ([prisma#813](prisma#813)), Slice 6 Mongo ([prisma#816](prisma#816) / TML-2888). Residual op-porting deferred to the successor project. | | ADR "DDL as a target-contributed query-AST kind + adapter DDL-lowering seam" + subsystem-doc updates (Adapters & Targets, Migration System) | 🟡 partially met | Durable design notes migrated to [`projects/typed-ddl-migration-ops/typed-ddl-design-notes.md`](projects/typed-ddl-migration-ops/typed-ddl-design-notes.md) as draft material; canonical ADR + subsystem-doc updates owned by **TML-2923** in the successor project, where the dust from Phase-2's remaining design decisions has to settle first. | ## Slices merged in this project | Slice | Linear | PR | |---|---|---| | `ddl-in-query-ast` (foundational) | TML-2761 | merged | | `sql-marker-ops-through-adapter` | TML-2753 | merged | | `mongo-marker-ledger-through-adapter` | TML-2825 | merged | | `planner-create-table-adopts-ddl-ast` | TML-2754 | [prisma#751](prisma#751) | | `codec-routed-ddl-defaults` | TML-2867 | [prisma#794](prisma#794) | | `sqlite-create-table-adoption` (Phase 1) | TML-2859 | [prisma#768](prisma#768) | | `pg-add-column-pioneer` (Phase 1) | — | [prisma#813](prisma#813) | | `mongo-planner-create-collection-and-index-adoption` (Phase 1) | TML-2888 | [prisma#816](prisma#816) | | `typed-migration-verification-queries` | TML-2889 | [prisma#825](prisma#825) | | `un-namespaced-pg-defaults-to-public` | TML-2916 | [prisma#838](prisma#838) | | `pg-addcolumn-opid-and-codecref-roundtrip` | TML-2918 | [prisma#837](prisma#837) | ## What follows in the successor project [Typed DDL migration ops — complete the conversion](https://linear.app/prisma-company/project/typed-ddl-migration-ops-complete-the-conversion-9a86e44d4c38) owns: - **TML-2919** (in flight as [prisma#840](prisma#840)) — PG: remaining raw-SQL op-builders → typed DDL; delete `buildAddColumnSql`. - **TML-2920** — PG: model `CREATE EXTENSION` as first-class entity kind. - **TML-2921** — SQLite: convert op execute steps to typed DDL. - **TML-2922** — SQLite: `RecreateTable` + AST growth (`CASE WHEN`, row-tuple `IN`). - **TML-2866** — SQLite inline-autoincrement: stop smuggling column options through `DdlColumn.type`. - **TML-2923** — ADR + subsystem docs (the deferred AC prisma#10 from this project). - **TML-2925** — Rewrite `dataTransform` op factory: defer lowering, type the EXISTS wrapper. - **TML-2927** — Introduce `PostgresTableRef` end-to-end (typed table refs). ## Reviewer notes - **Deletion is the only behavioral change** — 56 files removed, 5087 deletions, zero additions outside the final retro. Source code, fixtures, examples, and tests are untouched. - **External-reference scan was empty** before delete (`rg -l "projects/migrate-marker-ledger-to-typed-query-ast-commands/" --glob '!projects/migrate-marker-ledger-to-typed-query-ast-commands/**' --glob '!.git/**'` returned no matches). No links to re-point. - **The two commits are intentionally split** (`docs(marker-ledger): final close-out retro` then `chore: close out … — delete workspace`) so the final retro is preserved as a tracked commit on `main` for archeology if anyone later asks "how did Phase 2 get extracted out cleanly?" - **The migrated doc is *draft material*, not a finished ADR.** The design notes capture the steady-state architecture (the principles, the visitor/dispatch model, the constraint shape, the codec split, the lowering mechanism); they live in the successor project's workspace alongside its `spec.md`/`plan.md`, where TML-2923's ADR slice absorbs/replaces it. Writing the canonical ADR here, before the remaining Phase-2 design decisions (TML-2919/2920/2921/2922) land, would produce a doc that drifts within weeks. - **The doc lands on `main` before the successor project's workspace does** (TML-2919/prisma#840 also creates `projects/typed-ddl-migration-ops/` but is in flight). If this PR merges first, my commit creates the dir; if prisma#840 merges first, my file lands next to its spec/plan. Either order works. ## Testing performed - Worktree gates not re-run for a delete-only PR; the merged slices each shipped with their own gate runs. - `rg` reference scan confirmed pre-delete. ## Skill update n/a — internal project workspace removal. ## Checklist - [x] All commits signed off (DCO). - [x] Scoped to one logical concern (project close-out). - [x] Tests are updated — `n/a` (delete-only, no behavioral change). - [x] PR title in `<TICKET-or-scope>: <sentence-case title>` form. - [x] **Skill update** filled in (`n/a`). --------- Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]> Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Linked issue
Refs TML-2888 — Slice 6 of Marker/ledger via typed query AST. Closes Phase 1 of that project: SQLite (#768) and Postgres ALTER TABLE (#813) landed earlier; this PR is the Mongo pioneer.
At a glance
The migration runner's DDL dispatch — before, a separate executor reached past the adapter to driver helper calls; after, DDL takes the same path the runner's data-transform arm already uses (mongo-runner.ts):
And the planner's op factories stop hand-authoring AST nodes — the contract-free builder constructs them (migration-factories.ts):
The emitted commands and database effects are identical to before — this PR changes how they're constructed and executed, not what they do.
Reviewer notes
projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/mongo-planner-create-collection-and-index-adoption/reviews/code-review.md.CreateCollectionWireCommandet al.), which the driver executes via node-driver helpers — the same idiom the existing DML wire commands use. It does not lower to raw{create: …}server documents; the wire union is ours, the driver owns transport.AsyncIterables via a hand-rolled thunk (lazyDdlIterable) rather thanasync function*— a yield-less generator trips Biome'suseYield, and we don't suppress lints. Two tests pin the laziness contract (no DB action until iterated; iterating twice doesn't re-execute).refactor(codecs): …) is deliberately unrelated to the Mongo work — it's a small cleanup deferred from feat(postgres): adopt typed ALTER TABLE ADD COLUMN (DDL AST pioneer) #813, carried here as its own commit. Reviewable in isolation.validatedCollection()keeps thecreateCollection()/createIndex()factories alive (they now construct via the builder internally).feat(mongo): lower migration DDL through the adapter…): the five lowering arms + wire types + oracle. The option-field mapping there is a verbatim port of the deleted executor's mapping — the oracle and the rewritten behavioral suite pin it field-by-field.Decision
This PR ships four things:
MongoAdapter.lower()accepts migration DDL. The five DDL command kinds (createCollection,createIndex,dropCollection,dropIndex,collMod) lower to typed wire commands, mirroring the SQL family'sLowerer.lower(ast: AnyQueryAst | DdlNode, ctx)— one lowering entry for queries and DDL alike.MongoCommandExecutoris deleted. Every DDL step executes viaadapter.lower → driver.execute, the path marker DML and data-transforms already use.MongoInspectionExecutor(prechecks/postchecks) survives unchanged in its own module.collection(name).createCollection(options)/.createIndex(keys, options)produce the canonical frozen command nodes; theCreateCollection/CreateIndexop factories construct through them, and their check filters through the contract-free field accessor (including a new.and()combinator on filter expressions, added beside the existing.not()).CODEC_DESCRIPTOR_MISSING→ materialize" logic in the framework'sextractCodecLookupand the SQL runtime'screateAstCodecResolvercollapses onto one sharedresolveCodecDescriptorOrThrowhelper.Design rationale is recorded in the project design notes (
projects/migrate-marker-ledger-to-typed-query-ast-commands/design-notes.md, § "Slice 6").How it fits together
AnyMongoWireCommandunion grows five typed DDL members, carrying exactly the option fields the planner sets.structuralLowergains one arm per DDL kind; the option mapping is the retired executor's mapping, moved. DDL lowering is structural — no codec routing.db.createCollection,collection.createIndex, …), lazily on first iteration.runner-depsslot, and its exports are deleted.A deliberate asymmetry with the Postgres adoption (#813): lowering happens execute-time at the runner boundary, not plan-time inside
toOp(lowerer). Postgres serializes the loweredsqlintoops.json; Mongo serializes the typed command node itself, so plan-time lowering would degrade the serialized artifact to opaque wire documents.toOp()stays sync;ops.jsonis byte-identical to before.Behavior changes & evidence
driver.execute()on a DDL wire command is now lazy — no database action until the iterable is consumed, consistent with the DML arms (mongo-driver.ts; evidence: the laziness tests in mongo-driver test).renderTypeScript()output, op ids, andops.jsonserialization are unchanged — the serializer is untouched; existing round-trip and op-factory suites pass unmodified (mongo-ops-serializer.ts)..and(other)beside.not()(filter-expressions.ts; evidence: builder/factory tests exercising the unique-postcheck fold).forCodecRefcases + the existing resolver suite).Summary
The Mongo migration planner's DDL now reaches the database the same way every other operation does — built through the contract-free builder, lowered by the adapter, executed by the driver — completing "the planner adopts the typed AST across all three targets" (Phase 1 of the marker/ledger typed-query-AST project).
Testing performed
pnpm build(66 tasks),pnpm typecheck(138 tasks)pnpm test:packages(815 files / 10k+ tests; one CLI parallel-load flake reproduced and ruled pre-existing — clean on rerun)pnpm test:integration(188 files, 1082 tests)pnpm lint:code,pnpm lint:packages,pnpm lint:deps,pnpm lint:casts(delta 0),pnpm fixtures:checkSkill update
n/a — internal only. No CLI, public API, config, or error-code surface changes; migration authoring (
migration.ts) is untouched.Follow-ups
validatedCollection()onto the builder; thetyped-migration-verification-queriesslice moves prechecks/postchecks offMongoInspectionExecutor.descriptorsByIdvs SQLCodecDescriptorRegistry) remain separate across the plane split — deliberate; recorded in the D3 dispatch artifact.Alternatives considered
adapter.execDdl(node)). Rejected: preserves a second execution mechanism and diverges from the SQL family's one-lowering-entry interface.MongoMigrationLowererwrapper intotoOp(lowerer). Rejected: plumbing without unification — two dispatch paths would survive in the runner.toOp(lowerer)(the literal Postgres mirror). Rejected: Mongo serializes the typed node intoops.json; lowering at plan time would serialize opaque wire documents instead — the wrong artifact.Checklist
git commit -s) per the DCO. The DCO status check will block merge if any commit is missing aSigned-off-by:trailer.TML-NNNN: <sentence-case title>form (Linear ticket prefix + concise title naming the concrete deliverable). See.claude/skills/create-pr/SKILL.mdfor the full convention.Summary by CodeRabbit
New Features
Bug Fixes / Improvements
Tests