Repository navigation
Conversation
Define the spec and plan for on-disk migration persistence, covering contract-to-contract diffing, abstract ops IR, migration file management, DAG reconstruction, and CLI commands (migration plan, new, verify, db update). Key decisions: offline contract-to-contract planner (no DB for migration plan), abstract op IR on disk resolved to SQL at apply time, sha256:empty sentinel, direct contract IR diffing (not via SqlSchemaIR conversion).
…R (M1)
Implement Milestone 1 of on-disk migrations: a pure contract-to-contract
diff planner that produces abstract migration operation IR.
Abstract ops IR (core-control-plane):
- 8 operation types: enableExtension, createStorageType, createTable,
addColumn, addPrimaryKey, addUniqueConstraint, createIndex, addForeignKey
- ADR 044 structured pre/post check vocabulary (14 check types)
- ContractDiffResult union (success with ops, failure with conflicts)
- EMPTY_CONTRACT_HASH sentinel for new projects
Contract planner (family-sql):
- planContractDiff({ from, to }) diffs two SqlStorage states
- Deterministic op ordering matching existing Postgres planner
- Semantic satisfaction for constraints (unique satisfies index, etc.)
- Conflict detection: type change, nullability tightening, column/table
removal, PK change → failure with structured conflicts
- Extension detection via codec→extension mapping (pgvector)
- Pre/post check generation per ADR 044
20 unit tests covering all additive op types, conflict cases,
determinism, edge cases (NOT NULL with/without defaults, PK addition).
pnpm lint:deps passes with no violations.
TML-1936 [PN] M1: Planner + abstract ops IR
Contract-to-contract diff planner that produces abstract operation IR. No DB connection needed — pure, offline diffing of two |
|
Important Review skippedDraft detected. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the Use the checkbox below for a quick retry:
WalkthroughThis change introduces the abstract operations intermediate representation (IR) for on-disk migrations and a contract-to-contract planner that determines DDL operations required to evolve a database schema from one state to another. It includes supporting documentation and comprehensive test coverage. Changes
Tip Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs). Note 🎁 Summarized by CodeRabbit FreeYour organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login. Comment |
@prisma-next/runtime-executor
@prisma-next/sql-runtime
@prisma-next/integration-kysely
@prisma-next/extension-pgvector
@prisma-next/sql-orm-client
@prisma-next/contract-authoring
@prisma-next/contract-psl
@prisma-next/contract-ts
@prisma-next/ids
@prisma-next/cli
@prisma-next/emitter
@prisma-next/eslint-plugin
@prisma-next/migration-tools
@prisma-next/vite-plugin-contract-emit
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/family-sql
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-lane
@prisma-next/target-postgres
@prisma-next/adapter-postgres
@prisma-next/driver-postgres
@prisma-next/postgres
@prisma-next/core-control-plane
@prisma-next/core-execution-plane
@prisma-next/contract
@prisma-next/operations
@prisma-next/plan
@prisma-next/utils
commit: |
…irst draft) New package @prisma-next/migration-tools with four export subpaths: - ./types: MigrationManifest, MigrationOps, MigrationPackage, MigrationGraph - ./io: read/write migration packages, directory naming, collision handling - ./attestation: computeEdgeId, attestMigration, verifyMigration - ./dag: reconstructGraph, findLeaf, findPath, detectCycles, detectOrphans 55 unit tests covering all functionality. All existing tests pass. Co-authored-by: Cursor <[email protected]>
… codes Introduce MigrationToolsError with stable codes following ADR 027 NAMESPACE.SUBCODE convention (MIGRATION.DIR_EXISTS, MIGRATION.FILE_MISSING, etc.). Each error carries code, category, why, fix, and details for agent-friendly error handling. Register 7 new tooling-time codes in ADR 027 and document as RD-16 in spec. Co-authored-by: Cursor <[email protected]>
Rewrite M3 plan with concrete implementation details (file paths, option interfaces, step-by-step logic, error boundary patterns). Defer db update to follow-on project. Document that planContractDiff is the intended single diff engine — the introspection-based path should eventually convert to contract IR and feed through the same engine (RD-3). Remove "parity with introspection planner" framing from acceptance criteria in favor of correctness. Co-authored-by: Cursor <[email protected]>
Add `migration plan`, `migration verify`, and `migration new` CLI commands with config support, control plane integration, and tests. - Add migrations.dir to PrismaNextConfig - Wire planContractDiff through TargetMigrationsCapability and ControlClient to respect framework/sql layering - Implement migration-plan (offline contract diff, DAG leaf resolution, write migration package) - Implement migration-verify (recompute edgeId, attest drafts) - Implement migration-new (scaffold empty draft package) - Add unit and e2e tests for all three commands Co-authored-by: Cursor <[email protected]>
- Add migration apply (limited) to scope; remove from non-goals - Change RD-6 from abstract ops IR to direct SQL on disk - Update RD-5 rationale for contract-level diffing - Resolve all open questions (control plane wiring, draft vs attested, abstract ops vs SQL lowering) - Remove db update from scope, add to non-goals - Fix FR-8/FR-9 descriptions (were marked out of scope but are implemented) - Add FR-10 for migration apply - Add M4 (apply) and M5 (close-out) milestones to plan - Clean up stale TODOs and notes from EM discussion Co-authored-by: Cursor <[email protected]>
Add detailed task plan for replacing abstract ops IR with direct SQL lowering. Includes 5-phase breakdown (prep, emitter, planner, consumers, cleanup), SqlEmitter interface design for layering compliance, and complete file-level blast radius. Also cleans up spec (consolidate user flows, remove graph.index.json from FR-2, fix cosmetic blank line) and updates plan.md to reference the new task plan. Made-with: Cursor
|
Superseded by #184 — reduced scope, consolidated all milestones into a single PR. |
#184) Supersedes #179 closes [TML-1936](https://linear.app/prisma-company/issue/TML-1936) refs [TML-1937](https://linear.app/prisma-company/issue/TML-1937) refs [TML-1938](https://linear.app/prisma-company/issue/TML-1938) ## Summary End-to-end on-disk migration support: plan migrations offline, serialize them to disk, and apply them against a live database. - **Offline migration planning** (`migration plan`): Diffs two contracts without a DB connection. Uses `contractToSchemaIR()` to synthesize a `SqlSchemaIR` from the previous contract, then feeds it into the existing `PostgresMigrationPlanner` — no new planner needed. Supports additive, widening, and destructive operations. - **On-disk migration format**: `migration.json` + `ops.json` serialization, edge attestation (`computeEdgeId`, `attestMigration`, `verifyMigration`), DAG reconstruction with cycle/orphan detection. - **CLI commands**: - `migration plan` — offline diff → attested package - `migration apply` — read pending migrations from DAG, execute sequentially against a live DB via `ControlClient` - `migration verify` — re-attest / validate integrity - **Destructive change detection**: Hash-diff heuristic catches removals; the planner catches type changes and nullability tightening as conflicts. - **Migration apply**: Reads on-disk packages, determines pending migrations via DAG path from DB marker to leaf, executes each in its own transaction with full execution checks (prechecks, postchecks, idempotency). Resume-safe — re-run after failure picks up from the last successful migration. Warns when contract.json is stale (storageHash differs from DAG leaf). ## Architecture ``` contract.ts → emit → contract.json ↓ migration plan (offline): contractToSchemaIR(from) + planner.plan(to) ↓ migrations/<timestamp>_<name>/ ├── migration.json (manifest + edge attestation) └── ops.json (SQL operations) ↓ migration apply (online): read marker → find pending path → ControlClient.migrationApply() per edge ↓ DB updated, marker at new hash ``` ### Key implementation details (migration apply) - Routes through `ControlClient`, consistent with `db init` and `db update` - `origin: null` for first migration (runner expects no marker on fresh DB, not `EMPTY_CONTRACT_HASH`) - Destination contract validated via `familyInstance.validateContractIR()` before passing to runner - Framework components built from config for schema verification - One transaction per migration with all execution checks enabled - Policy-agnostic: passes all operation classes to the runner (policy gate is at plan time) - Stale-plan detection: warns when contract.json storageHash differs from DAG leaf ## Test plan - [x] Unit tests for `contractToSchemaIR` conversion (15 tests) - [x] Unit tests for `detectDestructiveChanges` (7 tests) - [x] Planner integration tests (9 tests) - [x] CLI command unit tests for migration-plan, migration-verify - [x] Migration apply unit tests — DAG path resolution (6 tests) - [x] Migration plan CLI e2e tests (7 tests) - [x] Migration apply CLI e2e tests against real Postgres (5 tests: single apply, idempotency, multi-migration, destructive, resume) - [x] Migration tools tests (attestation, DAG, I/O round-trips) - [x] NativeTypeExpander tests (with and without expander) - [x] `pnpm test:all` passes - [x] `pnpm lint:deps` clean - [x] `pnpm typecheck` clean <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * CLI: add migration commands — plan, show, status, verify, and apply for offline on-disk migrations * On-disk migrations: persistent migration packages with content-attested edge IDs and DAG-based chaining * Runtime API: read marker and apply migrations programmatically * **Documentation** * Comprehensive migration docs, ADRs, and user stories for on-disk workflow * **Tests** * Extensive unit and end-to-end tests covering planning, attestation, DAGs, verification, and apply flows * **Chores** * Added migrations config option and minor ignore-file updates <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Cursor <[email protected]> Co-authored-by: Will Madden <[email protected]>
closes TML-1936
Goal
Implement Milestone 1 of on-disk migrations: a pure, offline contract-to-contract diff planner that produces abstract migration operation IR. This is the foundation — M2 (persistence/DAG) and M3 (CLI commands) build on top.
The planner answers "what changed between schema A and schema B?" without a database connection. The existing introspection-based planner answers "what's different between the contract and the live DB?" — they serve different purposes.
Before / After
What changed and why
Abstract ops IR (
core-control-plane/abstract-ops): 8 operation types (enableExtension,createStorageType,createTable,addColumn,addPrimaryKey,addUniqueConstraint,createIndex,addForeignKey) with typed args, ADR 044 structured pre/post checks, andContractDiffResultunion. Lives in the framework domain since it's target-agnostic — any SQL target can resolve these to concrete DDL.Contract planner (
family-sql/contract-planner):planContractDiff()diffs twoSqlStoragestates and produces ops in deterministic order (extensions → types → tables → columns → PKs → uniques → indexes → FKs). Detects non-additive conflicts (type changes, column removal, nullability tightening) and returns structured failures. Extension detection via codec→extension mapping (pgvector).20 unit tests covering all op types, conflict cases, determinism, edge cases (NOT NULL with/without defaults, PK addition on existing tables, constraint name generation).
Spec and plan docs for the full 4-milestone project in
projects/on-disk-migrations/.Summary by CodeRabbit
Release Notes
New Features
Documentation