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

TML-1750: Add db init CLI command - #54

Merged
wmadden merged 80 commits into
mainfrom
tml-1750-add-db-init-cli-command-and-wire-it-up-to-planner-and-runner
Dec 30, 2025
Merged

wmadden merged 80 commits into
mainfrom
tml-1750-add-db-init-cli-command-and-wire-it-up-to-planner-and-runner

Conversation

@wmadden

@wmadden wmadden commented Dec 30, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

Release Notes

  • New Features

    • Added prisma-next db init command for database initialization with additive migration planning and execution
    • Plan mode (--plan) to preview migrations without applying
    • JSON output option (--json) for programmatic consumption
    • Enhanced error reporting with conflict summaries on planning failures
  • Improvements

    • Improved schema verification test infrastructure
    • Better handling of PostgreSQL adapter-level extensions
    • Refined error messages and troubleshooting guidance
  • Documentation

    • Added CLI command documentation and usage examples
    • Updated test patterns and infrastructure guidelines

✏️ Tip: You can customize this high-level summary in your review settings.

- errorMigrationPlanningFailed: for planning conflicts
- errorTargetMigrationNotSupported: for targets without migration support
- createDbInitCommand() factory with --plan and --json options
- Output formatters for plan and apply modes
- Register command under 'prisma-next db init'
- Export command from package
- Tests for empty database apply mode
- Tests for plan mode (--plan flag)
- Tests for non-empty database conflicts
- Tests for error handling (missing contract, quiet mode)
- Helper functions: setupDbInitFixture, runDbInit
- Use bracket notation for index signature properties
- Handle exactOptionalPropertyTypes for marker.profileHash
Previously only *.integration.test.ts files were included, which meant
E2E tests (*.e2e.test.ts) were not being executed. This was a
pre-existing issue affecting multiple E2E test files.
…esolution

The withTempDir helper was creating temp directories in /tmp which
caused jiti (used by loadConfig) to fail resolving workspace packages
like @prisma-next/adapter-postgres/control.

Now creates temp directories inside the cli-e2e-test-app fixture
directory where pnpm workspace symlinks are available.
The 'pg' and 'postgres' extensions in contract.extensions are adapter-level
metadata namespaces used for codec IDs (e.g., 'pg/int4@1'), not PostgreSQL
database extensions like 'pgvector'.

The planner now filters these out before validating unsupported extensions.
…matting

- Add pg and postgres extensions to db-init contract fixture
- Remove trailing newlines from snapshot files
Simplified test file naming by dropping the redundant 'integration' suffix.
The test directory already indicates these are integration tests.

cli.emit.integration.test.ts was renamed to cli.emit-core.test.ts to avoid
conflict with the existing cli.emit.test.ts file.
- cli.emit-cli-process.e2e.test.ts: Fix CLI path (wrong number of ../ segments)
- cli.db-introspect.e2e.test.ts: Update snapshots
- cli.db-introspect.test.ts: Skip tests that use broken ESM mocking strategy
- family.introspect.test.ts: Add timeouts to all tests (default was 100ms)

These tests were never running before because vitest.config.ts was only
including *.integration.test.ts files.
All async tests that perform database operations need proper timeouts.
The default 100ms timeout is too short for database operations.
…rospect tests

- codecs.test.ts: Add timeout to beforeEach hook
- family.introspect.test.ts: Add timeouts to 2 more tests
…cture

Task 7.2 documents the current state where test/integration/ contains
in-process 'e2e' tests that mock process.exit, while test/e2e/ is
intended for true subprocess E2E tests.

Proposes renaming in-process tests to drop 'e2e' suffix and adding
true subprocess tests following the cli.emit-cli-process.e2e.test.ts pattern.
Remove explicit CodecTypes type argument from sql() calls in
contract-builder.test.ts. The sql() function already has a default type
parameter that derives CodecTypes from the contract using
ExtractCodecTypes<TContract>, so the explicit parameter is unnecessary.
- CLI README: Add db init command documentation and export
- test/integration README: Update to reflect current file naming (*.test.ts)
  and clarify CLI integration tests vs true subprocess e2e tests
- cli-e2e-test-patterns.mdc: Add section clarifying in-process vs subprocess tests
Replace multiple individual expect().toBe() assertions with single
toMatchObject() calls for related values:
- Lines 299-305: Consolidate codecId assertions for builder vs fixture
- Lines 344-346: Consolidate codecId assertions for dataTypes constants
- Lines 514-544: Consolidate N:M relation assertions into single matcher

This improves test readability by showing expected state at a glance.
Wrap JSON.parse call in try/catch that throws a structured error with
the contract file path and parse error message, matching the existing
readFile error handling style. This ensures the CLI fails cleanly with
a clear error message when the contract JSON is malformed.
Split the 902-line test file into four focused test files:
- family.schema-verify.basic.test.ts (happy path, missing table/column)
- family.schema-verify.constraints.test.ts (primary key, foreign key)
- family.schema-verify.types.test.ts (type mismatch, nullability, registry)
- family.schema-verify.modes.test.ts (strict mode, extensions)

Extract shared setup into family.schema-verify.helpers.ts with:
- useDevDatabase() hook for shared database connection
- createFamilyInstance() factory
- withDriver() and runSchemaVerify() helpers
- Re-exports of common imports

Each new file is under 200 lines, well under the 500-line guideline.
Reuse the already-parsed contractJson1 object instead of re-parsing
result1.contractJson a second time. The comparison now uses the
existing parsed objects directly.
…t.test.ts

Extract boilerplate driver/familyInstance creation and teardown into
a withIntrospection helper that:
- Creates the driver
- Builds the familyInstance
- Calls introspect
- Passes the resulting schemaIR to a callback
- Ensures driver.close() in finally block

This reduces duplication across 8 tests and correctly handles driver
lifecycle in one place.
Replace silent return with explicit failure when postgresDriver.create()
throws during the invalid connection test. This ensures CI shows failure
rather than silently passing if the driver behavior changes or there's
an environment issue.
Replace 'profileHash' in contractJson with Object.hasOwn(contractJson, 'profileHash')
to ensure we're checking only own properties, not inherited ones.
The expect.stringMatching already validates that created_at is a string
matching the timestamp pattern, making the separate typeof check redundant.
Replace multiple expect().toBe() calls with a single toMatchObject matcher
for related properties (ok, summary, contract, meta). Conditionally include
profileHash in the expected object when present. Keep timing assertion
separate as it uses toBeGreaterThanOrEqual.
Clarify that loading extension packs twice is intentional to verify
the emit -> validate -> re-emit flow produces consistent results.
Introduce local interfaces (MigrationPlan, MigrationPlanner, MigrationRunner,
PlannerResult, RunnerResult) that capture the structural contracts for
migration operations. This eliminates scattered inline type casts and enables
TypeScript's discriminated union narrowing to work correctly.

This is a partial migration toward proper SPI types. Task 7.2 in
agent-os/specs/2025-12-05-db-init-command/tasks.md will move these types to
@prisma-next/core-control-plane and make migration support an explicit
optional target capability.
…preading

Use the fluent .extensions() method on the contract builder rather than
manually spreading the contract and adding extensions. This is cleaner
and leverages the intended API.
The caller can apply the default logic themselves with ?? operator,
making the interface simpler and more transparent.
…iles

Move runDbSign, setupDbSignFixture, runDbInit, setupDbInitFixture from
cli-test-helpers.ts to their respective test files. These helpers were
only used by single test files and should be co-located with those tests.

Keep only truly shared helpers in cli-test-helpers.ts:
- setupTestDirectoryFromFixtures
- setupDbTestFixture (shared base for db fixture setup)
- withTempDir
- Re-exports from CLI package
Add ./test/utils export to @prisma-next/emitter package and update
contract-imports.test.ts to use the package export instead of relative
path import. This respects package boundaries and follows the pattern
used by @prisma-next/sql-runtime/test/utils.

@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

📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between b6f87cd and 0460d0e.

📒 Files selected for processing (7)
  • packages/1-framework/3-tooling/emitter/package.json
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/contract-imports.test.ts
  • test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/db-init/contract.ts
  • test/integration/test/utils/cli-test-helpers.ts
🧰 Additional context used
📓 Path-based instructions (22)
**/package.json

📄 CodeRabbit inference engine (.cursor/rules/multi-plane-entrypoints.mdc)

Export subpath entrypoints in package.json with correct types and import mappings for ./adapter, ./control, and ./runtime paths

When adding new exports to the CLI package, add the export path with types and import mappings to the exports field in package.json

Follow multi-plane entrypoints in single packages as per .cursor/rules/multi-plane-entrypoints.mdc

When moving packages, update all script paths in package.json (including biome.json config path, scripts/clean.mjs, and other root-level script references) by counting directory depth from the package to root

Files:

  • packages/1-framework/3-tooling/emitter/package.json
packages/**/package.json

📄 CodeRabbit inference engine (.cursor/rules/shared-plane-packages.mdc)

packages/**/package.json: Shared plane packages must have sideEffects: false in package.json
Use explicit export paths in package.json following the pattern with separate export identifiers for types, validators, and factories
Shared plane packages should depend only on framework core packages and validation libraries (Arktype), not on migration-plane or runtime-plane packages

Files:

  • packages/1-framework/3-tooling/emitter/package.json
!(**/*.test.{ts,tsx}|**/*.spec.{ts,tsx})**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-patterns.mdc)

!(**/*.test.{ts,tsx}|**/*.spec.{ts,tsx})**/*.{ts,tsx}: Blind type casts (as unknown as X) are forbidden in production code; use type predicates instead
Type safety is non-negotiable; never disable type checking with @ts-expect-error to work around broken types; fix the type definitions instead

Files:

  • packages/1-framework/3-tooling/emitter/package.json
  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/utils/cli-test-helpers.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/db-init/contract.ts
  • test/integration/test/contract-imports.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/arktype-usage.mdc)

**/*.{ts,tsx}: Use the 'key?' syntax with the ? suffix for optional keys in Arktype schemas instead of using 'string | undefined' type unions
Reference schemas directly as object property values in Arktype schemas - this works seamlessly without special syntax
Use type({ '[string]': Schema }) syntax to create Record<string, Schema> types in Arktype instead of using Record<string, Schema> string notation
Use the .array() method on Arktype schemas to create array types instead of wrapping schemas in type([Schema]) or using manual validation
Extract TypeScript types from Arktype schemas using the .infer property instead of manually duplicating type definitions
Use type.declare<>() to ensure Arktype schemas match pre-existing TypeScript types for compile-time type safety, especially when working with readonly properties
Use .array().readonly() method chaining to create readonly array types in Arktype instead of using string notation like 'string[]'
Don't manually re-validate what Arktype has already checked - once validation passes, trust the structure matches the schema
Use instanceof type.errors to check for Arktype validation errors instead of other error checking patterns, for proper type narrowing
Return the original input value from validation functions instead of returning the Arktype validation result to preserve literal types

Prefer explicit, direct imports over barrel imports: import from specific module paths like @prisma/sql/builder instead of barrel re-exports like @prisma/sql

Always use Object.hasOwn() instead of hasOwnProperty() to check for own properties on objects

