Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

TML-2888: Mongo migration DDL lowers through the adapter; executor retired - #816

Merged
wmadden-electric merged 28 commits into
mainfrom
mongo-planner-ddl-adoption
Jun 15, 2026
Merged

wmadden-electric merged 28 commits into
mainfrom
mongo-planner-ddl-adoption

Conversation

@wmadden-electric

@wmadden-electric wmadden-electric commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

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):

// before — step.command.accept(commandExecutor) → db.createCollection(...) / db.collection(...).createIndex(...)
// after  — one path to the wire, same as DML:
for (const step of ddlOp.execute) {
  const wire = await adapter.lower({ command: step.command }, {});
  for await (const _ of driver.execute(wire)) {
    /* consume */
  }
}

And the planner's op factories stop hand-authoring AST nodes — the contract-free builder constructs them (migration-factories.ts):

// before — command: new CreateIndexCommand(collection, keys, { ...options, name }),
//          filter: MongoFieldFilter.eq('key', keysToKeySpec(keys))
const f = createFieldAccessor<IndexInfoDocShape>();
const fullFilter = options?.unique ? filter.and(f.unique.eq(true)) : filter;
execute: [{ command: collection(collectionName).createIndex(keys, { ...options, name }) }],

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

  • An internal review already ran on this branch (architect + principal-engineer pass): verdict SHIP, no blocker/major findings; its two minor findings (oracle exactness, lazy DDL arms) are fixed in the final commit. The artifact is committed at projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/mongo-planner-create-collection-and-index-adoption/reviews/code-review.md.
  • DDL lowers to typed wire-command union members (CreateCollectionWireCommand et 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.
  • The driver's DDL arms are lazily-started AsyncIterables via a hand-rolled thunk (lazyDdlIterable) rather than async function* — a yield-less generator trips Biome's useYield, and we don't suppress lints. Two tests pin the laziness contract (no DB action until iterated; iterating twice doesn't re-execute).
  • The codec-dedup commit (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.
  • Drop/CollMod/DropIndex factories intentionally keep hand-written filters and the old construction style — their construction migration is Phase 2; only their execution unifies in this PR. Likewise validatedCollection() keeps the createCollection()/createIndex() factories alive (they now construct via the builder internally).
  • Largest commit is the first (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:

  1. MongoAdapter.lower() accepts migration DDL. The five DDL command kinds (createCollection, createIndex, dropCollection, dropIndex, collMod) lower to typed wire commands, mirroring the SQL family's Lowerer.lower(ast: AnyQueryAst | DdlNode, ctx) — one lowering entry for queries and DDL alike.
  2. The runner's DDL dispatch unifies and MongoCommandExecutor is deleted. Every DDL step executes via adapter.lower → driver.execute, the path marker DML and data-transforms already use. MongoInspectionExecutor (prechecks/postchecks) survives unchanged in its own module.
  3. The contract-free builder gains DDL terminals. collection(name).createCollection(options) / .createIndex(keys, options) produce the canonical frozen command nodes; the CreateCollection/CreateIndex op 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()).
  4. A codec-resolution dedup deferred from feat(postgres): adopt typed ALTER TABLE ADD COLUMN (DDL AST pioneer) #813: the duplicated "find descriptor → throw CODEC_DESCRIPTOR_MISSING → materialize" logic in the framework's extractCodecLookup and the SQL runtime's createAstCodecResolver collapses onto one shared resolveCodecDescriptorOrThrow helper.

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

  1. Wire types (wire-commands.ts): the AnyMongoWireCommand union grows five typed DDL members, carrying exactly the option fields the planner sets.
  2. Lowering (mongo-adapter.ts): structuralLower gains one arm per DDL kind; the option mapping is the retired executor's mapping, moved. DDL lowering is structural — no codec routing.
  3. Transport (mongo-driver.ts): the driver executes DDL wire commands via the node driver's helpers (db.createCollection, collection.createIndex, …), lazily on first iteration.
  4. Runner (mongo-runner.ts): the DDL loop converges onto lower→execute; the executor, its runner-deps slot, and its exports are deleted.
  5. Construction (collection.ts, migration-factories.ts): the builder terminals return the real frozen nodes (no parallel option shapes, no second AST layer), and the pioneer pair's factories construct through them.

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 lowered sql into ops.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.json is byte-identical to before.

Behavior changes & evidence

  • No user-observable behavior change. Wire-level parity is pinned by an exact-match lowering oracle covering every option field per kind (ddl-lowering-oracle.test.ts), and the behavioral suite re-asserts real database outcomes for all five kinds through the new path against mongodb-memory-server, including server-error fidelity negatives (command-executor.test.ts).
  • 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, and ops.json serialization are unchanged — the serializer is untouched; existing round-trip and op-factory suites pass unmodified (mongo-ops-serializer.ts).
  • Filter expressions gain .and(other) beside .not() (filter-expressions.ts; evidence: builder/factory tests exercising the unique-postcheck fold).
  • Codec descriptor resolution is single-sourced (resolve-codec.ts, call sites control-stack.ts and ast-codec-resolver.ts; evidence: control-stack.test.ts forCodecRef cases + 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:check
  • Targeted: adapter-mongo (317), target-mongo (403), mongo-query-builder (422), framework-components (403), driver-mongo (22)

Skill update

n/a — internal only. No CLI, public API, config, or error-code surface changes; migration authoring (migration.ts) is untouched.

Follow-ups

  • Phase 2 (tracked in the project plan): migrate Drop/CollMod construction + validatedCollection() onto the builder; the typed-migration-verification-queries slice moves prechecks/postchecks off MongoInspectionExecutor.
  • The two codec descriptor indexes (framework descriptorsById vs SQL CodecDescriptorRegistry) remain separate across the plane split — deliberate; recorded in the D3 dispatch artifact.

Alternatives considered

  • Declare Mongo already adopted (its planner already built typed frozen-class nodes dispatched by a visitor). Rejected: typed nodes were never the whole ask — DDL still bypassed the adapter's lowering seam, and the ops were hand-authored rather than builder-constructed.
  • Keep helper-based execution behind an adapter method (adapter.execDdl(node)). Rejected: preserves a second execution mechanism and diverges from the SQL family's one-lowering-entry interface.
  • Thread a thin MongoMigrationLowerer wrapper into toOp(lowerer). Rejected: plumbing without unification — two dispatch paths would survive in the runner.
  • Plan-time lowering inside toOp(lowerer) (the literal Postgres mirror). Rejected: Mongo serializes the typed node into ops.json; lowering at plan time would serialize opaque wire documents instead — the wrong artifact.

Checklist

  • All commits are signed off (git commit -s) per the DCO. The DCO status check will block merge if any commit is missing a Signed-off-by: trailer.
  • I read CONTRIBUTING.md and the change is scoped to one logical concern (plus one explicitly-flagged carried cleanup commit).
  • Tests are updated.
  • The PR title is in TML-NNNN: <sentence-case title> form (Linear ticket prefix + concise title naming the concrete deliverable). See .claude/skills/create-pr/SKILL.md for the full convention.
  • The Skill update section above is filled in.

Summary by CodeRabbit

  • New Features

    • Full Mongo DDL support: create/drop collections & indexes, collMod and schema ops flow adapter→driver; query builder gains collection().createCollection()/createIndex(); control surface exposes executeDdl.
    • Utility: added helper to remove undefined properties from objects.
  • Bug Fixes / Improvements

    • Centralized codec descriptor resolution with consistent error handling.
    • Migration tooling updated to use query-builder APIs; DDL command shapes now surface options under a single options object.
  • Tests

    • Extensive new and updated tests covering DDL lowering, driver execution, adapter/runner and command shapes.

@wmadden-electric
wmadden-electric requested a review from a team as a code owner June 11, 2026 19:47
@coderabbitai

coderabbitai Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This 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.

Changes

MongoDB DDL Infrastructure and Codec Resolution

Layer / File(s) Summary
Codec descriptor resolution helper
packages/1-framework/1-core/framework-components/src/shared/resolve-codec.ts, packages/1-framework/1-core/framework-components/src/exports/codec.ts, packages/1-framework/1-core/framework-components/src/control/control-stack.ts, packages/2-sql/5-runtime/src/codecs/ast-codec-resolver.ts, packages/1-framework/1-core/framework-components/test/control-stack.test.ts
Introduces resolveCodecDescriptorOrThrow, re-exports it, and replaces inline missing-descriptor checks in control-stack and ast-codec-resolver; adds tests for lookup.forCodecRef.
Query builder DDL API
packages/2-mongo-family/4-query/query-ast/src/filter-expressions.ts, packages/2-mongo-family/5-query-builders/query-builder/src/contract-free/collection.ts, packages/2-mongo-family/5-query-builders/query-builder/test/collection-ddl.test.ts
Adds collection().createCollection() and collection().createIndex() APIs and MongoFilterExpression.and() helper; tests verify command shape and option forwarding.
DDL AST shape refactor
packages/2-mongo-family/4-query/query-ast/src/ddl-commands.ts, packages/2-mongo-family/4-query/query-ast/test/ddl-commands.test.ts
Refactors CreateIndex/CreateCollection/CollMod to store configurable settings under a single options field and updates tests/serialization expectations accordingly.
Wire command types and exports
packages/2-mongo-family/6-transport/mongo-wire/src/wire-commands.ts, packages/2-mongo-family/6-transport/mongo-wire/src/exports/index.ts
Adds DDL wire commands (CreateCollectionWireCommand, CreateIndexWireCommand, DropCollectionWireCommand, DropIndexWireCommand, CollModWireCommand), splits DML/DDL unions, adds isDdlWireCommand, and expands exports.
Adapter plan types and public exports
packages/2-mongo-family/6-transport/mongo-lowering/src/adapter-types.ts, packages/2-mongo-family/6-transport/mongo-lowering/src/exports/index.ts
Adds MongoDdlPlan wrapper and updates public exports to include DDL plan typing.
Adapter DDL lowering implementation
packages/3-mongo-target/2-mongo-adapter/src/mongo-adapter.ts
Implements lowerDdlCommand to convert DDL AST commands into wire commands and updates MongoAdapter.lower to dispatch DML vs DDL plans.
Inspection executor extraction
packages/3-mongo-target/2-mongo-adapter/src/core/inspection-executor.ts, packages/3-mongo-target/2-mongo-adapter/src/exports/control.ts, packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
Extracts MongoInspectionExecutor into its own module, updates entrypoint exports, and adjusts runner dependency imports.
Runner deps & execution pipeline
packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts, packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts, packages/3-mongo-target/1-mongo-target/test/mongo-runner.test.ts
Replaces commandExecutor with an executeDdl seam that lowers and dispatches DDL via adapter+driver.run; updates runner and tests to use executeDdl for DDL steps.
Migration factories wiring
packages/3-mongo-target/1-mongo-target/package.json, packages/3-mongo-target/1-mongo-target/src/core/migration-factories.ts
Adds @prisma-next/mongo-query-builder and rewrites migration-factory functions to use collection(name) builder and typed field accessors for existence/index probes and DDL invocation.
Adapter DDL tests and lowering oracle
packages/3-mongo-target/2-mongo-adapter/test/command-executor.test.ts, packages/3-mongo-target/2-mongo-adapter/test/ddl-lowering-oracle.test.ts
Refactors tests to exercise the lower→execute pipeline with extensive DDL option coverage and adds a lowering-oracle that asserts expected wire shapes.
Driver DDL API and handlers
packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts, packages/3-mongo-target/3-mongo-driver/test/mongo-driver.test.ts
Narrows execute to DML, adds run for DDL wire commands, and implements DDL handlers that call the MongoDB driver APIs; tests validate DDL effects and error propagation.
Ops serializer & test updates
packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts, various tests under packages/3-mongo-target/1-mongo-target/test/*
Deserializes DDL commands into typed *Options objects and updates numerous tests to assert option fields under cmd.options.
Utility: definedProps
packages/1-framework/0-foundation/utils/src/defined.ts, packages/1-framework/0-foundation/utils/src/exports/defined.ts, packages/1-framework/0-foundation/utils/test/defined.test.ts
Adds definedProps helper to remove undefined-valued keys when building option objects and re-exports it; adds tests.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • prisma/prisma-next#807: Both PRs update codec descriptor resolution in extractCodecLookup/forCodecRef to route lookup through a shared helper and surface RUNTIME.CODEC_DESCRIPTOR_MISSING for missing ids.

Suggested reviewers

  • wmadden

Poem

🐰 Wire commands hop, DDL takes wing,
Builders hum softly, field accessors sing,
Resolve helper finds the codec true,
Runner and driver dance the new queue,
A rabbit cheers: schema work — through and through!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.74% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main objective: routing Mongo migration DDL through the adapter with executor retirement.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch mongo-planner-ddl-adoption

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented Jun 11, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 152.71 KB (+0.03% 🔺)
postgres / emit 120.95 KB (+0.05% 🔺)
mongo / no-emit 77.81 KB (+1.16% 🔺)
mongo / emit 71.9 KB (+1.26% 🔺)
cf-worker / no-emit 181.12 KB (+0.03% 🔺)
cf-worker / emit 146.13 KB (+0.06% 🔺)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts (1)

35-41: ⚡ Quick win

Replace bare cast in production code.

Line 40 uses undefined as never; use castAs<never>(undefined) to follow repo casting rules.

As per coding guidelines, production TS/JS must not use bare as casts; use blindCast<T, "Reason"> or castAs<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

📥 Commits

Reviewing files that changed from the base of the PR and between b76e5fa and 62bee6c.

⛔ Files ignored due to path filters (8)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/design-notes.md is 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.md is 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.md is 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.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/mongo-planner-create-collection-and-index-adoption/plan.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/mongo-planner-create-collection-and-index-adoption/reviews/code-review.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/mongo-planner-create-collection-and-index-adoption/spec.md is excluded by !projects/**
📒 Files selected for processing (25)
  • packages/1-framework/1-core/framework-components/src/control/control-stack.ts
  • packages/1-framework/1-core/framework-components/src/exports/codec.ts
  • packages/1-framework/1-core/framework-components/src/shared/resolve-codec.ts
  • packages/1-framework/1-core/framework-components/test/control-stack.test.ts
  • packages/2-mongo-family/4-query/query-ast/src/filter-expressions.ts
  • packages/2-mongo-family/5-query-builders/query-builder/src/contract-free/collection.ts
  • 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/2-mongo-family/6-transport/mongo-lowering/src/exports/index.ts
  • packages/2-mongo-family/6-transport/mongo-wire/src/exports/index.ts
  • packages/2-mongo-family/6-transport/mongo-wire/src/wire-commands.ts
  • packages/2-sql/5-runtime/src/codecs/ast-codec-resolver.ts
  • packages/3-mongo-target/1-mongo-target/package.json
  • packages/3-mongo-target/1-mongo-target/src/core/migration-factories.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts
  • packages/3-mongo-target/1-mongo-target/test/mongo-runner.test.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/command-executor.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/inspection-executor.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
  • packages/3-mongo-target/2-mongo-adapter/src/exports/control.ts
  • packages/3-mongo-target/2-mongo-adapter/src/mongo-adapter.ts
  • packages/3-mongo-target/2-mongo-adapter/test/command-executor.test.ts
  • packages/3-mongo-target/2-mongo-adapter/test/ddl-lowering-oracle.test.ts
  • packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts
  • packages/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

@pkg-pr-new

pkg-pr-new Bot commented Jun 11, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

npm i https://pkg.pr.new/@prisma-next/extension-author-tools@816

@prisma-next/mongo-runtime

npm i https://pkg.pr.new/@prisma-next/mongo-runtime@816

@prisma-next/family-mongo

npm i https://pkg.pr.new/@prisma-next/family-mongo@816

@prisma-next/sql-runtime

npm i https://pkg.pr.new/@prisma-next/sql-runtime@816

@prisma-next/family-sql

npm i https://pkg.pr.new/@prisma-next/family-sql@816

@prisma-next/extension-arktype-json

npm i https://pkg.pr.new/@prisma-next/extension-arktype-json@816

@prisma-next/middleware-cache

npm i https://pkg.pr.new/@prisma-next/middleware-cache@816

@prisma-next/mongo

npm i https://pkg.pr.new/@prisma-next/mongo@816

@prisma-next/extension-paradedb

npm i https://pkg.pr.new/@prisma-next/extension-paradedb@816

@prisma-next/extension-pgvector

npm i https://pkg.pr.new/@prisma-next/extension-pgvector@816

@prisma-next/extension-postgis

npm i https://pkg.pr.new/@prisma-next/extension-postgis@816

@prisma-next/postgres

npm i https://pkg.pr.new/@prisma-next/postgres@816

@prisma-next/sql-orm-client

npm i https://pkg.pr.new/@prisma-next/sql-orm-client@816

@prisma-next/sqlite

npm i https://pkg.pr.new/@prisma-next/sqlite@816

@prisma-next/extension-supabase

npm i https://pkg.pr.new/@prisma-next/extension-supabase@816

@prisma-next/target-mongo

npm i https://pkg.pr.new/@prisma-next/target-mongo@816

@prisma-next/adapter-mongo

npm i https://pkg.pr.new/@prisma-next/adapter-mongo@816

@prisma-next/driver-mongo

npm i https://pkg.pr.new/@prisma-next/driver-mongo@816

@prisma-next/contract

npm i https://pkg.pr.new/@prisma-next/contract@816

@prisma-next/utils

npm i https://pkg.pr.new/@prisma-next/utils@816

@prisma-next/config

npm i https://pkg.pr.new/@prisma-next/config@816

@prisma-next/errors

npm i https://pkg.pr.new/@prisma-next/errors@816

@prisma-next/framework-components

npm i https://pkg.pr.new/@prisma-next/framework-components@816

@prisma-next/operations

npm i https://pkg.pr.new/@prisma-next/operations@816

@prisma-next/ts-render

npm i https://pkg.pr.new/@prisma-next/ts-render@816

@prisma-next/contract-authoring

npm i https://pkg.pr.new/@prisma-next/contract-authoring@816

@prisma-next/ids

npm i https://pkg.pr.new/@prisma-next/ids@816

@prisma-next/psl-parser

npm i https://pkg.pr.new/@prisma-next/psl-parser@816

@prisma-next/psl-printer

npm i https://pkg.pr.new/@prisma-next/psl-printer@816

@prisma-next/cli

npm i https://pkg.pr.new/@prisma-next/cli@816

@prisma-next/cli-telemetry

npm i https://pkg.pr.new/@prisma-next/cli-telemetry@816

@prisma-next/emitter

npm i https://pkg.pr.new/@prisma-next/emitter@816

@prisma-next/migration-tools

npm i https://pkg.pr.new/@prisma-next/migration-tools@816

prisma-next

npm i https://pkg.pr.new/prisma-next@816

@prisma-next/vite-plugin-contract-emit

npm i https://pkg.pr.new/@prisma-next/vite-plugin-contract-emit@816

@prisma-next/mongo-codec

npm i https://pkg.pr.new/@prisma-next/mongo-codec@816

@prisma-next/mongo-contract

npm i https://pkg.pr.new/@prisma-next/mongo-contract@816

@prisma-next/mongo-value

npm i https://pkg.pr.new/@prisma-next/mongo-value@816

@prisma-next/mongo-contract-psl

npm i https://pkg.pr.new/@prisma-next/mongo-contract-psl@816

@prisma-next/mongo-contract-ts

npm i https://pkg.pr.new/@prisma-next/mongo-contract-ts@816

@prisma-next/mongo-emitter

npm i https://pkg.pr.new/@prisma-next/mongo-emitter@816

@prisma-next/mongo-schema-ir

npm i https://pkg.pr.new/@prisma-next/mongo-schema-ir@816

@prisma-next/mongo-query-ast

npm i https://pkg.pr.new/@prisma-next/mongo-query-ast@816

@prisma-next/mongo-orm

npm i https://pkg.pr.new/@prisma-next/mongo-orm@816

@prisma-next/mongo-query-builder

npm i https://pkg.pr.new/@prisma-next/mongo-query-builder@816

@prisma-next/mongo-lowering

npm i https://pkg.pr.new/@prisma-next/mongo-lowering@816

@prisma-next/mongo-wire

npm i https://pkg.pr.new/@prisma-next/mongo-wire@816

@prisma-next/sql-contract

npm i https://pkg.pr.new/@prisma-next/sql-contract@816

@prisma-next/sql-errors

npm i https://pkg.pr.new/@prisma-next/sql-errors@816

@prisma-next/sql-operations

npm i https://pkg.pr.new/@prisma-next/sql-operations@816

@prisma-next/sql-schema-ir

npm i https://pkg.pr.new/@prisma-next/sql-schema-ir@816

@prisma-next/sql-contract-psl

npm i https://pkg.pr.new/@prisma-next/sql-contract-psl@816

@prisma-next/sql-contract-ts

npm i https://pkg.pr.new/@prisma-next/sql-contract-ts@816

@prisma-next/sql-contract-emitter

npm i https://pkg.pr.new/@prisma-next/sql-contract-emitter@816

@prisma-next/sql-lane-query-builder

npm i https://pkg.pr.new/@prisma-next/sql-lane-query-builder@816

@prisma-next/sql-relational-core

npm i https://pkg.pr.new/@prisma-next/sql-relational-core@816

@prisma-next/sql-builder

npm i https://pkg.pr.new/@prisma-next/sql-builder@816

@prisma-next/target-postgres

npm i https://pkg.pr.new/@prisma-next/target-postgres@816

@prisma-next/target-sqlite

npm i https://pkg.pr.new/@prisma-next/target-sqlite@816

@prisma-next/adapter-postgres

npm i https://pkg.pr.new/@prisma-next/adapter-postgres@816

@prisma-next/adapter-sqlite

npm i https://pkg.pr.new/@prisma-next/adapter-sqlite@816

@prisma-next/driver-postgres

npm i https://pkg.pr.new/@prisma-next/driver-postgres@816

@prisma-next/driver-sqlite

npm i https://pkg.pr.new/@prisma-next/driver-sqlite@816

commit: f3de4a9

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

The 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 iterable avoids 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

📥 Commits

Reviewing files that changed from the base of the PR and between 62bee6c and d4db0aa.

📒 Files selected for processing (1)
  • packages/3-mongo-target/3-mongo-driver/test/mongo-driver.test.ts

@wmadden wmadden left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good start but there are some areas which need improemvement

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Finish 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, and changeStreamPreAndPostImages). With the new DDL command shape, this test file no longer typechecks. These assertions need to read from cmd.options instead.

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 | 🟠 Major

Tighten the new DDL option narrowing.

CreateIndexJson/CreateCollectionJson/CollModJson define wildcardProjection?, weights?, timeseries?, changeStreamPreAndPostImages?, and clusteredIndex? as Record<string, unknown>, so the only thing making them concrete option types happens via the raw as casts in deserializeDdlCommand (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-numeric weights, invalid wildcardProjection values).

Update the arktype schemas to validate these fields precisely (preferred) or replace the raw as casts with the repo cast helpers (blindCast/castAs from @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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f58da2 and 4b82dfa.

📒 Files selected for processing (21)
  • packages/1-framework/0-foundation/utils/src/defined.ts
  • packages/1-framework/0-foundation/utils/src/exports/defined.ts
  • packages/1-framework/0-foundation/utils/test/defined.test.ts
  • packages/2-mongo-family/4-query/query-ast/src/ddl-commands.ts
  • packages/2-mongo-family/4-query/query-ast/test/ddl-commands.test.ts
  • 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/2-mongo-family/6-transport/mongo-lowering/src/driver-types.ts
  • packages/2-mongo-family/6-transport/mongo-wire/src/exports/index.ts
  • packages/2-mongo-family/6-transport/mongo-wire/src/wire-commands.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts
  • packages/3-mongo-target/1-mongo-target/test/migration-factories.test.ts
  • packages/3-mongo-target/1-mongo-target/test/mongo-ops-serializer.test.ts
  • packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts
  • packages/3-mongo-target/1-mongo-target/test/mongo-runner.test.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/mongo-control-adapter.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
  • packages/3-mongo-target/2-mongo-adapter/src/mongo-adapter.ts
  • packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts
  • packages/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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Finish 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, and changeStreamPreAndPostImages). With the new DDL command shape, this test file no longer typechecks. These assertions need to read from cmd.options instead.

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 | 🟠 Major

Tighten the new DDL option narrowing.

CreateIndexJson/CreateCollectionJson/CollModJson define wildcardProjection?, weights?, timeseries?, changeStreamPreAndPostImages?, and clusteredIndex? as Record<string, unknown>, so the only thing making them concrete option types happens via the raw as casts in deserializeDdlCommand (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-numeric weights, invalid wildcardProjection values).

Update the arktype schemas to validate these fields precisely (preferred) or replace the raw as casts with the repo cast helpers (blindCast/castAs from @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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f58da2 and 4b82dfa.

📒 Files selected for processing (21)
  • packages/1-framework/0-foundation/utils/src/defined.ts
  • packages/1-framework/0-foundation/utils/src/exports/defined.ts
  • packages/1-framework/0-foundation/utils/test/defined.test.ts
  • packages/2-mongo-family/4-query/query-ast/src/ddl-commands.ts
  • packages/2-mongo-family/4-query/query-ast/test/ddl-commands.test.ts
  • 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/2-mongo-family/6-transport/mongo-lowering/src/driver-types.ts
  • packages/2-mongo-family/6-transport/mongo-wire/src/exports/index.ts
  • packages/2-mongo-family/6-transport/mongo-wire/src/wire-commands.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts
  • packages/3-mongo-target/1-mongo-target/test/migration-factories.test.ts
  • packages/3-mongo-target/1-mongo-target/test/mongo-ops-serializer.test.ts
  • packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts
  • packages/3-mongo-target/1-mongo-target/test/mongo-runner.test.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/mongo-control-adapter.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
  • packages/3-mongo-target/2-mongo-adapter/src/mongo-adapter.ts
  • packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts
  • packages/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 win

Avoid bare casts in the exhaustive error paths.

Line 73 and Line 93 introduce bare as casts in production code. This repo’s TypeScript rule requires blindCast<T, "Reason"> or castAs<T> instead, and blindCast is already imported here. Based on learnings, use the repo’s no-bare-casts rule: “No bare as in production code. Use blindCast<T, "Reason"> or castAs<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 win

Assert 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 generic Error. If this test is meant to pin the propagation contract, assert MongoServerError (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.

@wmadden-electric
wmadden-electric force-pushed the mongo-planner-ddl-adoption branch from ebcb9d6 to 86a0724 Compare June 15, 2026 10:58

@wmadden wmadden left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Better but not great

wmadden-electric and others added 19 commits June 15, 2026 15:08
…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]>
…, 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]>
…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]>
…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]>
wmadden-electric and others added 7 commits June 15, 2026 15:08
…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]>
@wmadden-electric
wmadden-electric force-pushed the mongo-planner-ddl-adoption branch from c4dcf62 to 9385529 Compare June 15, 2026 13:16
… 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]>
@wmadden-electric
wmadden-electric added this pull request to the merge queue Jun 15, 2026
Merged via the queue into main with commit 90d93bd Jun 15, 2026
20 checks passed
@wmadden-electric
wmadden-electric deleted the mongo-planner-ddl-adoption branch June 15, 2026 14:48
wmadden-electric added a commit that referenced this pull request Jun 15, 2026
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]>
paulwer pushed a commit to paulwer/prisma-next that referenced this pull request Jul 12, 2026
…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]>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants