Repository navigation
refactor(mongo-migration): move subsystem to target-mongo and add planner dual output - #348
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:
📝 WalkthroughWalkthroughMigration planning moved from the adapter to the target layer; the migration runner was refactored to accept injected dependencies; a visitor-based op-call model and TypeScript rendering were added; adapter exports were narrowed and a runner-deps factory introduced; many tests and README examples updated. Changes
Sequence Diagram(s)sequenceDiagram
participant Dev as Developer
participant Driver as ControlDriver
participant Adapter as Adapter (createMongoRunnerDeps)
participant Runner as MongoMigrationRunner
participant Planner as MongoMigrationPlanner
participant DB as MongoDB
Dev->>Driver: create control driver
Dev->>Adapter: createMongoRunnerDeps(driver)
Adapter->>Driver: extract Db (throws if missing)
Adapter->>Runner: return MongoRunnerDependencies
Dev->>Runner: new MongoMigrationRunner(deps)
Dev->>Planner: request plan(contract, schema)
Planner->>Planner: diff -> OpFactoryCall[]
Dev->>Runner: runner.execute(plan)
Runner->>Runner: use deps.commandExecutor / deps.inspectionExecutor / deps.markerOps
Runner->>DB: execute DDL & inspection via executors
Runner->>DB: read/update marker via markerOps
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
…o to target-mongo Move planner, runner, serializer, and helper modules (contract-to-schema, ddl-formatter, filter-evaluator) from adapter-mongo to target-mongo to correct package layering. These modules operate on AST/IR and have no runtime dependency on the mongodb driver. Refactor MongoMigrationRunner to accept an executor factory via constructor injection, removing its direct dependency on MongoCommandExecutor and MongoInspectionExecutor. The runner file no longer imports from mongodb. Adapter-mongo retains backward-compatible re-exports from target-mongo and keeps the concrete executor implementations (command-executor, introspect-schema, mongo-control-driver).
… adapter re-exports Decouple MongoMigrationRunner from the mongodb driver by replacing direct marker-ledger function calls with a MarkerOperations interface injected via a RunnerDependenciesFactory. The runner no longer imports Db or any mongodb types. Remove all 12 backward-compat re-exports from adapter-mongo control.ts. Update 8 consumer files (integration tests, example tests) to import moved symbols from @prisma-next/target-mongo/control directly. Add createMongoRunnerDeps in adapter-mongo as the concrete factory that constructs executors and marker ops from a control driver instance.
…dual renderers Refactor MongoMigrationPlanner to produce OpFactoryCall[] via planCalls(), then delegate plan() to planCalls() + renderOps(). This separates the schema-diff logic from operation materialization, enabling both runtime execution (renderOps) and code generation (renderTypeScript). Add collMod factory function with meta overrides for id/label/operationClass. Add schemaIndexToCreateIndexOptions and schemaCollectionToCreateCollectionOptions helpers that extract creation options from schema IR types. renderTypeScript generates complete runnable Migration files that import from @prisma-next/family-mongo/migration and @prisma-next/target-mongo/migration. 260 tests pass including round-trip equivalence tests that verify renderOps(planCalls()) produces identical JSON to the original plan().
…oryCall Replace the plain discriminated-union OpFactoryCall type with frozen subclasses (CreateIndexCall, DropIndexCall, CreateCollectionCall, DropCollectionCall, CollModCall) extending an abstract base class, plus an OpFactoryCallVisitor<R> interface. This matches the established MongoAstNode/MongoDdlCommandVisitor pattern from mongo-query-ast. Convert all switch-on-factory sites (renderOps, renderTypeScript, operationClassForFactory, labelForCall) to visitor implementations. Adding a new variant now forces all visitors to handle it at compile time.
Codifies when and how to use the frozen-class/visitor pattern for discriminated unions with multiple dispatch sites. Points to MongoAstNode and OpFactoryCall as codebase examples.
There was a problem hiding this comment.
Actionable comments posted: 11
🧹 Nitpick comments (7)
packages/1-framework/3-tooling/migration/test/migration-base.test.ts (2)
56-56: Use timeout helper instead of hardcoded value.Per repo guidelines, prefer
@prisma-next/test-utilstimeout helpers over hardcoded numbers.♻️ Suggested fix
+import { timeouts } from '@prisma-next/test-utils'; + -describe('Migration.run() subprocess', { timeout: 15_000 }, () => { +describe('Migration.run() subprocess', { timeout: timeouts.subprocess }, () => {Note: Verify the appropriate timeout constant name in
@prisma-next/test-utils/timeouts.ts(e.g.,subprocess,typeScriptCompilation, or similar).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/migration/test/migration-base.test.ts` at line 56, Replace the hardcoded timeout 15_000 in the describe block for "Migration.run() subprocess" with the shared timeout constant from `@prisma-next/test-utils`: import the appropriate constant (e.g., subprocess or typeScriptCompilation) from '@prisma-next/test-utils/timeouts' and use that constant in the describe call (the describe('Migration.run() subprocess', { timeout: ... }) invocation); ensure you add the import at the top of the file and use the correctly named exported symbol so the test follows the repo timeout helper convention.
196-202: Consider usingtoMatchObjectfor related assertions.Per coding guidelines, prefer object matchers over multiple individual
expect().toBe()calls when checking 2+ related values.♻️ Suggested refactor
- expect(manifest.from).toBe('abc123'); - expect(manifest.to).toBe('def456'); - expect(manifest.labels).toEqual(['add-users']); - expect(manifest.migrationId).toBeNull(); - expect(manifest.kind).toBe('regular'); - expect(manifest.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/); + expect(manifest).toMatchObject({ + from: 'abc123', + to: 'def456', + labels: ['add-users'], + migrationId: null, + kind: 'regular', + }); + expect(manifest.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/migration/test/migration-base.test.ts` around lines 196 - 202, Replace the multiple individual assertions on the parsed manifest with a single object matcher: instead of separate expect(manifest.from).toBe(...), expect(manifest.to).toBe(...), expect(manifest.labels)... and expect(manifest.migrationId)..., use expect(manifest).toMatchObject({ from: 'abc123', to: 'def456', labels: ['add-users'], migrationId: null, kind: 'regular' }) and keep the createdAt assertion as-is (e.g., expect(manifest.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/)); update the test that parses migration.json (variable manifest in migration-base.test.ts) to use toMatchObject for the related fields.packages/3-mongo-target/1-mongo-target/src/exports/control.ts (1)
18-27: Avoid exposing the concrete AST classes on the public control surface.Re-exporting
CollModCall/CreateIndexCall/etc. bakes the current class-based representation into the API and makes the plain-data-vs-AST decision much harder to change later. Prefer exported interfaces/factories here and keep the classes internal. As per coding guidelines, “Export interfaces and factory functions for public APIs; keep concrete classes as private implementation details”.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-mongo-target/1-mongo-target/src/exports/control.ts` around lines 18 - 27, The current file re-exports concrete AST classes (CollModCall, CreateCollectionCall, CreateIndexCall, DropCollectionCall, DropIndexCall) which leaks implementation details; change this export surface to expose only plain-data interfaces and/or factory functions (e.g., Export an ICollModCall, ICreateCollectionCall, ICreateIndexCall, IDropCollectionCall, IDropIndexCall or factory creators) while removing direct re-exports of the class symbols (CollModCall, CreateCollectionCall, CreateIndexCall, DropCollectionCall, DropIndexCall) so the class implementations remain internal to ../core/op-factory-call; keep existing exported types like CollModMeta, OpFactoryCall, OpFactoryCallVisitor but add or re-export interface types and factory functions instead of the classes.packages/2-mongo-family/9-family/README.md (1)
105-119: Consider using a named class in the example.The anonymous class pattern (
export default class extends Migration) combined withMigration.run(import.meta.url)doesn't demonstrate the actual API correctly. The other example migrations in this PR (e.g.,examples/mongo-demo/migrations/.../migration.ts) use named classes.📝 Suggested improvement
-export default class extends Migration { +class AddUsersCollection extends Migration { describe() { return { from: "abc123", to: "def456", labels: ["add-users"] } } plan() { return [ createCollection("users", { validator: { $jsonSchema: { required: ["email"] } }, validationLevel: "strict", }), createIndex("users", [{ field: "email", direction: 1 }], { unique: true }), ] } } -Migration.run(import.meta.url) +export default AddUsersCollection; +Migration.run(import.meta.url, AddUsersCollection)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-mongo-family/9-family/README.md` around lines 105 - 119, Replace the anonymous "export default class extends Migration" with a named class (e.g., "class AddUsersMigration extends Migration") and export that name (or export default the named class) so examples using Migration.run(import.meta.url) map to a concrete class name; update the describe() and plan() methods remain unchanged and keep references to createCollection and createIndex inside the named class.packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts (1)
1-1208: Consider splitting this test file in a follow-up.This file is 1208 lines, significantly exceeding the 500-line guideline. Consider splitting by functionality in a follow-up PR:
mongo-planner.index-diffing.test.tsmongo-planner.validator-diffing.test.tsmongo-planner.collection-lifecycle.test.tsmongo-planner.plan-calls.test.tsAs per coding guidelines: "Keep test files under 500 lines to maintain readability and navigability."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts` around lines 1 - 1208, The test file exceeds the 500-line guideline; split the large mongo-planner test into smaller, focused files by moving the relevant describe blocks into separate test files (e.g., create mongo-planner.index-diffing.test.ts containing the "index diffing" describe, mongo-planner.validator-diffing.test.ts for "validator diffing", mongo-planner.collection-lifecycle.test.ts for "collection lifecycle" and ordering/plan metadata as appropriate, and mongo-planner.plan-calls.test.ts for the "planCalls" describe). Ensure each new file imports the same utilities and types used here (MongoMigrationPlanner, planSuccess/planCallsSuccess helpers, CollModCall/CreateIndexCall, MongoSchemaIR/Collection/Index/Validator, and the makeContract/ascIndex helpers or move those helpers into a shared test-utils file) so tests compile and preserve the existing describe/it blocks and assertions unchanged.examples/retail-store/test/manual-migration.test.ts (1)
60-69: Consider using object matcher for manifest assertions.Multiple individual assertions on the same object can be consolidated for better readability and more actionable failure messages.
♻️ Suggested refactor
it('migration.json has expected structure', () => { const manifest = JSON.parse(readFileSync(resolve(migrationDir, 'migration.json'), 'utf-8')); - expect(manifest.migrationId).toBeNull(); - expect(manifest.kind).toBe('regular'); - expect(manifest.labels).toEqual(['add-product-validation']); - expect(manifest.from).toMatch(/^sha256:/); - expect(manifest.to).toMatch(/^sha256:/); - expect(manifest.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/); + expect(manifest).toMatchObject({ + migrationId: null, + kind: 'regular', + labels: ['add-product-validation'], + }); + expect(manifest.from).toMatch(/^sha256:/); + expect(manifest.to).toMatch(/^sha256:/); + expect(manifest.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/); });As per coding guidelines: "Prefer object matchers (toMatchObject) over multiple individual expect().toBe() calls when checking 2 or more related values in tests"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/retail-store/test/manual-migration.test.ts` around lines 60 - 69, Consolidate the multiple expects in the "migration.json has expected structure" test by asserting the parsed manifest object with a single object matcher: replace the individual expect(manifest.*) calls with one assertion using expect(manifest).toEqual or expect(manifest).toMatchObject/expect.objectContaining that verifies migrationId: null, kind: 'regular', labels: ['add-product-validation'] and uses expect.stringMatching(/ˆsha256:/) (or expect.stringMatching) for from and to and expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/) for createdAt; update the test block that defines manifest accordingly to improve readability and failure messages.packages/3-mongo-target/1-mongo-target/test/migration-factories.test.ts (1)
1-556: Consider splitting this test file in a follow-up.This file is 556 lines, slightly over the 500-line guideline. Consider splitting by factory type in a follow-up:
migration-factories.index.test.ts(createIndex, dropIndex)migration-factories.collection.test.ts(createCollection, dropCollection)migration-factories.validation.test.ts(setValidation, collMod, validatedCollection)migration-factories.serialization.test.ts(round-trip tests)As per coding guidelines: "Keep test files under 500 lines to maintain readability and navigability."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-mongo-target/1-mongo-target/test/migration-factories.test.ts` around lines 1 - 556, The test file exceeds the 500-line guideline; split tests by factory into separate files to improve readability: move createIndex and dropIndex describe blocks into migration-factories.index.test.ts, move createCollection and dropCollection describe blocks into migration-factories.collection.test.ts, move setValidation, collMod, and validatedCollection describe blocks into migration-factories.validation.test.ts, and move the serialization round-trip describe block into migration-factories.serialization.test.ts; ensure each new file imports the same symbols used in its tests (e.g., createIndex, dropIndex, createCollection, dropCollection, setValidation, collMod, validatedCollection, plus ListIndexesCommand, CreateIndexCommand, CreateCollectionCommand, DropCollectionCommand, CollModCommand, MongoFieldFilter, MongoAndExpr, keysToKeySpec, defaultMongoIndexName, buildIndexOpId) and preserve all assertions and test names exactly so behavior and JSON round-trip comparisons remain unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In @.agents/skills/ast-visitor-pattern/SKILL.md:
- Around line 19-47: Add a minimal BazNode class to the example so BazNode is
declared and the union Foo and visitor FooVisitor type-check; implement BazNode
as a subclass of FooNode with readonly kind = 'baz', a readonly field (e.g.,
count: number), a constructor that sets the field and calls this.freeze(), and
an accept<R>(visitor: FooVisitor<R>): R method that calls visitor.baz(this);
ensure the new class name BazNode matches all existing references
(FooVisitor.baz, Foo union) so the snippet is copy/paste friendly.
In `@packages/2-mongo-family/9-family/README.md`:
- Line 121: Update the README example to call Migration.run with the required
second argument: pass the migration class (e.g., AddUsersCollection) as the
second parameter to Migration.run(import.meta.url, AddUsersCollection); ensure
the migration shown above follows the named class pattern (export default class
AddUsersCollection extends Migration) so the identifier matches the call.
In `@packages/3-mongo-target/1-mongo-target/README.md`:
- Around line 39-52: The README example defines an anonymous default class that
implements plan() but then calls Migration.run(import.meta.url) with only one
argument; update the example to export a named migration class (e.g.,
UsersMigration extends Migration) that contains the plan() method and invoke
Migration.run(import.meta.url, UsersMigration) so the required second parameter
(the MigrationClass) is passed; keep the existing plan implementation
(createCollection/createIndex) and the Migration.run call updated to reference
the named class.
In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts`:
- Around line 31-46: buildIndexLookupKey() currently omits the index name so
renames go undetected; update the function (buildIndexLookupKey) to include the
index's explicit name in the constructed lookup key (e.g., add a
"name:<index.name>" token into the opts array when index.name exists, taking
care to use a stable representation for empty/undefined names) so that indexes
with identical keys/options but different names are treated as different entries
by the planner.
- Around line 171-175: The code currently only emits a CreateCollectionCall when
collectionHasOptions(destColl) is true, so plain new collections with no options
get no create op; update the block in the !originColl && destColl branch to
always push a CreateCollectionCall for collName and pass options only when
present (e.g., compute opts = collectionHasOptions(destColl) ?
schemaCollectionToCreateCollectionOptions(destColl) : undefined; then
collCreates.push(new CreateCollectionCall(collName, opts))); keep using the
existing helpers (collectionHasOptions,
schemaCollectionToCreateCollectionOptions) and the CreateCollectionCall and
collName identifiers.
In `@packages/3-mongo-target/1-mongo-target/src/core/op-factory-call.ts`:
- Around line 33-35: The freeze() method on OpFactoryCall (in
op-factory-call.ts) only freezes the outer object, leaving nested payload
properties (keys, options, meta) mutable; update freeze() to perform a deep
freeze (or clone-then-freeze) of those nested objects so the AST node becomes
fully immutable—use a well-established utility (e.g., lodash's cloneDeep +
freeze, or Object.freeze combined with a robust deep-freeze helper) or a modern
native pattern to recursively freeze keys, options, and meta before calling
Object.freeze(this), ensuring functions/methods that construct planned calls
(e.g., the OpFactoryCall constructor) pass through this new deep-freeze step.
- Around line 136-147: The mapper schemaIndexToCreateIndexOptions currently
omits explicit index names from the returned CreateIndexOptions; update
schemaIndexToCreateIndexOptions (and use the MongoSchemaIndex.name field) to
include the index name (e.g., set name: index.name || undefined) so that
CreateIndexOptions preserves contract-defined index names instead of letting
Mongo generate one.
In `@packages/3-mongo-target/1-mongo-target/src/core/render-typescript.ts`:
- Around line 1-15: The renderer renderTypeScript currently imports
MigrationMeta from `@prisma-next/migration-tools`, violating the core plane
boundary; fix by either (A) moving the renderTypeScript implementation out of
the shared core into the migration-plane module so it may keep using the
MigrationMeta type, or (B) remove the external MigrationMeta import and define a
local metadata shape (e.g., a MigrationMetaLocal interface or use a
generic/unknown meta param) in the same module and update
renderTypeScript(calls, meta?) signature and all callers to use that local
shape; ensure no direct import of MigrationMeta remains in this file.
- Around line 120-121: renderKey currently emits keys matching the identifier
regex unquoted, which leaves "__proto__" unquoted and thus sets an object's
prototype; modify renderKey to explicitly treat "__proto__" as a quoted key
(i.e., return JSON.stringify(key) for key === "__proto__") even if it matches
/^[a-zA-Z_$][a-zA-Z0-9_$]*$/, so that emitting object literals uses a normal own
property for "__proto__" instead of altering the prototype.
In `@packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts`:
- Around line 12-20: The function extractDb uses a blind cast to assume driver
has a db property; replace that with a proper type guard: add a predicate (e.g.,
isMongoDriverWithDb(driver): driver is ControlDriverInstance<'mongo','mongo'> &
{ db: Db }) that checks Object.hasOwn(driver, 'db') and that driver.db is
truthy, then use that predicate in extractDb to narrow the type and safely
return mongoDriver.db or throw the same Error; update references to
ControlDriverInstance and mongoDriver.db accordingly.
In `@packages/3-mongo-target/2-mongo-adapter/src/exports/control.ts`:
- Line 9: The test import is pulling initMarker from the wrong package; update
the import in db-verify-sign.test.ts so it imports initMarker from
`@prisma-next/target-mongo/control` (where initMarker is actually exported)
instead of `@prisma-next/adapter-mongo/control`; locate the import line for
initMarker in db-verify-sign.test.ts and change the module path to
`@prisma-next/target-mongo/control` so the test imports the correct symbol.
---
Nitpick comments:
In `@examples/retail-store/test/manual-migration.test.ts`:
- Around line 60-69: Consolidate the multiple expects in the "migration.json has
expected structure" test by asserting the parsed manifest object with a single
object matcher: replace the individual expect(manifest.*) calls with one
assertion using expect(manifest).toEqual or
expect(manifest).toMatchObject/expect.objectContaining that verifies
migrationId: null, kind: 'regular', labels: ['add-product-validation'] and uses
expect.stringMatching(/ˆsha256:/) (or expect.stringMatching) for from and to and
expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/) for createdAt; update the test
block that defines manifest accordingly to improve readability and failure
messages.
In `@packages/1-framework/3-tooling/migration/test/migration-base.test.ts`:
- Line 56: Replace the hardcoded timeout 15_000 in the describe block for
"Migration.run() subprocess" with the shared timeout constant from
`@prisma-next/test-utils`: import the appropriate constant (e.g., subprocess or
typeScriptCompilation) from '@prisma-next/test-utils/timeouts' and use that
constant in the describe call (the describe('Migration.run() subprocess', {
timeout: ... }) invocation); ensure you add the import at the top of the file
and use the correctly named exported symbol so the test follows the repo timeout
helper convention.
- Around line 196-202: Replace the multiple individual assertions on the parsed
manifest with a single object matcher: instead of separate
expect(manifest.from).toBe(...), expect(manifest.to).toBe(...),
expect(manifest.labels)... and expect(manifest.migrationId)..., use
expect(manifest).toMatchObject({ from: 'abc123', to: 'def456', labels:
['add-users'], migrationId: null, kind: 'regular' }) and keep the createdAt
assertion as-is (e.g.,
expect(manifest.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/)); update the test that
parses migration.json (variable manifest in migration-base.test.ts) to use
toMatchObject for the related fields.
In `@packages/2-mongo-family/9-family/README.md`:
- Around line 105-119: Replace the anonymous "export default class extends
Migration" with a named class (e.g., "class AddUsersMigration extends
Migration") and export that name (or export default the named class) so examples
using Migration.run(import.meta.url) map to a concrete class name; update the
describe() and plan() methods remain unchanged and keep references to
createCollection and createIndex inside the named class.
In `@packages/3-mongo-target/1-mongo-target/src/exports/control.ts`:
- Around line 18-27: The current file re-exports concrete AST classes
(CollModCall, CreateCollectionCall, CreateIndexCall, DropCollectionCall,
DropIndexCall) which leaks implementation details; change this export surface to
expose only plain-data interfaces and/or factory functions (e.g., Export an
ICollModCall, ICreateCollectionCall, ICreateIndexCall, IDropCollectionCall,
IDropIndexCall or factory creators) while removing direct re-exports of the
class symbols (CollModCall, CreateCollectionCall, CreateIndexCall,
DropCollectionCall, DropIndexCall) so the class implementations remain internal
to ../core/op-factory-call; keep existing exported types like CollModMeta,
OpFactoryCall, OpFactoryCallVisitor but add or re-export interface types and
factory functions instead of the classes.
In `@packages/3-mongo-target/1-mongo-target/test/migration-factories.test.ts`:
- Around line 1-556: The test file exceeds the 500-line guideline; split tests
by factory into separate files to improve readability: move createIndex and
dropIndex describe blocks into migration-factories.index.test.ts, move
createCollection and dropCollection describe blocks into
migration-factories.collection.test.ts, move setValidation, collMod, and
validatedCollection describe blocks into migration-factories.validation.test.ts,
and move the serialization round-trip describe block into
migration-factories.serialization.test.ts; ensure each new file imports the same
symbols used in its tests (e.g., createIndex, dropIndex, createCollection,
dropCollection, setValidation, collMod, validatedCollection, plus
ListIndexesCommand, CreateIndexCommand, CreateCollectionCommand,
DropCollectionCommand, CollModCommand, MongoFieldFilter, MongoAndExpr,
keysToKeySpec, defaultMongoIndexName, buildIndexOpId) and preserve all
assertions and test names exactly so behavior and JSON round-trip comparisons
remain unchanged.
In `@packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts`:
- Around line 1-1208: The test file exceeds the 500-line guideline; split the
large mongo-planner test into smaller, focused files by moving the relevant
describe blocks into separate test files (e.g., create
mongo-planner.index-diffing.test.ts containing the "index diffing" describe,
mongo-planner.validator-diffing.test.ts for "validator diffing",
mongo-planner.collection-lifecycle.test.ts for "collection lifecycle" and
ordering/plan metadata as appropriate, and mongo-planner.plan-calls.test.ts for
the "planCalls" describe). Ensure each new file imports the same utilities and
types used here (MongoMigrationPlanner, planSuccess/planCallsSuccess helpers,
CollModCall/CreateIndexCall, MongoSchemaIR/Collection/Index/Validator, and the
makeContract/ascIndex helpers or move those helpers into a shared test-utils
file) so tests compile and preserve the existing describe/it blocks and
assertions unchanged.
🪄 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: 219688f4-a5f7-458e-b745-839d7c4bc9e6
⛔ Files ignored due to path filters (8)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/mongo-migration-authoring/assets/migration-authoring-design.mdis excluded by!projects/**projects/mongo-migration-authoring/plan.mdis excluded by!projects/**projects/mongo-migration-authoring/plans/data-migrations-plan.mdis excluded by!projects/**projects/mongo-migration-authoring/spec.mdis excluded by!projects/**projects/mongo-migration-authoring/specs/data-migrations.spec.mdis excluded by!projects/**projects/mongo-migration-authoring/specs/migration-subsystem-refactor.spec.mdis excluded by!projects/**projects/mongo-migration-authoring/specs/planner-dual-output.spec.mdis excluded by!projects/**
📒 Files selected for processing (57)
.agents/skills/ast-visitor-pattern/SKILL.mdexamples/mongo-demo/migrations/20260415_add-posts-author-index/migration.jsonexamples/mongo-demo/migrations/20260415_add-posts-author-index/migration.tsexamples/mongo-demo/migrations/20260415_add-posts-author-index/ops.jsonexamples/mongo-demo/package.jsonexamples/mongo-demo/test/manual-migration.test.tsexamples/retail-store/migrations/20260415_add-product-validation/migration.jsonexamples/retail-store/migrations/20260415_add-product-validation/migration.tsexamples/retail-store/migrations/20260415_add-product-validation/ops.jsonexamples/retail-store/package.jsonexamples/retail-store/test/manual-migration.test.tspackages/1-framework/3-tooling/migration/package.jsonpackages/1-framework/3-tooling/migration/src/exports/migration.tspackages/1-framework/3-tooling/migration/src/migration-base.tspackages/1-framework/3-tooling/migration/test/migration-base.test.tspackages/1-framework/3-tooling/migration/tsdown.config.tspackages/2-mongo-family/9-family/README.mdpackages/2-mongo-family/9-family/package.jsonpackages/2-mongo-family/9-family/src/core/control-instance.tspackages/2-mongo-family/9-family/src/core/mongo-migration.tspackages/2-mongo-family/9-family/src/core/mongo-target-descriptor.tspackages/2-mongo-family/9-family/src/exports/migration.tspackages/2-mongo-family/9-family/tsdown.config.tspackages/3-mongo-target/1-mongo-target/README.mdpackages/3-mongo-target/1-mongo-target/package.jsonpackages/3-mongo-target/1-mongo-target/src/core/contract-to-schema.tspackages/3-mongo-target/1-mongo-target/src/core/ddl-formatter.tspackages/3-mongo-target/1-mongo-target/src/core/filter-evaluator.tspackages/3-mongo-target/1-mongo-target/src/core/migration-factories.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-planner.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-runner.tspackages/3-mongo-target/1-mongo-target/src/core/op-factory-call.tspackages/3-mongo-target/1-mongo-target/src/core/render-ops.tspackages/3-mongo-target/1-mongo-target/src/core/render-typescript.tspackages/3-mongo-target/1-mongo-target/src/exports/control.tspackages/3-mongo-target/1-mongo-target/src/exports/migration.tspackages/3-mongo-target/1-mongo-target/test/contract-to-schema.test.tspackages/3-mongo-target/1-mongo-target/test/ddl-formatter.test.tspackages/3-mongo-target/1-mongo-target/test/filter-evaluator.test.tspackages/3-mongo-target/1-mongo-target/test/migration-e2e.test.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/render-ops.test.tspackages/3-mongo-target/1-mongo-target/test/render-typescript.test.tspackages/3-mongo-target/1-mongo-target/tsdown.config.tspackages/3-mongo-target/2-mongo-adapter/src/core/mongo-planner.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/test/mongo-runner.test.tstest/integration/test/cli.mongo-db-sign.e2e.test.tstest/integration/test/cli.mongo-db-verify.e2e.test.tstest/integration/test/mongo/migration-authoring-e2e.test.tstest/integration/test/mongo/migration-e2e.test.tstest/integration/test/mongo/migration-m2-vocabulary.test.tstest/integration/test/mongo/migration-psl-authoring.test.ts
💤 Files with no reviewable changes (1)
- packages/3-mongo-target/2-mongo-adapter/src/core/mongo-planner.ts
918f7f2 to
55ba9f4
Compare
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/middleware-telemetry
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@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/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/emitter
@prisma-next/migration-tools
@prisma-next/vite-plugin-contract-emit
@prisma-next/runtime-executor
@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-pipeline-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: 4
♻️ Duplicate comments (2)
packages/3-mongo-target/1-mongo-target/src/core/render-typescript.ts (2)
120-121:⚠️ Potential issue | 🔴 CriticalQuote
__proto__keys when emitting object literals.Line 121 can emit
__proto__unquoted, which changes object prototype semantics instead of emitting a normal own property in generated migration code.Suggested fix
function renderKey(key: string): string { + if (key === '__proto__') return JSON.stringify(key); return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : JSON.stringify(key); }#!/bin/bash node <<'EOF' const a = ({ __proto__: { polluted: true }, x: 1 }); const b = ({ "__proto__": { polluted: true }, x: 1 }); console.log('a own __proto__:', Object.hasOwn(a, '__proto__')); // false console.log('b own __proto__:', Object.hasOwn(b, '__proto__')); // true EOF🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-mongo-target/1-mongo-target/src/core/render-typescript.ts` around lines 120 - 121, The renderKey function currently returns an unquoted identifier for keys matching /^[a-zA-Z_$][a-zA-Z0-9_$]*$/, which will emit __proto__ unquoted and change prototype semantics; update renderKey to treat "__proto__" as a non-identifier and return JSON.stringify(key) for that specific string (i.e., in function renderKey(key: string) add a guard like if (key === "__proto__") return JSON.stringify(key) before the regex test, or modify the condition to require key !== "__proto__" so __proto__ is always quoted).
1-15:⚠️ Potential issue | 🟠 Major
src/coreimports migration-plane type directly (layer boundary break).This file imports
MigrationMetafrom@prisma-next/migration-tools/migration, which introduces a plane-crossing dependency in shared core.As per coding guidelines,
packages/**/src/core/**: “Keepsrc/core/**free of migration/runtime imports; depend only on shared-plane packages.”🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-mongo-target/1-mongo-target/src/core/render-typescript.ts` around lines 1 - 15, The file imports MigrationMeta from `@prisma-next/migration-tools/migration` which breaks the core/shared-plane boundary; replace that direct migration-plane import by depending only on a shared-plane type (or by declaring a local minimal MigrationMeta interface) and update the renderTypeScript signature to use the shared/local type instead of MigrationMeta; specifically change the import of MigrationMeta and any type annotations in the renderTypeScript(calls: ReadonlyArray<OpFactoryCall>, meta?: MigrationMeta) declaration to reference the new shared-local type so src/core stays free of migration/runtime imports.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/3-mongo-target/1-mongo-target/src/core/migration-factories.ts`:
- Around line 210-223: The postcheck currently only adds filters for collection
name and optional validationLevel/validationAction, so when options.validator is
present but those two are omitted the check only verifies collection existence;
update the postcheck building in migration-factories.ts (the block that
constructs the ListCollectionsCommand filter used when hasValidator is true) to
also include a MongoFieldFilter for the validator when options.validator is
provided (e.g. add MongoFieldFilter.eq('options.validator', options.validator)
or an appropriate deep-equality check) alongside the existing
MongoFieldFilter.eq('name', collection) so the "validator applied" check
actually verifies the validator contents.
In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts`:
- Around line 13-18: The imports for MongoDdlCommandVisitor and
MongoInspectionCommandVisitor in mongo-runner.ts are coming from the
migration/control plane; move those types to a shared-plane export and update
the import to avoid a plane-crossing dependency: add or use an existing
shared-plane module that re-exports MongoDdlCommandVisitor and
MongoInspectionCommandVisitor (e.g., from a shared types package), change the
imports in the file to import these two symbols from that shared-plane module
instead of '@prisma-next/mongo-query-ast/control', and keep other
control-plane-only symbols (MongoMigrationCheck, MongoMigrationPlanOperation)
untouched so src/core remains free of migration/runtime imports.
- Around line 58-60: The MongoMigrationRunner is incorrectly bound to the
constructor-injected driver (deps) so execute() ignores the runtime
options.driver; update the class so execute() uses the driver passed in options
(options.driver) rather than always using constructor deps, or fall back to deps
only if options.driver is absent; inspect and change the MongoMigrationRunner
constructor/fields and the execute(...) implementation to reference the runtime
driver symbol (options.driver) and remove any hard-coded use of deps.driver so a
single runner can run against multiple drivers.
---
Duplicate comments:
In `@packages/3-mongo-target/1-mongo-target/src/core/render-typescript.ts`:
- Around line 120-121: The renderKey function currently returns an unquoted
identifier for keys matching /^[a-zA-Z_$][a-zA-Z0-9_$]*$/, which will emit
__proto__ unquoted and change prototype semantics; update renderKey to treat
"__proto__" as a non-identifier and return JSON.stringify(key) for that specific
string (i.e., in function renderKey(key: string) add a guard like if (key ===
"__proto__") return JSON.stringify(key) before the regex test, or modify the
condition to require key !== "__proto__" so __proto__ is always quoted).
- Around line 1-15: The file imports MigrationMeta from
`@prisma-next/migration-tools/migration` which breaks the core/shared-plane
boundary; replace that direct migration-plane import by depending only on a
shared-plane type (or by declaring a local minimal MigrationMeta interface) and
update the renderTypeScript signature to use the shared/local type instead of
MigrationMeta; specifically change the import of MigrationMeta and any type
annotations in the renderTypeScript(calls: ReadonlyArray<OpFactoryCall>, meta?:
MigrationMeta) declaration to reference the new shared-local type so src/core
stays free of migration/runtime imports.
🪄 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: 9c06d6f8-6800-4138-9573-593522f8b994
⛔ Files ignored due to path filters (3)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/mongo-migration-authoring/specs/migration-subsystem-refactor.spec.mdis excluded by!projects/**projects/mongo-migration-authoring/specs/planner-dual-output.spec.mdis excluded by!projects/**
📒 Files selected for processing (38)
.agents/skills/ast-visitor-pattern/SKILL.mdexamples/mongo-demo/test/manual-migration.test.tsexamples/retail-store/test/manual-migration.test.tspackages/2-mongo-family/9-family/src/core/control-instance.tspackages/2-mongo-family/9-family/src/core/mongo-target-descriptor.tspackages/3-mongo-target/1-mongo-target/package.jsonpackages/3-mongo-target/1-mongo-target/src/core/contract-to-schema.tspackages/3-mongo-target/1-mongo-target/src/core/ddl-formatter.tspackages/3-mongo-target/1-mongo-target/src/core/filter-evaluator.tspackages/3-mongo-target/1-mongo-target/src/core/migration-factories.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-planner.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-runner.tspackages/3-mongo-target/1-mongo-target/src/core/op-factory-call.tspackages/3-mongo-target/1-mongo-target/src/core/render-ops.tspackages/3-mongo-target/1-mongo-target/src/core/render-typescript.tspackages/3-mongo-target/1-mongo-target/src/exports/control.tspackages/3-mongo-target/1-mongo-target/src/exports/migration.tspackages/3-mongo-target/1-mongo-target/test/contract-to-schema.test.tspackages/3-mongo-target/1-mongo-target/test/ddl-formatter.test.tspackages/3-mongo-target/1-mongo-target/test/filter-evaluator.test.tspackages/3-mongo-target/1-mongo-target/test/migration-e2e.test.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/render-ops.test.tspackages/3-mongo-target/1-mongo-target/test/render-typescript.test.tspackages/3-mongo-target/2-mongo-adapter/src/core/mongo-planner.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/test/mongo-runner.test.tstest/integration/test/cli.mongo-db-sign.e2e.test.tstest/integration/test/cli.mongo-db-verify.e2e.test.tstest/integration/test/mongo/db-verify-sign.test.tstest/integration/test/mongo/migration-authoring-e2e.test.tstest/integration/test/mongo/migration-e2e.test.tstest/integration/test/mongo/migration-m2-vocabulary.test.tstest/integration/test/mongo/migration-psl-authoring.test.ts
💤 Files with no reviewable changes (1)
- packages/3-mongo-target/2-mongo-adapter/src/core/mongo-planner.ts
✅ Files skipped from review due to trivial changes (7)
- test/integration/test/mongo/migration-psl-authoring.test.ts
- packages/3-mongo-target/1-mongo-target/src/core/op-factory-call.ts
- packages/3-mongo-target/1-mongo-target/src/exports/migration.ts
- packages/3-mongo-target/1-mongo-target/test/render-typescript.test.ts
- .agents/skills/ast-visitor-pattern/SKILL.md
- test/integration/test/mongo/migration-m2-vocabulary.test.ts
- packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts
🚧 Files skipped from review as they are similar to previous changes (13)
- test/integration/test/cli.mongo-db-verify.e2e.test.ts
- examples/retail-store/test/manual-migration.test.ts
- packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
- test/integration/test/mongo/migration-authoring-e2e.test.ts
- test/integration/test/mongo/migration-e2e.test.ts
- packages/3-mongo-target/2-mongo-adapter/src/exports/control.ts
- test/integration/test/cli.mongo-db-sign.e2e.test.ts
- packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts
- packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.ts
- packages/3-mongo-target/1-mongo-target/test/migration-e2e.test.ts
- packages/3-mongo-target/1-mongo-target/src/exports/control.ts
- packages/3-mongo-target/1-mongo-target/package.json
- packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts
…__proto__ key Replace MigrationMeta import from @prisma-next/migration-tools/migration with a local RenderMigrationMeta type to keep src/core/ within the shared plane. Add explicit __proto__ check in renderKey to prevent prototype pollution in generated object literals.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/3-mongo-target/1-mongo-target/src/exports/control.ts (1)
3-3: Avoid exposing concrete classes in the public control API.Re-exporting concrete implementations (
FilterEvaluator,MongoMigrationPlanner,MongoMigrationRunner, and*Callclasses) makes internal refactors breaking for consumers. Prefer exposing interfaces/types + factory functions from this surface.As per coding guidelines, "Export interfaces and factory functions for public APIs; keep concrete classes as private implementation details."
Also applies to: 11-13, 16-20
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-mongo-target/1-mongo-target/src/exports/control.ts` at line 3, The public control surface is exporting concrete classes (e.g., FilterEvaluator, MongoMigrationPlanner, MongoMigrationRunner and the *Call classes); change these exports to expose only interfaces/types and factory functions instead: define and export interfaces (e.g., IFilterEvaluator, IMongoMigrationPlanner, IMongoMigrationRunner or export existing types) and implement private concrete classes inside the package, then add and export factory functions (e.g., createFilterEvaluator(...), createMongoMigrationPlanner(...), createMongoMigrationRunner(...), createXCall(...)) that return the interface types; update the export list in control.ts to export the interfaces and the new factory function names and remove re-exports of the concrete class symbols so consumers depend on interfaces/factories only.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/3-mongo-target/1-mongo-target/src/exports/control.ts`:
- Line 3: The public control surface is exporting concrete classes (e.g.,
FilterEvaluator, MongoMigrationPlanner, MongoMigrationRunner and the *Call
classes); change these exports to expose only interfaces/types and factory
functions instead: define and export interfaces (e.g., IFilterEvaluator,
IMongoMigrationPlanner, IMongoMigrationRunner or export existing types) and
implement private concrete classes inside the package, then add and export
factory functions (e.g., createFilterEvaluator(...),
createMongoMigrationPlanner(...), createMongoMigrationRunner(...),
createXCall(...)) that return the interface types; update the export list in
control.ts to export the interfaces and the new factory function names and
remove re-exports of the concrete class symbols so consumers depend on
interfaces/factories only.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: a044fa9d-4360-48cd-8e8a-59e604e3bb4e
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (6)
.agents/skills/ast-visitor-pattern/SKILL.mdpackages/2-mongo-family/9-family/README.mdpackages/3-mongo-target/1-mongo-target/README.mdpackages/3-mongo-target/1-mongo-target/package.jsonpackages/3-mongo-target/1-mongo-target/src/core/render-typescript.tspackages/3-mongo-target/1-mongo-target/src/exports/control.ts
✅ Files skipped from review due to trivial changes (2)
- packages/3-mongo-target/1-mongo-target/package.json
- .agents/skills/ast-visitor-pattern/SKILL.md
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/3-mongo-target/1-mongo-target/src/core/render-typescript.ts
MongoMigrationRunner no longer implements the framework MigrationRunner interface directly — the wrapper in mongoTargetDescriptor.createRunner() satisfies it instead. The runner accepts pre-constructed deps and has no knowledge of drivers.
Exclude mongo-runner.ts from unit coverage (integration-tested in adapter). Add tests for render-typescript edge cases (multiline arrays, null, empty arrays/objects, __proto__ key quoting, bigint fallback, undefined in arrays, special-char keys). Add tests for op-factory-call helpers (bare collection, clusteredIndex mapping). Add tests for ddl-formatter branches (max/timeseries/collation/clusteredIndex, command-less steps). Add planner tests for sparse index lookup, timeseries/clusteredIndex immutable changes, and policy violation labels. Refactor planner if-else chain to simple if/else-if/else to avoid logically impossible V8 branch. Add v8-ignore blocks for unreachable defensive fallbacks in module-level visitors and serializer error handling.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts (1)
24-33: Consider documenting the single-driver invariant for the returned wrapper.The
cachedDeps ??= createMongoRunnerDeps(options.driver)pattern caches dependencies from the firstexecute()call. Subsequent calls will reuse these deps regardless ofoptions.driver. This is safe given the current framework usage where each wrapper is tied to a single driver, but could become a subtle bug if that invariant changes.Consider either:
- Adding a comment documenting this assumption, or
- Asserting the driver hasn't changed on subsequent calls
🛡️ Optional defensive check
createRunner(_family: MongoControlFamilyInstance) { let cachedDeps: MongoRunnerDependencies | undefined; + let boundDriver: unknown; return { async execute(options) { + if (cachedDeps && boundDriver !== options.driver) { + throw new Error('Runner wrapper cannot be reused across different drivers'); + } cachedDeps ??= createMongoRunnerDeps(options.driver); + boundDriver = options.driver; const { driver: _, ...runnerOptions } = options;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts` around lines 24 - 33, The createRunner wrapper caches dependencies via cachedDeps ??= createMongoRunnerDeps(options.driver) which assumes a single driver per wrapper; add a short comment above the cachedDeps line documenting the single-driver invariant for createRunner (or implement a defensive check: on subsequent execute calls verify options.driver === cachedDeps.driver or throw) so callers and future maintainers know the assumption; reference createRunner, cachedDeps, createMongoRunnerDeps, MongoMigrationRunner and execute when making the change.packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts (2)
1141-1152: Consider usingtoMatchObjectfor related property assertions.Multiple separate assertions for
collectionandkeyscould be consolidated for clearer test output.♻️ Optional refactor
expect(calls).toHaveLength(1); expect(calls[0]).toBeInstanceOf(CreateIndexCall); const call = calls[0] as CreateIndexCall; - expect(call.collection).toBe('users'); - expect(call.keys).toEqual([{ field: 'email', direction: 1 }]); + expect(call).toMatchObject({ + collection: 'users', + keys: [{ field: 'email', direction: 1 }], + });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts` around lines 1141 - 1152, Replace the two separate assertions on the CreateIndexCall instance with a single object-shape assertion using toMatchObject: after getting calls[0] (instanceof CreateIndexCall), assert that the call matches { collection: 'users', keys: [{ field: 'email', direction: 1 }] } to consolidate related property checks; keep the instanceof CreateIndexCall check and use makeContract/planCallsSuccess/CreateIndexCall/calls to locate the code to change.
1228-1233: Consider usingtoMatchObjectfor meta property assertions.The three meta property assertions could be consolidated for clearer test output and reduced verbosity.
♻️ Optional refactor
expect(calls).toHaveLength(1); expect(calls[0]).toBeInstanceOf(CollModCall); const call = calls[0] as CollModCall; - expect(call.meta?.id).toBe('validator.users.update'); - expect(call.meta?.label).toBe('Update validator on users'); - expect(call.meta?.operationClass).toBe('destructive'); + expect(call.meta).toMatchObject({ + id: 'validator.users.update', + label: 'Update validator on users', + operationClass: 'destructive', + });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts` around lines 1228 - 1233, Replace the three separate assertions on the CollModCall meta with a single consolidated assertion using toMatchObject: locate the test that inspects calls[0] (instanceOf CollModCall), cast to call and replace the expect(call.meta?.id), expect(call.meta?.label) and expect(call.meta?.operationClass) lines with one expect(call.meta).toMatchObject({ id: 'validator.users.update', label: 'Update validator on users', operationClass: 'destructive' }) so the meta properties are asserted in one clear statement.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts`:
- Around line 329-349: The planner currently passes
changeStreamPreAndPostImages: undefined to CollModCall when the destination
removed the property; change MongoSchemaCollectionOptions handling in
planMutableOptionsDiffCall so that if dest?.changeStreamPreAndPostImages is
undefined you pass { enabled: false } instead (e.g., const desiredCSPPI =
destCSPPI ?? { enabled: false }) and use desiredCSPPI in the CollModCall and to
compute operationClass; keep CollModCall, collName and the id/label fields
intact.
In `@packages/3-mongo-target/1-mongo-target/test/ddl-formatter.test.ts`:
- Around line 367-385: Replace the direct "as never" cast on the no-op execute
step inside the test op with the double-cast pattern to preserve typing
boundaries; e.g. change "{ description: 'no-op step' } as never" to "{
description: 'no-op step' } as unknown as typeof op.execute[number]". Update the
execute array in the test (the op variable used with formatMongoOperations and
CreateIndexCommand) so the first step uses the double-cast instead of "as
never".
---
Nitpick comments:
In `@packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts`:
- Around line 24-33: The createRunner wrapper caches dependencies via cachedDeps
??= createMongoRunnerDeps(options.driver) which assumes a single driver per
wrapper; add a short comment above the cachedDeps line documenting the
single-driver invariant for createRunner (or implement a defensive check: on
subsequent execute calls verify options.driver === cachedDeps.driver or throw)
so callers and future maintainers know the assumption; reference createRunner,
cachedDeps, createMongoRunnerDeps, MongoMigrationRunner and execute when making
the change.
In `@packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts`:
- Around line 1141-1152: Replace the two separate assertions on the
CreateIndexCall instance with a single object-shape assertion using
toMatchObject: after getting calls[0] (instanceof CreateIndexCall), assert that
the call matches { collection: 'users', keys: [{ field: 'email', direction: 1 }]
} to consolidate related property checks; keep the instanceof CreateIndexCall
check and use makeContract/planCallsSuccess/CreateIndexCall/calls to locate the
code to change.
- Around line 1228-1233: Replace the three separate assertions on the
CollModCall meta with a single consolidated assertion using toMatchObject:
locate the test that inspects calls[0] (instanceOf CollModCall), cast to call
and replace the expect(call.meta?.id), expect(call.meta?.label) and
expect(call.meta?.operationClass) lines with one
expect(call.meta).toMatchObject({ id: 'validator.users.update', label: 'Update
validator on users', operationClass: 'destructive' }) so the meta properties are
asserted in one clear statement.
🪄 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: bb505928-4144-4085-8c4b-6101648bf31f
📒 Files selected for processing (16)
examples/mongo-demo/test/manual-migration.test.tsexamples/retail-store/test/manual-migration.test.tspackages/2-mongo-family/9-family/src/core/mongo-target-descriptor.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-planner.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-runner.tspackages/3-mongo-target/1-mongo-target/test/ddl-formatter.test.tspackages/3-mongo-target/1-mongo-target/test/migration-factories.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-planner.test.tspackages/3-mongo-target/1-mongo-target/test/render-typescript.test.tspackages/3-mongo-target/1-mongo-target/vitest.config.tspackages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.tstest/integration/test/mongo/migration-authoring-e2e.test.tstest/integration/test/mongo/migration-e2e.test.tstest/integration/test/mongo/migration-m2-vocabulary.test.tstest/integration/test/mongo/migration-psl-authoring.test.ts
✅ Files skipped from review due to trivial changes (5)
- packages/3-mongo-target/1-mongo-target/vitest.config.ts
- packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts
- test/integration/test/mongo/migration-authoring-e2e.test.ts
- packages/3-mongo-target/1-mongo-target/test/migration-factories.test.ts
- packages/3-mongo-target/1-mongo-target/test/render-typescript.test.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- test/integration/test/mongo/migration-m2-vocabulary.test.ts
- examples/retail-store/test/manual-migration.test.ts
- test/integration/test/mongo/migration-psl-authoring.test.ts
- packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.ts
- test/integration/test/mongo/migration-e2e.test.ts
… dest
planMutableOptionsDiffCall was passing undefined to CollModCall when the
destination removed changeStreamPreAndPostImages, which would be a no-op
instead of actually disabling the feature. Now defaults to { enabled: false }.
Also: use double-cast in ddl-formatter test, consolidate assertions
with toMatchObject in planner tests, add single-driver invariant
comment to createRunner wrapper.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts (1)
153-154: Consider runtime validation for external contract/schema.The casts from
unknowntoMongoContract/MongoSchemaIRwork correctly but rely on callers providing correctly-typed objects. Since these come through an interface boundary, runtime validation could catch misconfiguration earlier.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts` around lines 153 - 154, The code unsafely casts options.contract and options.schema to MongoContract and MongoSchemaIR (contract and originIR) without runtime checks; add runtime validation using a type-guard or schema validator (e.g., custom isMongoContract/isMongoSchemaIR functions or a Zod/io-ts schema) to verify options.contract and options.schema before casting, and throw a clear error if validation fails so callers get an early, descriptive failure instead of runtime type errors; update the code paths that use contract and originIR to use the validated values.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts`:
- Around line 153-154: The code unsafely casts options.contract and
options.schema to MongoContract and MongoSchemaIR (contract and originIR)
without runtime checks; add runtime validation using a type-guard or schema
validator (e.g., custom isMongoContract/isMongoSchemaIR functions or a Zod/io-ts
schema) to verify options.contract and options.schema before casting, and throw
a clear error if validation fails so callers get an early, descriptive failure
instead of runtime type errors; update the code paths that use contract and
originIR to use the validated values.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 58b27151-ebc9-488a-948e-772b6ee3ee79
📒 Files selected for processing (4)
packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-planner.tspackages/3-mongo-target/1-mongo-target/test/ddl-formatter.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts
✅ Files skipped from review due to trivial changes (2)
- packages/3-mongo-target/1-mongo-target/test/ddl-formatter.test.ts
- packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts
…all nodes These properties are intrinsic to each call type, not external concerns. Eliminates the operationClassVisitor/labelVisitor indirection and the v8 ignore blocks they required.
closes TML-2219
Key snippets
Runner depends on abstract interfaces only
OpFactoryCall visitor pattern
Intent
Correct the layering of the Mongo migration subsystem so that target-agnostic orchestration (planner, runner, serializer) lives in the target package and the adapter contains only concrete
mongodbdriver bindings. Then introduce a structured intermediate representation (OpFactoryCall) that separates schema-diff logic from operation materialization, enabling both runtime execution and TypeScript code generation.Change map
MarkerOperations+MongoRunnerDependenciesFactoryplanCalls()producingOpFactoryCall[], visitor-based policy checksOpFactoryCallVisitor<R>OpFactoryCall→MongoMigrationPlanOperationOpFactoryCall→ TypeScript sourcecollModfactory + helpersplanCalls()testscollModfactory + helpersThe story
Move pure modules from adapter to target. Five modules (planner, serializer, contract-to-schema, DDL formatter, filter evaluator) are git-renamed with 100% similarity. The runner is renamed with modifications. Test files follow.
Decouple the runner from
mongodb. The runner's two dependencies onDb— DDL execution and marker operations — are abstracted behind interfaces. AMongoRunnerDependenciesFactorybridges the lifecycle gap (runner constructed before driver available). The concrete factory (createMongoRunnerDeps) lives in the adapter.Remove all adapter re-exports, update consumers. The adapter's
control.tsno longer re-exports any symbol fromtarget-mongo. Eight consumer files updated to import from@prisma-next/target-mongo/control.Introduce
OpFactoryCallintermediate representation. The planner'splanCalls()method produces an array ofOpFactoryCallobjects describing which factory to call with which arguments.plan()becomes a thin wrapper:planCalls() → renderOps().Add dual renderers.
renderOps()calls factory functions to produceMongoMigrationPlanOperation[](preserving existing behavior).renderTypeScript()generates a complete runnable migration file with correct imports and factory calls.Refactor
OpFactoryCallto AST class/visitor pattern. The plain discriminated union is replaced with frozen subclasses and anOpFactoryCallVisitor<R>interface. All switch statements are replaced with visitor implementations, giving compile-time exhaustiveness.Fix TypeScript errors. Add missing
MongoSchemaIRimport and@prisma-next/migration-toolsdependency.Behavior changes & evidence
Module relocation (no behavior change): Five pure modules move from
adapter-mongototarget-mongo. All symbols now exported from@prisma-next/target-mongo/control.packages/3-mongo-target/Runner no longer depends on
Dbormongodbtypes: The runner receives all dependencies through abstract interfaces.Adapter re-exports removed; consumers import from target: All 12 backward-compat re-exports removed. Consumer files updated.
Adds
planCalls()method returningOpFactoryCall[]: The planner produces a structured intermediate representation of the schema diff.Adds
renderOps()andrenderTypeScript()renderers: Two visitor-based functions that interpretOpFactoryCall— one produces runtime operations, the other produces TypeScript source code.Adds
collModfactory function: Handles collection modification operations with configurable metadata.OpFactoryCalluses AST class/visitor pattern (structural change, no behavior change): Plain union replaced with frozen classes +OpFactoryCallVisitor<R>. All dispatch sites use visitors instead of switches.Compatibility / migration / risk
MongoMigrationRunnerconstructor signature changed: No-arg → requiresMongoRunnerDependenciesFactory. The only construction site (mongoTargetDescriptor.createRunner()) is updated.@prisma-next/target-mongo/control. One file missed (db-verify-sign.test.ts).OpFactoryCallis no longer plain data: Tests must construct class instances. If any consumer needs to serialize/deserializeOpFactoryCall, a deserialization function will be needed.execute()call: When running multiple migrations sequentially, executors and marker-ops bindings are reconstructed each time from the sameDbhandle.Follow-ups / open questions
db-verify-sign.test.tsbroken import.OpFactoryCallshould be plain data (as spec says) or AST classes (as implemented) and update the spec accordingly.renderTypeScriptare not covered by tests.Non-goals / intentionally out of scope
planCalls()separation)prisma migration plan --emit-tsMigrationRunnerinterfaceSummary by CodeRabbit
New Features
Improvements
Documentation
Tests