**/*.{ts,tsx}: Import core contract types (ContractBase, Source) and document family types (DocumentContract) from @prisma-next/contract/types
Import target-neutral operations (OperationRegistry, ArgSpec, ReturnSpec, createOperationRegistry) from @prisma-next/operations

**/*.{ts,tsx}: Extract CodecTypes from contract using the he...

Files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/utils/cli-test-helpers.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/db-init/contract.ts
  • test/integration/test/contract-imports.test.ts
**/*.test.ts

📄 CodeRabbit inference engine (.cursor/rules/contract-normalization-responsibilities.mdc)

**/*.test.ts: Contract builder tests must verify that normalization happens correctly with all required fields receiving their default values
Validator tests must verify that validation fails when required fields are missing, and must NOT test normalization behavior
Parser and emitter hook tests must test functionality with normalized contracts and must NOT test normalization behavior

**/*.test.ts: In tests using withDevDatabase() from @prisma-next/test-utils, avoid selecting or using extension-dependent columns (like pgvector, pg_trgm) when testing features unrelated to extension functionality, as pglite does not support PostgreSQL extensions
When tests must verify extension functionality end-to-end (e.g., pgvector queries), use a real PostgreSQL database instead of withDevDatabase() via withClient() and process.env['DATABASE_URL']
When writing ORM tests with includes, relation filters, or other non-extension features, explicitly exclude extension-dependent columns from select statements to ensure compatibility with pglite-based test databases

**/*.test.ts: Avoid using type assertions in tests to bypass type checking or test impossible states. Remove tests that use type assertions (e.g., 'as SqlContract') to test scenarios that contradict validated schemas.
Remove tests that use type assertions to test impossible states or test code coverage without testing real scenarios. After refactoring to use assertions, clean up unrealistic test cases.

**/*.test.ts: Write test descriptions that omit 'should' - use direct, action-oriented language (e.g., it('returns correct value') not it('should return correct value'))
Prefer object comparison with toEqual or toMatchObject instead of piece-by-piece property checks with type casts
Keep test files under 500 lines maximum and split large files by functionality, feature area, or test type using descriptive file names
Extract helper functions when the same pattern appears 3+ times, ensuring...

Files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/contract-imports.test.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/modular-refactoring-patterns.mdc)

**/*.ts: Start refactoring by extracting pure, side-effect-free utility functions as thin wrappers around AST factories and error constructors
Extract state management into separate modules defining immutable state shapes and interfaces
Replace any types with proper generic type parameters during function extraction, using existing type definitions like ModelColumnAccessor
Use the compact helper function to remove undefined values from objects when TypeScript's exactOptionalPropertyTypes is enabled
Organize imports in the following order: external type imports, external value imports, internal type imports, internal value imports

**/*.ts: Prefer assertions over defensive checks when data is guaranteed to be valid in TypeScript. Use non-null assertions (!) after validation checks instead of optional chaining or defensive conditionals.
Use assertions to access validated properties directly (e.g., columnMeta.codecId, columnMeta.nullable) instead of optional chaining (columnMeta?.codecId) after validation has already occurred.

Files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/utils/cli-test-helpers.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/db-init/contract.ts
  • test/integration/test/contract-imports.test.ts
**/*.{test,spec}.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/omit-should-in-tests.mdc)

Omit the word 'should' in test descriptions - write concise, direct descriptions instead (e.g., 'equals 1' instead of 'should equal 1')

Files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/contract-imports.test.ts
**/*.{test,spec}.ts

📄 CodeRabbit inference engine (.cursor/rules/prefer-object-matcher.mdc)

Prefer object matchers with .toMatchObject() over multiple individual expect().toBe() calls when checking 2+ related values in tests

**/*.{test,spec}.ts: Test files must not exceed 500 lines; split files that exceed this limit into multiple files organized by logical functionality
Split test files by logical groupings: by functionality (basic, errors, structure), by feature area (joins, projections, includes), or by test type (unit, integration, edge-cases)
Use descriptive test file names following the pattern {base}.{category}.test.ts, where base name indicates the subject being tested and category indicates the test type (e.g., .basic.test.ts, .errors.test.ts, .joins.test.ts)
Ensure each split test file contains all necessary imports, setup/teardown code, and is independently runnable without dependencies on other test files
Prefer object comparison assertions using toEqual or toMatchObject instead of piece-by-piece property checks with toHaveProperty or individual type assertions
Use expect.any() for type-only checks and expect.not.objectContaining() for absence checks when performing partial object comparisons
Compare entire plan structures using object comparison assertions instead of checking individual AST fields piecemeal to ensure all fields are present and correct

Use factory functions (such as createColumnRef, createParamRef, createLiteralExpr, createTableRef, createBinaryExpr) for creating AST nodes in tests instead of manual object creation

Use factory functions (e.g., createContractIR()) instead of manual object creation when creating ContractIR objects in tests. Ensure all required fields (schemaVersion, targetFamily, target, models, relations, storage, extensions, capabilities, meta, sources) are present through the factory function rather than manual construction.

**/*.{test,spec}.ts: Do not use the deprecated toMatchTypeOf() matcher in Vitest's expectTypeOf API; use toExtend() instead for verifying ...

Files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/contract-imports.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/shared-plane-packages.mdc)

Import from shared plane packages using the package name and export identifier (e.g., @prisma-next/sql-contract/types), not /exports/ paths

**/*.{ts,tsx,js,jsx}: Use arktype instead of zod for schema validation
Don't add comments if avoidable; prefer code which expresses its intent
Don't add exports for backwards compatibility unless explicitly requested
Do not reexport things from one file in another, except in the exports/ folders

**/*.{ts,tsx,js,jsx}: Import loadContractFromTs and createContractEmitCommand from the main package export @prisma-next/cli, not from subpaths
Import config utilities (defineConfig and config types) from the @prisma-next/cli/config-types subpath, not from the main package
Import loadExtensionPacks and loadExtensionPackManifest from the @prisma-next/cli/pack-loading subpath, not from the main package
Import command factory functions (e.g., createDbIntrospectCommand, createDbVerifyCommand) from their specific command subpaths (e.g., @prisma-next/cli/commands/db-introspect), not from the main package
Import the loadConfig function from the @prisma-next/cli/config-loader subpath, not from the main package

Update relative paths in source files (manifest paths, import paths, etc.) when moving packages by recalculating the path based on the new location's directory depth

If you need to disable a Biome rule for more than a couple of lines in a file, use a file-level disable comment at the top instead of many inline comments

Files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/utils/cli-test-helpers.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/db-init/contract.ts
  • test/integration/test/contract-imports.test.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/use-correct-tools.mdc)

Use local pnpm test scripts for testing; use pnpm test:coverage for all packages or pnpm coverage:packages for packages only

Files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/contract-imports.test.ts
**/*.{test,spec,util,utils}.ts

📄 CodeRabbit inference engine (.cursor/rules/test-import-patterns.mdc)

For same-package tests needing private functions, create test utilities within the same package that use relative imports and can be exported if needed, rather than exporting the private functions directly

Files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/contract-imports.test.ts
**/*.{test,spec}.{js,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

Omit 'should' from test descriptions as per .cursor/rules/omit-should-in-tests.mdc

Files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/contract-imports.test.ts
**/*.{test,spec}.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

**/*.{test,spec}.{ts,tsx,js}: Use correct test import patterns: import from source files with relative paths, don't export for tests as per .cursor/rules/test-import-patterns.mdc
Organize test files with max 500 lines, split by functionality as per .cursor/rules/test-file-organization.mdc
Prefer object matchers over multiple individual expect().toBe() calls as per .cursor/rules/prefer-object-matcher.mdc

Keep tests concise; omit 'should' from test descriptions

Files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/contract-imports.test.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

**/*.{test,spec}.{ts,tsx}: Use Vitest expect().toEqual(expect.any(Type)) pattern for type testing as per .cursor/rules/vitest-expect-typeof.mdc
Use factory functions for ContractIR objects in tests as per .cursor/rules/use-contract-ir-factories.mdc

Files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/contract-imports.test.ts
**/*.{test,spec,ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

Use factory functions for creating AST nodes instead of manual object creation as per .cursor/rules/use-ast-factories.mdc

Files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/utils/cli-test-helpers.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/db-init/contract.ts
  • test/integration/test/contract-imports.test.ts
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

**/*.{ts,tsx,js}: Use LATERAL/json_agg patterns for PostgreSQL queries as per .cursor/rules/postgres-lateral-patterns.mdc
Use Object.hasOwn() instead of hasOwnProperty() as per .cursor/rules/object-hasown.mdc
Prefer assertions over defensive checks; avoid schema validation redundancy as per .cursor/rules/prefer-assertions-over-defensive-checks.mdc

**/*.{ts,tsx,js}: Prefer links to canonical docs over long comments
Package layering is enforced; fix violations rather than bypassing (see scripts/check-imports.mjs and .cursor/rules/import-validation.mdc)
Numbered prefixes in package directory structure indicate dependency direction: lower numbers can be imported by higher numbers, never the reverse

Files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/utils/cli-test-helpers.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/db-init/contract.ts
  • test/integration/test/contract-imports.test.ts
**/*.test.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/moving-packages.mdc)

When moving test files to new locations, update paths to other packages, fixtures, and manifests (e.g., extension pack manifests) by recalculating directory depth based on the new location

Files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/contract-imports.test.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-patterns.mdc)

**/*.test.{ts,tsx}: Always validate contracts in tests using validateContract function; contracts must have fully qualified type IDs, not bare scalars
Blind type casts (as unknown as X) are acceptable only in test files for mocking and error cases
Use @ts-expect-error comments with explanations in test files only when working with dynamic proxy objects or complex type scenarios
When mocking class instances in tests, use Object.create() and Object.assign() to preserve the prototype instead of the spread operator
Common patterns in test files should be extracted into helper functions from appropriate shared utility packages or created as package-specific helpers

Files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/contract-imports.test.ts
**/test/**/*.{integration.test.ts,e2e.test.ts}

📄 CodeRabbit inference engine (.cursor/rules/typed-contract-in-tests.mdc)

Integration tests should import the typed Contract from fixtures/contract.d.ts instead of using the generic SqlContract<SqlStorage> type to provide proper type inference for tables, columns, and query results

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
**/{utils,errors}/*.ts

📄 CodeRabbit inference engine (.cursor/rules/modular-refactoring-patterns.mdc)

Centralize error constructors in a single module (e.g., utils/errors.ts) that throws specific error types

Files:

  • test/integration/test/utils/cli-test-helpers.ts
**/fixtures/**/*.{ts,tsx,js,json}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

Exclude test fixture config files from typechecking as per .cursor/rules/test-fixture-typechecking.mdc

Files:

  • test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/db-init/contract.ts
**/*contract*.{ts,tsx,json}

📄 CodeRabbit inference engine (AGENTS.md)

Capability-gated features (e.g., includeMany, returning) must be enabled in contract capabilities

Files:

  • test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/db-init/contract.ts
  • test/integration/test/contract-imports.test.ts
🧠 Learnings (2)
📚 Learning: 2025-12-26T23:02:40.679Z
Learnt from: wmadden
Repo: prisma/prisma-next PR: 38
File: packages/2-sql/3-tooling/family/src/core/migrations/plan-helpers.ts:40-47
Timestamp: 2025-12-26T23:02:40.679Z
Learning: In Prisma-next's TypeScript codebase, prefer using well-established utility libraries (e.g., Lodash) rather than building custom utilities for complex object operations such as deep freezing or deep cloning. Favor reliable, battle-tested functions and ensure dependencies are reviewed for tree-shaking and bundle size. If a lightweight utility suffices, consider modern native approaches or smaller libs.

Applied to files:

  • test/integration/test/cli.emit-core.test.ts
  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/test/utils/cli-test-helpers.ts
  • test/integration/test/cli.db-sign.e2e.test.ts
  • test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/db-init/contract.ts
  • test/integration/test/contract-imports.test.ts
📚 Learning: 2025-12-10T16:25:48.326Z
Learnt from: CR
Repo: prisma/prisma-next PR: 0
File: .cursor/rules/test-import-patterns.mdc:0-0
Timestamp: 2025-12-10T16:25:48.326Z
Learning: Applies to **/*.{test,spec}.ts : Cross-package tests should import from package exports using workspace package names (e.g., `prisma-next/package-name/...`)

Applied to files:

  • test/integration/test/contract-imports.test.ts
🧬 Code graph analysis (2)
test/integration/test/cli.db-sign.e2e.test.ts (1)
test/integration/test/utils/cli-test-helpers.ts (3)
  • setupTestDirectoryFromFixtures (96-147)
  • setupDbTestFixture (274-309)
  • executeCommand (314-314)
test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/db-init/contract.ts (2)
test/integration/test/family.schema-verify.helpers.ts (1)
  • defineContract (20-20)
scripts/validate-rules.mjs (1)
  • m (59-59)
🔇 Additional comments (10)
test/integration/test/cli.emit-core.test.ts (1)

166-169: LGTM! Past review comment addressed correctly.

The changes successfully address the past review comment by switching from stringified comparison to idiomatic object equality using .toEqual(). This provides better error messages with object diffs and is more readable.

test/integration/test/contract-imports.test.ts (1)

10-10: LGTM! Clean refactoring with proper patterns.

The changes successfully improve the test structure:

  • Import now uses the workspace package name for cross-package test utilities, addressing the previous review comment
  • The runTscAndAssertSuccess helper effectively consolidates TypeScript compilation checks and enhances debugging by including generated contract.d.ts content in error messages
  • Factory function usage for createContractIR follows the coding guidelines and simplifies test setup

Also applies to: 23-58, 76-76, 227-227, 235-235, 369-369

test/integration/test/utils/cli-test-helpers.ts (3)

262-268: LGTM - Interface properly exported.

The DbTestFixtureOptions interface is now correctly exported and well-documented. The optional schemaSql parameter provides the necessary flexibility for different test scenarios (empty database vs. pre-populated schema).


274-309: Conditional SQL execution is correct for db-init test scenarios.

The conditional at lines 280-285 is necessary to support different test scenarios:

  • db-sign tests: Always require a schema to verify against (uses default via schemaSql ?? DEFAULT_USER_TABLE_SQL)
  • db-init tests: Sometimes need an empty database to test bootstrap/initialization behavior (omit schemaSql)

This addresses the earlier question about why the condition is needed - it enables testing db-init against empty databases.


320-372: LGTM - Well-designed test infrastructure.

The withTempDir decorator follows best practices:

  • Uses beforeEach/afterEach for per-test cleanup (per coding guidelines)
  • Properly tracks directories in a Set for cleanup
  • Creates directories within fixtureAppDir to enable jiti workspace package resolution
  • Handles cleanup errors gracefully with try-catch

This provides a clean abstraction for managing temporary test directories.

test/integration/test/cli.db-sign.e2e.test.ts (3)

19-26: LGTM - Test-specific constant correctly placed.

The DEFAULT_USER_TABLE_SQL constant is appropriately defined in the test file rather than being exported from cli-test-helpers, as it's a test-specific detail for db-sign tests.


27-43: LGTM - Helper correctly placed in test file.

The setupDbSignFixture helper provides db-sign-specific defaults and is correctly placed in the test file per feedback. The nullish coalescing for default schema SQL is clean and appropriate.


45-62: LGTM - Clean abstraction for command execution.

The runDbSign helper properly encapsulates the CWD management pattern with appropriate try-finally cleanup. The _configPath parameter is intentionally unused (underscore prefix per convention) but kept for consistency with the function signature pattern.

test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/db-init/contract.ts (1)

1-20: LGTM - Proper use of contract builder pattern.

The contract is correctly built using builder methods throughout (.target(), .extensions(), .table(), .model(), .build()). The extensions are properly defined with both postgres (version metadata) and pg (namespace for codec IDs like 'pg/int4@1').

test/integration/test/cli.db-init.e2e.test.ts (1)

36-337: LGTM - Comprehensive e2e test suite.

The test suite follows best practices:

  • Helper correctly placed in test file per feedback
  • Comprehensive coverage: happy path, plan mode, conflicts, error handling
  • Uses withDevDatabase and withClient for proper cleanup
  • Test descriptions omit 'should' per guidelines
  • Uses object matchers with toMatchObject for multiple related values
  • Proper timeout handling with timeouts.spinUpPpgDev

Update @prisma-next/emitter and @prisma-next/sql-runtime to build
test/utils.ts as part of the tsup build output. This ensures the
./test/utils export points to built files in dist/ rather than source
TypeScript files, which wouldn't be available when the packages are
published (only dist/ is in the files array).
Replace verbose conditional spread with ifDefined helper to satisfy
exactOptionalPropertyTypes while keeping the code cleaner.
These command files (db-init, db-introspect, db-schema-verify, db-sign)
are thin wrappers around Commander.js setup and delegation to family
instance methods. They are tested via e2e tests in the integration-tests
package (test/integration/test/cli.*.e2e.test.ts) rather than unit tests,
following the same pattern as contract-emit.ts and db-verify.ts.
With e2e-tested command files properly excluded, the remaining code
has 100% coverage. Set thresholds to 95% to maintain high coverage.
@wmadden
wmadden force-pushed the tml-1750-add-db-init-cli-command-and-wire-it-up-to-planner-and-runner branch from 0d42a84 to 7446ac1 Compare December 30, 2025 07:27

@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 (1)
packages/1-framework/3-tooling/cli/vitest.config.ts (1)

21-61: Add explicit include to coverage configuration per coding guidelines.

The coding guidelines specify that vitest configurations should include an explicit include: ['src/**/*.ts'] in the coverage configuration to ensure source files are tracked properly and avoid 0% coverage when tests import from package exports.

As per coding guidelines, add the include property:

🔎 Proposed fix
     coverage: {
       provider: 'v8',
       reporter: ['text', 'json', 'html'],
+      include: ['src/**/*.ts'],
       exclude: [
         'dist/**',
📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between 0d42a84 and 7446ac1.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (3)
  • packages/1-framework/3-tooling/cli/vitest.config.ts
  • test/integration/package.json
  • test/integration/test/cli.db-init.e2e.test.ts
🧰 Additional context used
📓 Path-based instructions (25)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/arktype-usage.mdc)

**/*.{ts,tsx}: Use the 'key?' syntax with the ? suffix for optional keys in Arktype schemas instead of using 'string | undefined' type unions
Reference schemas directly as object property values in Arktype schemas - this works seamlessly without special syntax
Use type({ '[string]': Schema }) syntax to create Record<string, Schema> types in Arktype instead of using Record<string, Schema> string notation
Use the .array() method on Arktype schemas to create array types instead of wrapping schemas in type([Schema]) or using manual validation
Extract TypeScript types from Arktype schemas using the .infer property instead of manually duplicating type definitions
Use type.declare<>() to ensure Arktype schemas match pre-existing TypeScript types for compile-time type safety, especially when working with readonly properties
Use .array().readonly() method chaining to create readonly array types in Arktype instead of using string notation like 'string[]'
Don't manually re-validate what Arktype has already checked - once validation passes, trust the structure matches the schema
Use instanceof type.errors to check for Arktype validation errors instead of other error checking patterns, for proper type narrowing
Return the original input value from validation functions instead of returning the Arktype validation result to preserve literal types

Prefer explicit, direct imports over barrel imports: import from specific module paths like @prisma/sql/builder instead of barrel re-exports like @prisma/sql

Always use Object.hasOwn() instead of hasOwnProperty() to check for own properties on objects

**/*.{ts,tsx}: Import core contract types (ContractBase, Source) and document family types (DocumentContract) from @prisma-next/contract/types
Import target-neutral operations (OperationRegistry, ArgSpec, ReturnSpec, createOperationRegistry) from @prisma-next/operations

**/*.{ts,tsx}: Extract CodecTypes from contract using the he...

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/*.test.ts

📄 CodeRabbit inference engine (.cursor/rules/contract-normalization-responsibilities.mdc)

**/*.test.ts: Contract builder tests must verify that normalization happens correctly with all required fields receiving their default values
Validator tests must verify that validation fails when required fields are missing, and must NOT test normalization behavior
Parser and emitter hook tests must test functionality with normalized contracts and must NOT test normalization behavior

**/*.test.ts: In tests using withDevDatabase() from @prisma-next/test-utils, avoid selecting or using extension-dependent columns (like pgvector, pg_trgm) when testing features unrelated to extension functionality, as pglite does not support PostgreSQL extensions
When tests must verify extension functionality end-to-end (e.g., pgvector queries), use a real PostgreSQL database instead of withDevDatabase() via withClient() and process.env['DATABASE_URL']
When writing ORM tests with includes, relation filters, or other non-extension features, explicitly exclude extension-dependent columns from select statements to ensure compatibility with pglite-based test databases

**/*.test.ts: Avoid using type assertions in tests to bypass type checking or test impossible states. Remove tests that use type assertions (e.g., 'as SqlContract') to test scenarios that contradict validated schemas.
Remove tests that use type assertions to test impossible states or test code coverage without testing real scenarios. After refactoring to use assertions, clean up unrealistic test cases.

**/*.test.ts: Write test descriptions that omit 'should' - use direct, action-oriented language (e.g., it('returns correct value') not it('should return correct value'))
Prefer object comparison with toEqual or toMatchObject instead of piece-by-piece property checks with type casts
Keep test files under 500 lines maximum and split large files by functionality, feature area, or test type using descriptive file names
Extract helper functions when the same pattern appears 3+ times, ensuring...

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/modular-refactoring-patterns.mdc)

**/*.ts: Start refactoring by extracting pure, side-effect-free utility functions as thin wrappers around AST factories and error constructors
Extract state management into separate modules defining immutable state shapes and interfaces
Replace any types with proper generic type parameters during function extraction, using existing type definitions like ModelColumnAccessor
Use the compact helper function to remove undefined values from objects when TypeScript's exactOptionalPropertyTypes is enabled
Organize imports in the following order: external type imports, external value imports, internal type imports, internal value imports

**/*.ts: Prefer assertions over defensive checks when data is guaranteed to be valid in TypeScript. Use non-null assertions (!) after validation checks instead of optional chaining or defensive conditionals.
Use assertions to access validated properties directly (e.g., columnMeta.codecId, columnMeta.nullable) instead of optional chaining (columnMeta?.codecId) after validation has already occurred.

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/*.{test,spec}.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/omit-should-in-tests.mdc)

Omit the word 'should' in test descriptions - write concise, direct descriptions instead (e.g., 'equals 1' instead of 'should equal 1')

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec}.ts

📄 CodeRabbit inference engine (.cursor/rules/prefer-object-matcher.mdc)

Prefer object matchers with .toMatchObject() over multiple individual expect().toBe() calls when checking 2+ related values in tests

**/*.{test,spec}.ts: Test files must not exceed 500 lines; split files that exceed this limit into multiple files organized by logical functionality
Split test files by logical groupings: by functionality (basic, errors, structure), by feature area (joins, projections, includes), or by test type (unit, integration, edge-cases)
Use descriptive test file names following the pattern {base}.{category}.test.ts, where base name indicates the subject being tested and category indicates the test type (e.g., .basic.test.ts, .errors.test.ts, .joins.test.ts)
Ensure each split test file contains all necessary imports, setup/teardown code, and is independently runnable without dependencies on other test files
Prefer object comparison assertions using toEqual or toMatchObject instead of piece-by-piece property checks with toHaveProperty or individual type assertions
Use expect.any() for type-only checks and expect.not.objectContaining() for absence checks when performing partial object comparisons
Compare entire plan structures using object comparison assertions instead of checking individual AST fields piecemeal to ensure all fields are present and correct

Use factory functions (such as createColumnRef, createParamRef, createLiteralExpr, createTableRef, createBinaryExpr) for creating AST nodes in tests instead of manual object creation

Use factory functions (e.g., createContractIR()) instead of manual object creation when creating ContractIR objects in tests. Ensure all required fields (schemaVersion, targetFamily, target, models, relations, storage, extensions, capabilities, meta, sources) are present through the factory function rather than manual construction.

**/*.{test,spec}.ts: Do not use the deprecated toMatchTypeOf() matcher in Vitest's expectTypeOf API; use toExtend() instead for verifying ...

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/shared-plane-packages.mdc)

Import from shared plane packages using the package name and export identifier (e.g., @prisma-next/sql-contract/types), not /exports/ paths

**/*.{ts,tsx,js,jsx}: Use arktype instead of zod for schema validation
Don't add comments if avoidable; prefer code which expresses its intent
Don't add exports for backwards compatibility unless explicitly requested
Do not reexport things from one file in another, except in the exports/ folders

**/*.{ts,tsx,js,jsx}: Import loadContractFromTs and createContractEmitCommand from the main package export @prisma-next/cli, not from subpaths
Import config utilities (defineConfig and config types) from the @prisma-next/cli/config-types subpath, not from the main package
Import loadExtensionPacks and loadExtensionPackManifest from the @prisma-next/cli/pack-loading subpath, not from the main package
Import command factory functions (e.g., createDbIntrospectCommand, createDbVerifyCommand) from their specific command subpaths (e.g., @prisma-next/cli/commands/db-introspect), not from the main package
Import the loadConfig function from the @prisma-next/cli/config-loader subpath, not from the main package

Update relative paths in source files (manifest paths, import paths, etc.) when moving packages by recalculating the path based on the new location's directory depth

If you need to disable a Biome rule for more than a couple of lines in a file, use a file-level disable comment at the top instead of many inline comments

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/use-correct-tools.mdc)

Use local pnpm test scripts for testing; use pnpm test:coverage for all packages or pnpm coverage:packages for packages only

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec,util,utils}.ts

📄 CodeRabbit inference engine (.cursor/rules/test-import-patterns.mdc)

For same-package tests needing private functions, create test utilities within the same package that use relative imports and can be exported if needed, rather than exporting the private functions directly

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec}.{js,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

Omit 'should' from test descriptions as per .cursor/rules/omit-should-in-tests.mdc

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec}.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

**/*.{test,spec}.{ts,tsx,js}: Use correct test import patterns: import from source files with relative paths, don't export for tests as per .cursor/rules/test-import-patterns.mdc
Organize test files with max 500 lines, split by functionality as per .cursor/rules/test-file-organization.mdc
Prefer object matchers over multiple individual expect().toBe() calls as per .cursor/rules/prefer-object-matcher.mdc

Keep tests concise; omit 'should' from test descriptions

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

**/*.{test,spec}.{ts,tsx}: Use Vitest expect().toEqual(expect.any(Type)) pattern for type testing as per .cursor/rules/vitest-expect-typeof.mdc
Use factory functions for ContractIR objects in tests as per .cursor/rules/use-contract-ir-factories.mdc

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec,ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

Use factory functions for creating AST nodes instead of manual object creation as per .cursor/rules/use-ast-factories.mdc

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

**/*.{ts,tsx,js}: Use LATERAL/json_agg patterns for PostgreSQL queries as per .cursor/rules/postgres-lateral-patterns.mdc
Use Object.hasOwn() instead of hasOwnProperty() as per .cursor/rules/object-hasown.mdc
Prefer assertions over defensive checks; avoid schema validation redundancy as per .cursor/rules/prefer-assertions-over-defensive-checks.mdc

**/*.{ts,tsx,js}: Prefer links to canonical docs over long comments
Package layering is enforced; fix violations rather than bypassing (see scripts/check-imports.mjs and .cursor/rules/import-validation.mdc)
Numbered prefixes in package directory structure indicate dependency direction: lower numbers can be imported by higher numbers, never the reverse

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/test/**/*.{integration.test.ts,e2e.test.ts}

📄 CodeRabbit inference engine (.cursor/rules/typed-contract-in-tests.mdc)

Integration tests should import the typed Contract from fixtures/contract.d.ts instead of using the generic SqlContract<SqlStorage> type to provide proper type inference for tables, columns, and query results

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.test.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/moving-packages.mdc)

When moving test files to new locations, update paths to other packages, fixtures, and manifests (e.g., extension pack manifests) by recalculating directory depth based on the new location

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-patterns.mdc)

**/*.test.{ts,tsx}: Always validate contracts in tests using validateContract function; contracts must have fully qualified type IDs, not bare scalars
Blind type casts (as unknown as X) are acceptable only in test files for mocking and error cases
Use @ts-expect-error comments with explanations in test files only when working with dynamic proxy objects or complex type scenarios
When mocking class instances in tests, use Object.create() and Object.assign() to preserve the prototype instead of the spread operator
Common patterns in test files should be extracted into helper functions from appropriate shared utility packages or created as package-specific helpers

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
!(**/*.test.{ts,tsx}|**/*.spec.{ts,tsx})**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-patterns.mdc)

!(**/*.test.{ts,tsx}|**/*.spec.{ts,tsx})**/*.{ts,tsx}: Blind type casts (as unknown as X) are forbidden in production code; use type predicates instead
Type safety is non-negotiable; never disable type checking with @ts-expect-error to work around broken types; fix the type definitions instead

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • test/integration/package.json
  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/package.json

📄 CodeRabbit inference engine (.cursor/rules/multi-plane-entrypoints.mdc)

Export subpath entrypoints in package.json with correct types and import mappings for ./adapter, ./control, and ./runtime paths

When adding new exports to the CLI package, add the export path with types and import mappings to the exports field in package.json

Follow multi-plane entrypoints in single packages as per .cursor/rules/multi-plane-entrypoints.mdc

When moving packages, update all script paths in package.json (including biome.json config path, scripts/clean.mjs, and other root-level script references) by counting directory depth from the package to root

Files:

  • test/integration/package.json
**/*config.ts

📄 CodeRabbit inference engine (.cursor/rules/config-validation-and-normalization.mdc)

**/*config.ts: Use Arktype for validation in defineConfig() functions when implementing config files
Validate config structure using Arktype schemas and throw errors with clear messages when structure is invalid
Apply default values for optional config fields in defineConfig() and return a fully normalized config object
Use join() and dirname() from node:path for default path resolution in normalized config outputs
Validate and normalize nested config structures at each level using Arktype schemas
Join multiple Arktype validation error messages with semicolons for clear, actionable error reporting to users

Files:

  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/*.config.*

📄 CodeRabbit inference engine (.cursor/rules/declarative-config.mdc)

Prefer declarative configuration over hardcoded logic in config generators - use declarative data structures (JSON config files) instead of hardcoded conditionals for validation rules, constraints, and configuration logic

Files:

  • packages/1-framework/3-tooling/cli/vitest.config.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/import-validation.mdc)

packages/**/*.{ts,tsx}: Same-layer imports are allowed: packages in the same layer can import from each other (e.g., orm-lane can import from sql-relational-core if both are in the lanes layer)
Cross-layer imports must flow inward (toward core): packages can only import from inner layers (closer to core). Outer layers cannot import from inner layers (e.g., core layer cannot import from lanes layer)

Import SQL emitter hook (sqlTargetFamilyHook) from @prisma-next/sql-contract-emitter

Files:

  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/vitest.config.ts

📄 CodeRabbit inference engine (.cursor/rules/test-import-patterns.mdc)

Use vite-tsconfig-paths plugin in vitest configuration to automatically resolve workspace dependencies using tsconfig path mappings, rather than manually maintaining aliases

Add explicit include: ['src/**/*.ts'] in coverage configuration to ensure source files are tracked for coverage reports, avoiding 0% coverage when tests import from package exports

Files:

  • packages/1-framework/3-tooling/cli/vitest.config.ts
{src,packages}/**/cli/**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

{src,packages}/**/cli/**/*.{ts,tsx,js}: Follow CLI command description patterns as per .cursor/rules/cli-command-descriptions.mdc
CLI command error handling: throw errors, don't call process.exit as per .cursor/rules/cli-error-handling.mdc
Follow CLI package export structure and import patterns as per .cursor/rules/cli-package-exports.mdc

Files:

  • packages/1-framework/3-tooling/cli/vitest.config.ts
{src,packages}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

Prohibit inline type imports in source files as per .cursor/rules/no-inline-imports.mdc

Files:

  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/*.config.ts

📄 CodeRabbit inference engine (.cursor/rules/testing-guide.mdc)

Mark external dependencies in tsup.config.ts to prevent bundling: workspace packages (/^@prisma-next\//), CommonJS dependencies, and packages with native modules (e.g., @prisma/dev)

Files:

  • packages/1-framework/3-tooling/cli/vitest.config.ts
🧠 Learnings (1)
📚 Learning: 2025-12-26T23:02:40.679Z
Learnt from: wmadden
Repo: prisma/prisma-next PR: 38
File: packages/2-sql/3-tooling/family/src/core/migrations/plan-helpers.ts:40-47
Timestamp: 2025-12-26T23:02:40.679Z
Learning: In Prisma-next's TypeScript codebase, prefer using well-established utility libraries (e.g., Lodash) rather than building custom utilities for complex object operations such as deep freezing or deep cloning. Favor reliable, battle-tested functions and ensure dependencies are reviewed for tree-shaking and bundle size. If a lightweight utility suffices, consider modern native approaches or smaller libs.

Applied to files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
🧬 Code graph analysis (1)
test/integration/test/cli.db-init.e2e.test.ts (2)
test/integration/test/utils/cli-test-helpers.ts (6)
  • setupTestDirectoryFromFixtures (96-147)
  • setupDbTestFixture (274-309)
  • executeCommand (314-314)
  • withTempDir (338-372)
  • setupCommandMocks (317-317)
  • getExitCode (315-315)
packages/1-framework/3-tooling/cli/src/commands/db-init.ts (1)
  • createDbInitCommand (141-408)
🔇 Additional comments (7)
test/integration/package.json (1)

26-34: LGTM! Dependency reorganization looks correct.

The addition of @prisma-next/operations, @prisma-next/utils, and repositioning of related packages aligns with the broader platform reorganization described in the PR. All dependencies correctly use workspace:* versioning.

test/integration/test/cli.db-init.e2e.test.ts (4)

1-13: LGTM! Import patterns follow coding guidelines.

The imports correctly use:

  • Command-specific subpaths for CLI commands
  • Workspace package names for cross-package imports
  • Relative paths for local test utilities

22-34: LGTM! Helper correctly handles optional parameters.

The ifDefined utility properly handles the optional schemaSql parameter, addressing the concern from previous review comments about optional property handling.


40-52: LGTM! Helper function correctly manages execution context.

The helper properly handles directory changes and ensures cleanup via the finally block, following established patterns for CLI command testing.


72-280: LGTM! Test coverage is comprehensive and well-structured.

The test suite effectively covers:

  • Happy path scenarios (apply and plan modes)
  • JSON output formatting
  • Database state verification
  • Conflict detection
  • Error cases

All tests follow coding guidelines with proper use of object matchers, timeout handling, and database lifecycle management.

packages/1-framework/3-tooling/cli/vitest.config.ts (2)

36-37: LGTM - Clear rationale for command file exclusions.

The updated comment effectively explains why command files are excluded from unit test coverage and references the e2e test location pattern.


39-42: E2e test coverage confirmed for all newly excluded commands.

All four newly excluded commands have corresponding e2e test files in place:

  • cli.db-init.e2e.test.ts
  • cli.db-introspect.e2e.test.ts
  • cli.db-schema-verify.e2e.test.ts
  • cli.db-sign.e2e.test.ts

The exclusions from vitest coverage are justified by their e2e test implementation.

Add include: ['src/**/*.ts'] to the coverage config so Vitest
properly tracks source files for accurate coverage reports.
Replace manual createDbInitCommand + process.chdir + executeCommand
pattern with the existing runDbInit helper to reduce duplication and
maintain consistency. The helper already handles cwd management.

@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

📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between 7446ac1 and b7295b7.

📒 Files selected for processing (2)
  • packages/1-framework/3-tooling/cli/vitest.config.ts
  • test/integration/test/cli.db-init.e2e.test.ts
🧰 Additional context used
📓 Path-based instructions (24)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/arktype-usage.mdc)

**/*.{ts,tsx}: Use the 'key?' syntax with the ? suffix for optional keys in Arktype schemas instead of using 'string | undefined' type unions
Reference schemas directly as object property values in Arktype schemas - this works seamlessly without special syntax
Use type({ '[string]': Schema }) syntax to create Record<string, Schema> types in Arktype instead of using Record<string, Schema> string notation
Use the .array() method on Arktype schemas to create array types instead of wrapping schemas in type([Schema]) or using manual validation
Extract TypeScript types from Arktype schemas using the .infer property instead of manually duplicating type definitions
Use type.declare<>() to ensure Arktype schemas match pre-existing TypeScript types for compile-time type safety, especially when working with readonly properties
Use .array().readonly() method chaining to create readonly array types in Arktype instead of using string notation like 'string[]'
Don't manually re-validate what Arktype has already checked - once validation passes, trust the structure matches the schema
Use instanceof type.errors to check for Arktype validation errors instead of other error checking patterns, for proper type narrowing
Return the original input value from validation functions instead of returning the Arktype validation result to preserve literal types

Prefer explicit, direct imports over barrel imports: import from specific module paths like @prisma/sql/builder instead of barrel re-exports like @prisma/sql

Always use Object.hasOwn() instead of hasOwnProperty() to check for own properties on objects

**/*.{ts,tsx}: Import core contract types (ContractBase, Source) and document family types (DocumentContract) from @prisma-next/contract/types
Import target-neutral operations (OperationRegistry, ArgSpec, ReturnSpec, createOperationRegistry) from @prisma-next/operations

**/*.{ts,tsx}: Extract CodecTypes from contract using the he...

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/*.test.ts

📄 CodeRabbit inference engine (.cursor/rules/contract-normalization-responsibilities.mdc)

**/*.test.ts: Contract builder tests must verify that normalization happens correctly with all required fields receiving their default values
Validator tests must verify that validation fails when required fields are missing, and must NOT test normalization behavior
Parser and emitter hook tests must test functionality with normalized contracts and must NOT test normalization behavior

**/*.test.ts: In tests using withDevDatabase() from @prisma-next/test-utils, avoid selecting or using extension-dependent columns (like pgvector, pg_trgm) when testing features unrelated to extension functionality, as pglite does not support PostgreSQL extensions
When tests must verify extension functionality end-to-end (e.g., pgvector queries), use a real PostgreSQL database instead of withDevDatabase() via withClient() and process.env['DATABASE_URL']
When writing ORM tests with includes, relation filters, or other non-extension features, explicitly exclude extension-dependent columns from select statements to ensure compatibility with pglite-based test databases

**/*.test.ts: Avoid using type assertions in tests to bypass type checking or test impossible states. Remove tests that use type assertions (e.g., 'as SqlContract') to test scenarios that contradict validated schemas.
Remove tests that use type assertions to test impossible states or test code coverage without testing real scenarios. After refactoring to use assertions, clean up unrealistic test cases.

**/*.test.ts: Write test descriptions that omit 'should' - use direct, action-oriented language (e.g., it('returns correct value') not it('should return correct value'))
Prefer object comparison with toEqual or toMatchObject instead of piece-by-piece property checks with type casts
Keep test files under 500 lines maximum and split large files by functionality, feature area, or test type using descriptive file names
Extract helper functions when the same pattern appears 3+ times, ensuring...

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/modular-refactoring-patterns.mdc)

**/*.ts: Start refactoring by extracting pure, side-effect-free utility functions as thin wrappers around AST factories and error constructors
Extract state management into separate modules defining immutable state shapes and interfaces
Replace any types with proper generic type parameters during function extraction, using existing type definitions like ModelColumnAccessor
Use the compact helper function to remove undefined values from objects when TypeScript's exactOptionalPropertyTypes is enabled
Organize imports in the following order: external type imports, external value imports, internal type imports, internal value imports

**/*.ts: Prefer assertions over defensive checks when data is guaranteed to be valid in TypeScript. Use non-null assertions (!) after validation checks instead of optional chaining or defensive conditionals.
Use assertions to access validated properties directly (e.g., columnMeta.codecId, columnMeta.nullable) instead of optional chaining (columnMeta?.codecId) after validation has already occurred.

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/*.{test,spec}.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/omit-should-in-tests.mdc)

Omit the word 'should' in test descriptions - write concise, direct descriptions instead (e.g., 'equals 1' instead of 'should equal 1')

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec}.ts

📄 CodeRabbit inference engine (.cursor/rules/prefer-object-matcher.mdc)

Prefer object matchers with .toMatchObject() over multiple individual expect().toBe() calls when checking 2+ related values in tests

**/*.{test,spec}.ts: Test files must not exceed 500 lines; split files that exceed this limit into multiple files organized by logical functionality
Split test files by logical groupings: by functionality (basic, errors, structure), by feature area (joins, projections, includes), or by test type (unit, integration, edge-cases)
Use descriptive test file names following the pattern {base}.{category}.test.ts, where base name indicates the subject being tested and category indicates the test type (e.g., .basic.test.ts, .errors.test.ts, .joins.test.ts)
Ensure each split test file contains all necessary imports, setup/teardown code, and is independently runnable without dependencies on other test files
Prefer object comparison assertions using toEqual or toMatchObject instead of piece-by-piece property checks with toHaveProperty or individual type assertions
Use expect.any() for type-only checks and expect.not.objectContaining() for absence checks when performing partial object comparisons
Compare entire plan structures using object comparison assertions instead of checking individual AST fields piecemeal to ensure all fields are present and correct

Use factory functions (such as createColumnRef, createParamRef, createLiteralExpr, createTableRef, createBinaryExpr) for creating AST nodes in tests instead of manual object creation

Use factory functions (e.g., createContractIR()) instead of manual object creation when creating ContractIR objects in tests. Ensure all required fields (schemaVersion, targetFamily, target, models, relations, storage, extensions, capabilities, meta, sources) are present through the factory function rather than manual construction.

**/*.{test,spec}.ts: Do not use the deprecated toMatchTypeOf() matcher in Vitest's expectTypeOf API; use toExtend() instead for verifying ...

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/shared-plane-packages.mdc)

Import from shared plane packages using the package name and export identifier (e.g., @prisma-next/sql-contract/types), not /exports/ paths

**/*.{ts,tsx,js,jsx}: Use arktype instead of zod for schema validation
Don't add comments if avoidable; prefer code which expresses its intent
Don't add exports for backwards compatibility unless explicitly requested
Do not reexport things from one file in another, except in the exports/ folders

**/*.{ts,tsx,js,jsx}: Import loadContractFromTs and createContractEmitCommand from the main package export @prisma-next/cli, not from subpaths
Import config utilities (defineConfig and config types) from the @prisma-next/cli/config-types subpath, not from the main package
Import loadExtensionPacks and loadExtensionPackManifest from the @prisma-next/cli/pack-loading subpath, not from the main package
Import command factory functions (e.g., createDbIntrospectCommand, createDbVerifyCommand) from their specific command subpaths (e.g., @prisma-next/cli/commands/db-introspect), not from the main package
Import the loadConfig function from the @prisma-next/cli/config-loader subpath, not from the main package

Update relative paths in source files (manifest paths, import paths, etc.) when moving packages by recalculating the path based on the new location's directory depth

If you need to disable a Biome rule for more than a couple of lines in a file, use a file-level disable comment at the top instead of many inline comments

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/use-correct-tools.mdc)

Use local pnpm test scripts for testing; use pnpm test:coverage for all packages or pnpm coverage:packages for packages only

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec,util,utils}.ts

📄 CodeRabbit inference engine (.cursor/rules/test-import-patterns.mdc)

For same-package tests needing private functions, create test utilities within the same package that use relative imports and can be exported if needed, rather than exporting the private functions directly

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec}.{js,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

Omit 'should' from test descriptions as per .cursor/rules/omit-should-in-tests.mdc

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec}.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

**/*.{test,spec}.{ts,tsx,js}: Use correct test import patterns: import from source files with relative paths, don't export for tests as per .cursor/rules/test-import-patterns.mdc
Organize test files with max 500 lines, split by functionality as per .cursor/rules/test-file-organization.mdc
Prefer object matchers over multiple individual expect().toBe() calls as per .cursor/rules/prefer-object-matcher.mdc

Keep tests concise; omit 'should' from test descriptions

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

**/*.{test,spec}.{ts,tsx}: Use Vitest expect().toEqual(expect.any(Type)) pattern for type testing as per .cursor/rules/vitest-expect-typeof.mdc
Use factory functions for ContractIR objects in tests as per .cursor/rules/use-contract-ir-factories.mdc

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec,ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

Use factory functions for creating AST nodes instead of manual object creation as per .cursor/rules/use-ast-factories.mdc

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

**/*.{ts,tsx,js}: Use LATERAL/json_agg patterns for PostgreSQL queries as per .cursor/rules/postgres-lateral-patterns.mdc
Use Object.hasOwn() instead of hasOwnProperty() as per .cursor/rules/object-hasown.mdc
Prefer assertions over defensive checks; avoid schema validation redundancy as per .cursor/rules/prefer-assertions-over-defensive-checks.mdc

**/*.{ts,tsx,js}: Prefer links to canonical docs over long comments
Package layering is enforced; fix violations rather than bypassing (see scripts/check-imports.mjs and .cursor/rules/import-validation.mdc)
Numbered prefixes in package directory structure indicate dependency direction: lower numbers can be imported by higher numbers, never the reverse

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/test/**/*.{integration.test.ts,e2e.test.ts}

📄 CodeRabbit inference engine (.cursor/rules/typed-contract-in-tests.mdc)

Integration tests should import the typed Contract from fixtures/contract.d.ts instead of using the generic SqlContract<SqlStorage> type to provide proper type inference for tables, columns, and query results

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.test.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/moving-packages.mdc)

When moving test files to new locations, update paths to other packages, fixtures, and manifests (e.g., extension pack manifests) by recalculating directory depth based on the new location

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-patterns.mdc)

**/*.test.{ts,tsx}: Always validate contracts in tests using validateContract function; contracts must have fully qualified type IDs, not bare scalars
Blind type casts (as unknown as X) are acceptable only in test files for mocking and error cases
Use @ts-expect-error comments with explanations in test files only when working with dynamic proxy objects or complex type scenarios
When mocking class instances in tests, use Object.create() and Object.assign() to preserve the prototype instead of the spread operator
Common patterns in test files should be extracted into helper functions from appropriate shared utility packages or created as package-specific helpers

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
!(**/*.test.{ts,tsx}|**/*.spec.{ts,tsx})**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-patterns.mdc)

!(**/*.test.{ts,tsx}|**/*.spec.{ts,tsx})**/*.{ts,tsx}: Blind type casts (as unknown as X) are forbidden in production code; use type predicates instead
Type safety is non-negotiable; never disable type checking with @ts-expect-error to work around broken types; fix the type definitions instead

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/*config.ts

📄 CodeRabbit inference engine (.cursor/rules/config-validation-and-normalization.mdc)

**/*config.ts: Use Arktype for validation in defineConfig() functions when implementing config files
Validate config structure using Arktype schemas and throw errors with clear messages when structure is invalid
Apply default values for optional config fields in defineConfig() and return a fully normalized config object
Use join() and dirname() from node:path for default path resolution in normalized config outputs
Validate and normalize nested config structures at each level using Arktype schemas
Join multiple Arktype validation error messages with semicolons for clear, actionable error reporting to users

Files:

  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/*.config.*

📄 CodeRabbit inference engine (.cursor/rules/declarative-config.mdc)

Prefer declarative configuration over hardcoded logic in config generators - use declarative data structures (JSON config files) instead of hardcoded conditionals for validation rules, constraints, and configuration logic

Files:

  • packages/1-framework/3-tooling/cli/vitest.config.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/import-validation.mdc)

packages/**/*.{ts,tsx}: Same-layer imports are allowed: packages in the same layer can import from each other (e.g., orm-lane can import from sql-relational-core if both are in the lanes layer)
Cross-layer imports must flow inward (toward core): packages can only import from inner layers (closer to core). Outer layers cannot import from inner layers (e.g., core layer cannot import from lanes layer)

Import SQL emitter hook (sqlTargetFamilyHook) from @prisma-next/sql-contract-emitter

Files:

  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/vitest.config.ts

📄 CodeRabbit inference engine (.cursor/rules/test-import-patterns.mdc)

Use vite-tsconfig-paths plugin in vitest configuration to automatically resolve workspace dependencies using tsconfig path mappings, rather than manually maintaining aliases

Add explicit include: ['src/**/*.ts'] in coverage configuration to ensure source files are tracked for coverage reports, avoiding 0% coverage when tests import from package exports

Files:

  • packages/1-framework/3-tooling/cli/vitest.config.ts
{src,packages}/**/cli/**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

{src,packages}/**/cli/**/*.{ts,tsx,js}: Follow CLI command description patterns as per .cursor/rules/cli-command-descriptions.mdc
CLI command error handling: throw errors, don't call process.exit as per .cursor/rules/cli-error-handling.mdc
Follow CLI package export structure and import patterns as per .cursor/rules/cli-package-exports.mdc

Files:

  • packages/1-framework/3-tooling/cli/vitest.config.ts
{src,packages}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

Prohibit inline type imports in source files as per .cursor/rules/no-inline-imports.mdc

Files:

  • packages/1-framework/3-tooling/cli/vitest.config.ts
**/*.config.ts

📄 CodeRabbit inference engine (.cursor/rules/testing-guide.mdc)

Mark external dependencies in tsup.config.ts to prevent bundling: workspace packages (/^@prisma-next\//), CommonJS dependencies, and packages with native modules (e.g., @prisma/dev)

Files:

  • packages/1-framework/3-tooling/cli/vitest.config.ts
🧠 Learnings (2)
📚 Learning: 2025-12-26T23:02:40.679Z
Learnt from: wmadden
Repo: prisma/prisma-next PR: 38
File: packages/2-sql/3-tooling/family/src/core/migrations/plan-helpers.ts:40-47
Timestamp: 2025-12-26T23:02:40.679Z
Learning: In Prisma-next's TypeScript codebase, prefer using well-established utility libraries (e.g., Lodash) rather than building custom utilities for complex object operations such as deep freezing or deep cloning. Favor reliable, battle-tested functions and ensure dependencies are reviewed for tree-shaking and bundle size. If a lightweight utility suffices, consider modern native approaches or smaller libs.

Applied to files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
📚 Learning: 2025-12-26T23:05:52.166Z
Learnt from: CR
Repo: prisma/prisma-next PR: 0
File: .cursor/rules/testing-guide.mdc:0-0
Timestamp: 2025-12-26T23:05:52.166Z
Learning: Applies to **/vitest.config.ts : Add explicit `include: ['src/**/*.ts']` in coverage configuration to ensure source files are tracked for coverage reports, avoiding 0% coverage when tests import from package exports

Applied to files:

  • packages/1-framework/3-tooling/cli/vitest.config.ts
🧬 Code graph analysis (1)
test/integration/test/cli.db-init.e2e.test.ts (4)
test/integration/test/utils/cli-test-helpers.ts (1)
  • setupTestDirectoryFromFixtures (96-147)
scripts/coverage-report.mjs (2)
  • command (50-50)
  • result (435-435)
packages/1-framework/3-tooling/cli/src/commands/db-init.ts (1)
  • createDbInitCommand (141-408)
test/utils/src/exports/index.ts (1)
  • withDevDatabase (45-55)
🔇 Additional comments (11)
test/integration/test/cli.db-init.e2e.test.ts (8)

1-13: LGTM! Imports follow guidelines correctly.

The imports use correct subpaths for CLI commands and relative paths for within-package test utilities.


18-34: LGTM! Optional parameter handling uses the correct pattern.

The ifDefined helper correctly implements the compact pattern for optional properties with exactOptionalPropertyTypes.


36-52: LGTM! Helper correctly manages working directory.

The helper properly handles process.chdir() with cleanup in the finally block and provides a clean abstraction for running db-init commands in tests.


54-71: LGTM! Test setup and teardown follow best practices.

Mock setup in beforeEach and cleanup in afterEach ensure test isolation.


72-163: LGTM! Empty database tests are comprehensive and well-structured.

Tests verify both text output and JSON envelope format, check database state post-migration, and use object matchers correctly with toMatchObject and expect.any().


165-249: LGTM! Plan mode tests correctly verify dry-run behavior.

Tests confirm that --plan mode shows operations without applying them and verify database remains unchanged. JSON envelope assertions properly check for absence of execution and marker fields.


251-280: LGTM! Conflict detection test works correctly.

Test properly sets up a conflicting schema and verifies the command fails with a non-zero exit code.


282-328: LGTM! Error handling tests cover key failure scenarios.

Tests verify missing contract file error handling and quiet mode behavior. The regex pattern for error message matching provides appropriate flexibility for error message variations.

packages/1-framework/3-tooling/cli/vitest.config.ts (3)

24-24: LGTM! Include directive properly added.

This addresses the past review comment and coding guideline by ensuring source files are tracked for coverage reports.


37-43: The exclusions for command files are justified—all referenced e2e tests exist and cover the excluded commands. The pattern test/integration/test/cli.*.e2e.test.ts correctly matches the test files (e.g., cli.db-init.e2e.test.ts, cli.db-introspect.e2e.test.ts, cli.db-schema-verify.e2e.test.ts, cli.db-sign.e2e.test.ts), confirming that these thin CLI command wrappers are covered by integration tests rather than unit tests.


56-60: No action required—coverage threshold configuration is sound.

The 95% threshold applies only to 2 utility files (src/utils/result.ts and src/utils/result-handler.ts), both of which have dedicated unit test files. The remaining source files are strategically excluded with clear rationale: command files tested via e2e tests, UI/UX utilities, error factories, and files with non-Error exception handling. The configuration properly uses the include directive and exclude list as recommended by coding guidelines, making it a well-justified approach rather than an aggressive overreach.

The rejects.toThrow() assertion already confirms the command failed,
making the subsequent getExitCode() check redundant. Remove it to keep
the test focused and avoid duplicate failure checks.

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
agent-os/specs/2025-12-05-db-init-command/tasks.md (1)

148-167: Orchestration description uses type annotation; consider including domain terminology for clarity.

Line 152 states: "Build a ControlFamilyInstance<'sql'> from family/target/adapter/driver descriptors."

Based on the coding guidelines and learnings, this describes working with an instantiated SQL family instance. The type annotation ControlFamilyInstance<'sql'> is technically correct for code-level reference. For architectural clarity in orchestration steps, consider mentioning the domain term "SQL family instance" alongside or instead of the type annotation. This aligns with the learning from PR 51 to preserve this domain-specific terminology.

📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between b7295b7 and 15fe287.

📒 Files selected for processing (3)
  • agent-os/specs/2025-12-05-db-init-command/planning/branch-4-plan.md
  • agent-os/specs/2025-12-05-db-init-command/tasks.md
  • test/integration/test/cli.db-init.e2e.test.ts
💤 Files with no reviewable changes (1)
  • agent-os/specs/2025-12-05-db-init-command/planning/branch-4-plan.md
🧰 Additional context used
📓 Path-based instructions (20)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/arktype-usage.mdc)

**/*.{ts,tsx}: Use the 'key?' syntax with the ? suffix for optional keys in Arktype schemas instead of using 'string | undefined' type unions
Reference schemas directly as object property values in Arktype schemas - this works seamlessly without special syntax
Use type({ '[string]': Schema }) syntax to create Record<string, Schema> types in Arktype instead of using Record<string, Schema> string notation
Use the .array() method on Arktype schemas to create array types instead of wrapping schemas in type([Schema]) or using manual validation
Extract TypeScript types from Arktype schemas using the .infer property instead of manually duplicating type definitions
Use type.declare<>() to ensure Arktype schemas match pre-existing TypeScript types for compile-time type safety, especially when working with readonly properties
Use .array().readonly() method chaining to create readonly array types in Arktype instead of using string notation like 'string[]'
Don't manually re-validate what Arktype has already checked - once validation passes, trust the structure matches the schema
Use instanceof type.errors to check for Arktype validation errors instead of other error checking patterns, for proper type narrowing
Return the original input value from validation functions instead of returning the Arktype validation result to preserve literal types

Prefer explicit, direct imports over barrel imports: import from specific module paths like @prisma/sql/builder instead of barrel re-exports like @prisma/sql

Always use Object.hasOwn() instead of hasOwnProperty() to check for own properties on objects

**/*.{ts,tsx}: Import core contract types (ContractBase, Source) and document family types (DocumentContract) from @prisma-next/contract/types
Import target-neutral operations (OperationRegistry, ArgSpec, ReturnSpec, createOperationRegistry) from @prisma-next/operations

**/*.{ts,tsx}: Extract CodecTypes from contract using the he...

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.test.ts

📄 CodeRabbit inference engine (.cursor/rules/contract-normalization-responsibilities.mdc)

**/*.test.ts: Contract builder tests must verify that normalization happens correctly with all required fields receiving their default values
Validator tests must verify that validation fails when required fields are missing, and must NOT test normalization behavior
Parser and emitter hook tests must test functionality with normalized contracts and must NOT test normalization behavior

**/*.test.ts: In tests using withDevDatabase() from @prisma-next/test-utils, avoid selecting or using extension-dependent columns (like pgvector, pg_trgm) when testing features unrelated to extension functionality, as pglite does not support PostgreSQL extensions
When tests must verify extension functionality end-to-end (e.g., pgvector queries), use a real PostgreSQL database instead of withDevDatabase() via withClient() and process.env['DATABASE_URL']
When writing ORM tests with includes, relation filters, or other non-extension features, explicitly exclude extension-dependent columns from select statements to ensure compatibility with pglite-based test databases

**/*.test.ts: Avoid using type assertions in tests to bypass type checking or test impossible states. Remove tests that use type assertions (e.g., 'as SqlContract') to test scenarios that contradict validated schemas.
Remove tests that use type assertions to test impossible states or test code coverage without testing real scenarios. After refactoring to use assertions, clean up unrealistic test cases.

**/*.test.ts: Write test descriptions that omit 'should' - use direct, action-oriented language (e.g., it('returns correct value') not it('should return correct value'))
Prefer object comparison with toEqual or toMatchObject instead of piece-by-piece property checks with type casts
Keep test files under 500 lines maximum and split large files by functionality, feature area, or test type using descriptive file names
Extract helper functions when the same pattern appears 3+ times, ensuring...

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/modular-refactoring-patterns.mdc)

**/*.ts: Start refactoring by extracting pure, side-effect-free utility functions as thin wrappers around AST factories and error constructors
Extract state management into separate modules defining immutable state shapes and interfaces
Replace any types with proper generic type parameters during function extraction, using existing type definitions like ModelColumnAccessor
Use the compact helper function to remove undefined values from objects when TypeScript's exactOptionalPropertyTypes is enabled
Organize imports in the following order: external type imports, external value imports, internal type imports, internal value imports

**/*.ts: Prefer assertions over defensive checks when data is guaranteed to be valid in TypeScript. Use non-null assertions (!) after validation checks instead of optional chaining or defensive conditionals.
Use assertions to access validated properties directly (e.g., columnMeta.codecId, columnMeta.nullable) instead of optional chaining (columnMeta?.codecId) after validation has already occurred.

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec}.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/omit-should-in-tests.mdc)

Omit the word 'should' in test descriptions - write concise, direct descriptions instead (e.g., 'equals 1' instead of 'should equal 1')

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec}.ts

📄 CodeRabbit inference engine (.cursor/rules/prefer-object-matcher.mdc)

Prefer object matchers with .toMatchObject() over multiple individual expect().toBe() calls when checking 2+ related values in tests

**/*.{test,spec}.ts: Test files must not exceed 500 lines; split files that exceed this limit into multiple files organized by logical functionality
Split test files by logical groupings: by functionality (basic, errors, structure), by feature area (joins, projections, includes), or by test type (unit, integration, edge-cases)
Use descriptive test file names following the pattern {base}.{category}.test.ts, where base name indicates the subject being tested and category indicates the test type (e.g., .basic.test.ts, .errors.test.ts, .joins.test.ts)
Ensure each split test file contains all necessary imports, setup/teardown code, and is independently runnable without dependencies on other test files
Prefer object comparison assertions using toEqual or toMatchObject instead of piece-by-piece property checks with toHaveProperty or individual type assertions
Use expect.any() for type-only checks and expect.not.objectContaining() for absence checks when performing partial object comparisons
Compare entire plan structures using object comparison assertions instead of checking individual AST fields piecemeal to ensure all fields are present and correct

Use factory functions (such as createColumnRef, createParamRef, createLiteralExpr, createTableRef, createBinaryExpr) for creating AST nodes in tests instead of manual object creation

Use factory functions (e.g., createContractIR()) instead of manual object creation when creating ContractIR objects in tests. Ensure all required fields (schemaVersion, targetFamily, target, models, relations, storage, extensions, capabilities, meta, sources) are present through the factory function rather than manual construction.

**/*.{test,spec}.ts: Do not use the deprecated toMatchTypeOf() matcher in Vitest's expectTypeOf API; use toExtend() instead for verifying ...

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/shared-plane-packages.mdc)

Import from shared plane packages using the package name and export identifier (e.g., @prisma-next/sql-contract/types), not /exports/ paths

**/*.{ts,tsx,js,jsx}: Use arktype instead of zod for schema validation
Don't add comments if avoidable; prefer code which expresses its intent
Don't add exports for backwards compatibility unless explicitly requested
Do not reexport things from one file in another, except in the exports/ folders

**/*.{ts,tsx,js,jsx}: Import loadContractFromTs and createContractEmitCommand from the main package export @prisma-next/cli, not from subpaths
Import config utilities (defineConfig and config types) from the @prisma-next/cli/config-types subpath, not from the main package
Import loadExtensionPacks and loadExtensionPackManifest from the @prisma-next/cli/pack-loading subpath, not from the main package
Import command factory functions (e.g., createDbIntrospectCommand, createDbVerifyCommand) from their specific command subpaths (e.g., @prisma-next/cli/commands/db-introspect), not from the main package
Import the loadConfig function from the @prisma-next/cli/config-loader subpath, not from the main package

Update relative paths in source files (manifest paths, import paths, etc.) when moving packages by recalculating the path based on the new location's directory depth

If you need to disable a Biome rule for more than a couple of lines in a file, use a file-level disable comment at the top instead of many inline comments

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/use-correct-tools.mdc)

Use local pnpm test scripts for testing; use pnpm test:coverage for all packages or pnpm coverage:packages for packages only

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec,util,utils}.ts

📄 CodeRabbit inference engine (.cursor/rules/test-import-patterns.mdc)

For same-package tests needing private functions, create test utilities within the same package that use relative imports and can be exported if needed, rather than exporting the private functions directly

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec}.{js,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

Omit 'should' from test descriptions as per .cursor/rules/omit-should-in-tests.mdc

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec}.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

**/*.{test,spec}.{ts,tsx,js}: Use correct test import patterns: import from source files with relative paths, don't export for tests as per .cursor/rules/test-import-patterns.mdc
Organize test files with max 500 lines, split by functionality as per .cursor/rules/test-file-organization.mdc
Prefer object matchers over multiple individual expect().toBe() calls as per .cursor/rules/prefer-object-matcher.mdc

Keep tests concise; omit 'should' from test descriptions

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

**/*.{test,spec}.{ts,tsx}: Use Vitest expect().toEqual(expect.any(Type)) pattern for type testing as per .cursor/rules/vitest-expect-typeof.mdc
Use factory functions for ContractIR objects in tests as per .cursor/rules/use-contract-ir-factories.mdc

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{test,spec,ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

Use factory functions for creating AST nodes instead of manual object creation as per .cursor/rules/use-ast-factories.mdc

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

**/*.{ts,tsx,js}: Use LATERAL/json_agg patterns for PostgreSQL queries as per .cursor/rules/postgres-lateral-patterns.mdc
Use Object.hasOwn() instead of hasOwnProperty() as per .cursor/rules/object-hasown.mdc
Prefer assertions over defensive checks; avoid schema validation redundancy as per .cursor/rules/prefer-assertions-over-defensive-checks.mdc

**/*.{ts,tsx,js}: Prefer links to canonical docs over long comments
Package layering is enforced; fix violations rather than bypassing (see scripts/check-imports.mjs and .cursor/rules/import-validation.mdc)
Numbered prefixes in package directory structure indicate dependency direction: lower numbers can be imported by higher numbers, never the reverse

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/test/**/*.{integration.test.ts,e2e.test.ts}

📄 CodeRabbit inference engine (.cursor/rules/typed-contract-in-tests.mdc)

Integration tests should import the typed Contract from fixtures/contract.d.ts instead of using the generic SqlContract<SqlStorage> type to provide proper type inference for tables, columns, and query results

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.test.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/moving-packages.mdc)

When moving test files to new locations, update paths to other packages, fixtures, and manifests (e.g., extension pack manifests) by recalculating directory depth based on the new location

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-patterns.mdc)

**/*.test.{ts,tsx}: Always validate contracts in tests using validateContract function; contracts must have fully qualified type IDs, not bare scalars
Blind type casts (as unknown as X) are acceptable only in test files for mocking and error cases
Use @ts-expect-error comments with explanations in test files only when working with dynamic proxy objects or complex type scenarios
When mocking class instances in tests, use Object.create() and Object.assign() to preserve the prototype instead of the spread operator
Common patterns in test files should be extracted into helper functions from appropriate shared utility packages or created as package-specific helpers

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
!(**/*.test.{ts,tsx}|**/*.spec.{ts,tsx})**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-patterns.mdc)

!(**/*.test.{ts,tsx}|**/*.spec.{ts,tsx})**/*.{ts,tsx}: Blind type casts (as unknown as X) are forbidden in production code; use type predicates instead
Type safety is non-negotiable; never disable type checking with @ts-expect-error to work around broken types; fix the type definitions instead

Files:

  • test/integration/test/cli.db-init.e2e.test.ts
  • agent-os/specs/2025-12-05-db-init-command/tasks.md
**/*.{md,mdc}

📄 CodeRabbit inference engine (.cursor/rules/README.md)

Keep docs, READMEs, and rules up-to-date as per .cursor/rules/doc-maintenance.mdc

Files:

  • agent-os/specs/2025-12-05-db-init-command/tasks.md
**/*.{md,markdown}

📄 CodeRabbit inference engine (.cursor/rules/moving-packages.mdc)

After moving a package, update documentation including READMEs, AGENTS.md, and other documentation files to reflect the new package location

Files:

  • agent-os/specs/2025-12-05-db-init-command/tasks.md
**/{README,*.md,.cursor/rules/**/*.mdc}

📄 CodeRabbit inference engine (AGENTS.md)

Keep docs current (READMEs, rules, links)

Files:

  • agent-os/specs/2025-12-05-db-init-command/tasks.md
🧠 Learnings (2)
📚 Learning: 2025-12-26T23:02:40.679Z
Learnt from: wmadden
Repo: prisma/prisma-next PR: 38
File: packages/2-sql/3-tooling/family/src/core/migrations/plan-helpers.ts:40-47
Timestamp: 2025-12-26T23:02:40.679Z
Learning: In Prisma-next's TypeScript codebase, prefer using well-established utility libraries (e.g., Lodash) rather than building custom utilities for complex object operations such as deep freezing or deep cloning. Favor reliable, battle-tested functions and ensure dependencies are reviewed for tree-shaking and bundle size. If a lightweight utility suffices, consider modern native approaches or smaller libs.

Applied to files:

  • test/integration/test/cli.db-init.e2e.test.ts
📚 Learning: 2025-12-28T05:53:44.429Z
Learnt from: wmadden
Repo: prisma/prisma-next PR: 51
File: agent-os/specs/2025-12-05-db-init-command/verifications/branch-3-runner.md:20-20
Timestamp: 2025-12-28T05:53:44.429Z
Learning: In code reviews across the repository, preserve the domain-specific term "SQL family instance" when referring to an instantiated SqlControlFamilyInstance that provides control-plane operations. Do not replace it with generic terms like "database connection" or "configuration". Treat this phrase as an architectural concept consistently used throughout the codebase.

Applied to files:

  • agent-os/specs/2025-12-05-db-init-command/tasks.md
🧬 Code graph analysis (1)
test/integration/test/cli.db-init.e2e.test.ts (2)
test/integration/test/utils/cli-test-helpers.ts (4)
  • setupTestDirectoryFromFixtures (96-147)
  • setupDbTestFixture (274-309)
  • executeCommand (314-314)
  • setupCommandMocks (317-317)
test/utils/src/exports/index.ts (1)
  • withDevDatabase (45-55)
🔇 Additional comments (5)
agent-os/specs/2025-12-05-db-init-command/tasks.md (3)

256-266: Clarify scope: Are test infrastructure cleanup items in scope for this PR?

Lines 256–266 (task 7.2) describe current state of test infrastructure and propose cleanup (renaming in-process tests, moving subprocess tests). This task is correctly placed in section 7 ("Follow-up Cleanup"), which is out-of-scope for v1.

Confirm that this documentation reflects your understanding of current state rather than changes being made in this PR. If cleanup is not being done in this PR, the document is accurate. If it is being done, move this content to the appropriate task section (perhaps as a new branch).


134-186: File path references should be verified against actual PR implementation.

The changed sections (3.1–3.5) provide specific file paths with ✅ completion markers:

  • Line 137: packages/1-framework/3-tooling/cli/src/commands/db-init.ts and packages/1-framework/3-tooling/cli/src/cli.ts
  • Line 167: Orchestration in packages/1-framework/3-tooling/cli/src/commands/db-init.ts
  • Line 177: Output formatting in packages/1-framework/3-tooling/cli/src/utils/output.ts
  • Line 186: Test file at test/integration/test/cli.db-init.e2e.test.ts

Without access to the full codebase, these cannot be verified as existing and matching the described functionality. Ensure the specification matches the actual implementation before merging.


272-272: > Likely an incorrect or invalid review comment.

test/integration/test/cli.db-init.e2e.test.ts (2)

1-51: LGTM: Well-structured test helpers.

The imports and helper functions are well-organized. The setupDbInitFixture correctly uses ifDefined to handle optional properties, and runDbInit properly manages CWD changes with cleanup in the finally block.


71-276: Excellent test coverage for core scenarios.

The test suite comprehensively covers the key scenarios:

  • Empty database initialization (apply mode)
  • Plan mode (dry run)
  • JSON output in both modes
  • Conflict detection with existing schema
  • Proper verification of database state changes

The tests correctly use withDevDatabase for setup and withClient for verification after command execution, avoiding connection conflicts.

Comment on lines +94 to +110
await withClient(connectionString, async (client) => {
const result = await client.query(
'select core_hash, profile_hash from prisma_contract.marker where id = $1',
[1],
);
expect(result.rows.length).toBe(1);
expect(result.rows[0]?.core_hash).toBeDefined();
});

// Verify table was created
await withClient(connectionString, async (client) => {
const result = await client.query(`
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = 'user'
`);
expect(result.rows.length).toBe(1);
});

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.

🧹 Nitpick | 🔵 Trivial

Consider using object matchers for database verification.

The database verification could use a single object matcher instead of multiple individual expects, making the assertions more concise and comprehensive.

🔎 Proposed refactor
            // Verify marker was created in database
            await withClient(connectionString, async (client) => {
              const result = await client.query(
                'select core_hash, profile_hash from prisma_contract.marker where id = $1',
                [1],
              );
-             expect(result.rows.length).toBe(1);
-             expect(result.rows[0]?.core_hash).toBeDefined();
+             expect(result.rows).toMatchObject([
+               {
+                 core_hash: expect.any(String),
+                 profile_hash: expect.anything(),
+               },
+             ]);
            });

            // Verify table was created
            await withClient(connectionString, async (client) => {
              const result = await client.query(`
                SELECT table_name FROM information_schema.tables
                WHERE table_schema = 'public' AND table_name = 'user'
              `);
-             expect(result.rows.length).toBe(1);
+             expect(result.rows).toMatchObject([{ table_name: 'user' }]);
            });
🤖 Prompt for AI Agents
In test/integration/test/cli.db-init.e2e.test.ts around lines 94 to 110, the
test uses multiple individual expects to verify DB rows and table presence;
replace those with single object matchers for clarity and completeness: for the
first query assert the returned row matches an object shape (e.g.
expect(result.rows[0]).toMatchObject({ core_hash: expect.any(String),
profile_hash: expect.anything() })) and assert result.rows.length === 1 in the
same expect if desired; for the table check assert the rows array equals or
contains an object with table_name: 'user' (e.g.
expect(result.rows).toContainEqual({ table_name: 'user' })) so both presence and
shape are validated in single, concise assertions.

Comment on lines +186 to +201
// Verify no changes were made to database
await withClient(connectionString, async (client) => {
// Table should NOT exist
const tableResult = await client.query(`
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = 'user'
`);
expect(tableResult.rows.length).toBe(0);

// Marker should NOT exist
const schemaResult = await client.query(`
SELECT schema_name FROM information_schema.schemata
WHERE schema_name = 'prisma_contract'
`);
expect(schemaResult.rows.length).toBe(0);
});

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.

🧹 Nitpick | 🔵 Trivial

Consider using array equality assertions for absence checks.

When verifying that no rows exist, using toEqual([]) is more direct than checking rows.length.

🔎 Proposed refactor
            // Verify no changes were made to database
            await withClient(connectionString, async (client) => {
              // Table should NOT exist
              const tableResult = await client.query(`
                SELECT table_name FROM information_schema.tables
                WHERE table_schema = 'public' AND table_name = 'user'
              `);
-             expect(tableResult.rows.length).toBe(0);
+             expect(tableResult.rows).toEqual([]);

              // Marker should NOT exist
              const schemaResult = await client.query(`
                SELECT schema_name FROM information_schema.schemata
                WHERE schema_name = 'prisma_contract'
              `);
-             expect(schemaResult.rows.length).toBe(0);
+             expect(schemaResult.rows).toEqual([]);
            });
🤖 Prompt for AI Agents
In test/integration/test/cli.db-init.e2e.test.ts around lines 186 to 201, the
assertions that check for absence of rows use expect(rows.length).toBe(0);
change both checks to assert array equality directly
(expect(tableResult.rows).toEqual([]) and expect(schemaResult.rows).toEqual([]))
so the tests more explicitly verify there are no rows and produce clearer
failures.

Comment on lines +305 to +323
it(
'handles quiet mode flag',
async () => {
await withDevDatabase(async ({ connectionString }) => {
const { testSetup, configPath } = await setupDbInitFixture(
connectionString,
createTempDir,
fixtureSubdir,
);

await runDbInit(testSetup, ['--config', configPath, '--quiet', '--no-color']);

// In quiet mode, success output should be minimal
const output = consoleOutput.join('\n');
expect(output).not.toContain('Bootstrap');
});
},
timeouts.spinUpPpgDev,
);

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.

🧹 Nitpick | 🔵 Trivial

Consider reorganizing the quiet mode test.

The "handles quiet mode flag" test is currently in the "error handling" describe block, but quiet mode is an output formatting feature rather than error handling. Consider moving it to a separate describe block like "output modes" or grouping it with other non-error scenarios.

🔎 Proposed reorganization
    describe('error handling', () => {
      it(
        'handles missing contract file',
        async () => {
          await withDevDatabase(async ({ connectionString }) => {
            const testSetup = setupTestDirectoryFromFixtures(
              createTempDir,
              fixtureSubdir,
              'prisma-next.config.with-db.ts',
              { '{{DB_URL}}': connectionString },
            );
            const configPath = testSetup.configPath;

            // Don't emit contract - it should be missing
            await expect(
              runDbInit(testSetup, ['--config', configPath, '--no-color']),
            ).rejects.toThrow();

            // Verify error output
            const errorOutput = consoleErrors.join('\n');
            expect(errorOutput).toContain('PN-CLI-4');
            expect(errorOutput).toMatch(/file.*not found|not found.*file/i);
          });
        },
        timeouts.spinUpPpgDev,
      );
+   });
+
+   describe('output modes', () => {
      it(
        'handles quiet mode flag',
        async () => {
          await withDevDatabase(async ({ connectionString }) => {
            const { testSetup, configPath } = await setupDbInitFixture(
              connectionString,
              createTempDir,
              fixtureSubdir,
            );

            await runDbInit(testSetup, ['--config', configPath, '--quiet', '--no-color']);

            // In quiet mode, success output should be minimal
            const output = consoleOutput.join('\n');
            expect(output).not.toContain('Bootstrap');
          });
        },
        timeouts.spinUpPpgDev,
      );
    });

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In test/integration/test/cli.db-init.e2e.test.ts around lines 305 to 323, the
"handles quiet mode flag" test is located inside the "error handling" describe
block but it tests output formatting (quiet mode) not error behavior; move this
it(...) block out of the error handling describe and into a new or existing
describe (e.g., "output modes" or "output formatting") so tests are grouped by
concern, updating any indentation and surrounding hooks accordingly to keep
setup/teardown scoped correctly.

@wmadden

wmadden commented Dec 30, 2025

Copy link
Copy Markdown
Contributor Author

@CodeRabbit shut up

@coderabbitai

coderabbitai Bot commented Dec 30, 2025

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@wmadden Understood. I'll remain quiet unless you need assistance in the future.

@wmadden

wmadden commented Dec 30, 2025

Copy link
Copy Markdown
Contributor Author

Merging without review to progress to the next task - all tests pass but NPM deploy is broken

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.

1 participant