@prisma-next/target-postgres 0.1.0-dev.14 → 0.1.0-dev.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,42 +4,74 @@ Postgres target pack for Prisma Next.
4
4
 
5
5
  ## Package Classification
6
6
 
7
- - **Domain**: extensions
7
+ - **Domain**: targets
8
8
  - **Layer**: targets
9
9
  - **Plane**: multi-plane (migration, runtime)
10
10
 
11
11
  ## Purpose
12
12
 
13
- Provides the Postgres target descriptor (`TargetDescriptor`) for CLI config. The target descriptor includes the target manifest with capabilities and type information.
13
+ Provides the Postgres target descriptor (`SqlControlTargetDescriptor`) for CLI config. The target descriptor includes the target manifest with capabilities and type information, as well as factories for creating migration planners and runners.
14
14
 
15
15
  ## Responsibilities
16
16
 
17
- - **Target Descriptor Export**: Exports the Postgres `TargetDescriptor` for use in CLI configuration files
17
+ - **Target Descriptor Export**: Exports the Postgres `SqlControlTargetDescriptor` for use in CLI configuration files
18
18
  - **Manifest Loading**: Loads the Postgres target manifest from `packs/manifest.json` with capabilities and type information
19
- - **Multi-Plane Support**: Provides both migration-plane (CLI) and runtime-plane entry points for the Postgres target
20
- - **Planner Factory**: Implements the SQL family `SqlControlTargetDescriptor` extension so callers can request a Postgres-specific `MigrationPlanner`
19
+ - **Multi-Plane Support**: Provides both migration-plane (control) and runtime-plane entry points for the Postgres target
20
+ - **Planner Factory**: Implements `createPlanner()` to create Postgres-specific migration planners
21
+ - **Runner Factory**: Implements `createRunner()` to create Postgres-specific migration runners
21
22
 
22
23
  This package spans multiple planes:
23
- - **Migration plane** (`src/exports/cli.ts`): CLI entry point that exports `TargetDescriptor` for config files
24
+ - **Migration plane** (`src/exports/control.ts`): Control plane entry point that exports `SqlControlTargetDescriptor` for config files
24
25
  - **Runtime plane** (`src/exports/runtime.ts`): Runtime entry point for target-specific runtime code (future)
25
26
 
26
27
  ## Usage
27
28
 
28
- ### Migration Plane (CLI)
29
+ ### Control Plane (CLI)
29
30
 
30
31
  ```typescript
31
32
  import postgres from '@prisma-next/target-postgres/control';
33
+ import sqlFamilyDescriptor from '@prisma-next/family-sql/control';
34
+ import postgresAdapter from '@prisma-next/adapter-postgres/control';
35
+ import postgresDriver from '@prisma-next/driver-postgres/control';
32
36
 
33
- // postgres is a TargetDescriptor with:
37
+ // postgres is a SqlControlTargetDescriptor with:
34
38
  // - kind: 'target'
39
+ // - familyId: 'sql'
40
+ // - targetId: 'postgres'
35
41
  // - id: 'postgres'
36
- // - family: 'sql'
37
42
  // - manifest: ExtensionPackManifest
38
-
39
- // When paired with the SQL family, targets can expose planners
40
- const family = sqlFamilyDescriptor.create({ target: postgres, adapter, driver, extensions: [] });
43
+ // - createPlanner(): creates a Postgres migration planner
44
+ // - createRunner(): creates a Postgres migration runner
45
+
46
+ // Create family instance with target, adapter, and driver
47
+ const family = sqlFamilyDescriptor.create({
48
+ target: postgres,
49
+ adapter: postgresAdapter,
50
+ driver: postgresDriver,
51
+ extensions: [],
52
+ });
53
+
54
+ // Create planner and runner from target descriptor
41
55
  const planner = postgres.createPlanner(family);
56
+ const runner = postgres.createRunner(family);
57
+
58
+ // Plan and execute migrations
42
59
  const planResult = planner.plan({ contract, schema, policy });
60
+ if (planResult.kind === 'success') {
61
+ const executeResult = await runner.execute({
62
+ plan: planResult.plan,
63
+ driver,
64
+ destinationContract: contract,
65
+ policy,
66
+ });
67
+ if (!executeResult.ok) {
68
+ // Handle structured failure (e.g., EXECUTION_FAILED, PRECHECK_FAILED)
69
+ console.error(executeResult.failure.code, executeResult.failure.summary);
70
+ }
71
+ } else {
72
+ // Handle planner failure (e.g., unsupportedExtension, unsupportedOperation)
73
+ console.error(planResult.conflicts);
74
+ }
43
75
  ```
44
76
 
45
77
  ### Runtime Plane
@@ -51,11 +83,29 @@ import { ... } from '@prisma-next/target-postgres/runtime';
51
83
 
52
84
  ## Architecture
53
85
 
54
- This package provides both CLI and runtime entry points for the Postgres target. The CLI entry point loads the target manifest from `packs/manifest.json` and exports it as a `TargetDescriptor`. The runtime entry point will provide target-specific runtime functionality in the future.
86
+ This package provides both control and runtime entry points for the Postgres target. The control entry point loads the target manifest from `packs/manifest.json` and exports it as a `SqlControlTargetDescriptor`. The runtime entry point will provide target-specific runtime functionality in the future.
87
+
88
+ ## Error Handling
89
+
90
+ Both the planner and runner return structured results instead of throwing:
91
+
92
+ **Planner** returns `PlannerResult` with either:
93
+ - `kind: 'success'` with a `MigrationPlan`
94
+ - `kind: 'failure'` with a list of `PlannerConflict` objects (e.g., `unsupportedExtension`, `unsupportedOperation`)
95
+
96
+ **Runner** returns `MigrationRunnerResult` (`Result<MigrationRunnerSuccessValue, MigrationRunnerFailure>`) with either:
97
+ - `ok: true` with operation counts
98
+ - `ok: false` with a `MigrationRunnerFailure` containing error code, summary, and metadata
99
+
100
+ Runner error codes include: `EXECUTION_FAILED`, `PRECHECK_FAILED`, `POSTCHECK_FAILED`, `SCHEMA_VERIFY_FAILED`, `POLICY_VIOLATION`, `MARKER_ORIGIN_MISMATCH`, `DESTINATION_CONTRACT_MISMATCH`.
101
+
102
+ See `@prisma-next/family-sql/control` README for full error code documentation.
55
103
 
56
104
  ## Dependencies
57
105
 
58
- - **`@prisma-next/cli`**: CLI descriptor types (`TargetDescriptor`, `ExtensionPackManifest`)
106
+ - **`@prisma-next/family-sql`**: SQL family types (`SqlControlTargetDescriptor`, `SqlControlFamilyInstance`)
107
+ - **`@prisma-next/core-control-plane`**: Control plane types (`ControlTargetInstance`)
108
+ - **`@prisma-next/contract`**: Manifest types (`ExtensionPackManifest`)
59
109
  - **`arktype`**: Runtime validation
60
110
 
61
111
  **Dependents:**
@@ -63,6 +113,18 @@ This package provides both CLI and runtime entry points for the Postgres target.
63
113
 
64
114
  ## Exports
65
115
 
66
- - `./cli`: Migration entry point for `TargetDescriptor`
116
+ - `./control`: Control plane entry point for `SqlControlTargetDescriptor`
67
117
  - `./runtime`: Runtime entry point for target-specific runtime code (future)
68
118
 
119
+ ## Tests
120
+
121
+ This package ships a mix of fast planner unit tests and slower runner integration tests that require a dev Postgres instance (via `@prisma/dev`).
122
+
123
+ - **Default (`pnpm --filter @prisma-next/target-postgres test`)**: runs all tests including integration tests
124
+ - **Test files**:
125
+ - `test/migrations/planner.case1.test.ts`: Planner unit tests
126
+ - `test/migrations/runner.*.integration.test.ts`: Runner integration tests (basic, errors, idempotency, policy)
127
+
128
+ ```bash
129
+ pnpm --filter @prisma-next/target-postgres test
130
+ ```
@@ -43,6 +43,10 @@ var PostgresMigrationPlanner = class {
43
43
  }
44
44
  ]);
45
45
  }
46
+ const extensionResult = this.validateExtensions(options.contract);
47
+ if (extensionResult) {
48
+ return extensionResult;
49
+ }
46
50
  const operations = [];
47
51
  operations.push(
48
52
  ...this.buildExtensionOperations(options.contract, schemaName),
@@ -53,8 +57,8 @@ var PostgresMigrationPlanner = class {
53
57
  );
54
58
  const plan = createMigrationPlan({
55
59
  targetId: "postgres",
56
- policy: options.policy,
57
- contract: {
60
+ origin: null,
61
+ destination: {
58
62
  coreHash: options.contract.coreHash,
59
63
  ...options.contract.profileHash ? { profileHash: options.contract.profileHash } : {}
60
64
  },
@@ -62,6 +66,26 @@ var PostgresMigrationPlanner = class {
62
66
  });
63
67
  return plannerSuccess(plan);
64
68
  }
69
+ validateExtensions(contract) {
70
+ const extensions = contract.extensions ?? {};
71
+ const extensionNames = Object.keys(extensions);
72
+ const unsupportedExtensions = extensionNames.filter(
73
+ (extensionName) => !PG_EXTENSION_SQL[extensionName]
74
+ );
75
+ if (unsupportedExtensions.length > 0) {
76
+ const supportedExtensions = Object.keys(PG_EXTENSION_SQL).join(", ");
77
+ const unsupportedList = unsupportedExtensions.join(", ");
78
+ return plannerFailure([
79
+ {
80
+ kind: "unsupportedExtension",
81
+ summary: `Unsupported PostgreSQL extensions in contract: ${unsupportedList}`,
82
+ why: `The Postgres migration planner currently only supports: ${supportedExtensions}. Extensions are defined in contract.extensions.`,
83
+ location: { extension: unsupportedList }
84
+ }
85
+ ]);
86
+ }
87
+ return null;
88
+ }
65
89
  ensureAdditivePolicy(policy) {
66
90
  if (!policy.allowedOperationClasses.includes("additive")) {
67
91
  return plannerFailure([
@@ -78,16 +102,6 @@ var PostgresMigrationPlanner = class {
78
102
  const extensions = contract.extensions ?? {};
79
103
  const extensionNames = Object.keys(extensions);
80
104
  const operations = [];
81
- const unsupportedExtensions = extensionNames.filter(
82
- (extensionName) => !PG_EXTENSION_SQL[extensionName]
83
- );
84
- if (unsupportedExtensions.length > 0) {
85
- const supportedExtensions = Object.keys(PG_EXTENSION_SQL).join(", ");
86
- const unsupportedList = unsupportedExtensions.join(", ");
87
- throw new Error(
88
- `Unsupported PostgreSQL extensions in contract: ${unsupportedList}. The Postgres migration planner currently only supports the following extensions: ${supportedExtensions}. Extensions are defined in contract.extensions.`
89
- );
90
- }
91
105
  for (const extensionName of extensionNames) {
92
106
  const sql = PG_EXTENSION_SQL[extensionName];
93
107
  if (!sql) {
@@ -347,6 +361,527 @@ function constraintExistsCheck({
347
361
  )`;
348
362
  }
349
363
 
364
+ // src/core/migrations/runner.ts
365
+ import { ok, okVoid } from "@prisma-next/core-control-plane/result";
366
+ import { runnerFailure, runnerSuccess } from "@prisma-next/family-sql/control";
367
+ import { readMarker } from "@prisma-next/family-sql/verify";
368
+
369
+ // src/core/migrations/statement-builders.ts
370
+ var ensurePrismaContractSchemaStatement = {
371
+ sql: "create schema if not exists prisma_contract",
372
+ params: []
373
+ };
374
+ var ensureMarkerTableStatement = {
375
+ sql: `create table if not exists prisma_contract.marker (
376
+ id smallint primary key default 1,
377
+ core_hash text not null,
378
+ profile_hash text not null,
379
+ contract_json jsonb,
380
+ canonical_version int,
381
+ updated_at timestamptz not null default now(),
382
+ app_tag text,
383
+ meta jsonb not null default '{}'
384
+ )`,
385
+ params: []
386
+ };
387
+ var ensureLedgerTableStatement = {
388
+ sql: `create table if not exists prisma_contract.ledger (
389
+ id bigserial primary key,
390
+ created_at timestamptz not null default now(),
391
+ origin_core_hash text,
392
+ origin_profile_hash text,
393
+ destination_core_hash text not null,
394
+ destination_profile_hash text,
395
+ contract_json_before jsonb,
396
+ contract_json_after jsonb,
397
+ operations jsonb not null
398
+ )`,
399
+ params: []
400
+ };
401
+ function buildWriteMarkerStatements(input) {
402
+ const params = [
403
+ 1,
404
+ input.coreHash,
405
+ input.profileHash,
406
+ jsonParam(input.contractJson),
407
+ input.canonicalVersion ?? null,
408
+ input.appTag ?? null,
409
+ jsonParam(input.meta ?? {})
410
+ ];
411
+ return {
412
+ insert: {
413
+ sql: `insert into prisma_contract.marker (
414
+ id,
415
+ core_hash,
416
+ profile_hash,
417
+ contract_json,
418
+ canonical_version,
419
+ updated_at,
420
+ app_tag,
421
+ meta
422
+ ) values (
423
+ $1,
424
+ $2,
425
+ $3,
426
+ $4::jsonb,
427
+ $5,
428
+ now(),
429
+ $6,
430
+ $7::jsonb
431
+ )`,
432
+ params
433
+ },
434
+ update: {
435
+ sql: `update prisma_contract.marker set
436
+ core_hash = $2,
437
+ profile_hash = $3,
438
+ contract_json = $4::jsonb,
439
+ canonical_version = $5,
440
+ updated_at = now(),
441
+ app_tag = $6,
442
+ meta = $7::jsonb
443
+ where id = $1`,
444
+ params
445
+ }
446
+ };
447
+ }
448
+ function buildLedgerInsertStatement(input) {
449
+ return {
450
+ sql: `insert into prisma_contract.ledger (
451
+ origin_core_hash,
452
+ origin_profile_hash,
453
+ destination_core_hash,
454
+ destination_profile_hash,
455
+ contract_json_before,
456
+ contract_json_after,
457
+ operations
458
+ ) values (
459
+ $1,
460
+ $2,
461
+ $3,
462
+ $4,
463
+ $5::jsonb,
464
+ $6::jsonb,
465
+ $7::jsonb
466
+ )`,
467
+ params: [
468
+ input.originCoreHash ?? null,
469
+ input.originProfileHash ?? null,
470
+ input.destinationCoreHash,
471
+ input.destinationProfileHash ?? null,
472
+ jsonParam(input.contractJsonBefore),
473
+ jsonParam(input.contractJsonAfter),
474
+ jsonParam(input.operations)
475
+ ]
476
+ };
477
+ }
478
+ function jsonParam(value) {
479
+ return JSON.stringify(value ?? null);
480
+ }
481
+
482
+ // src/core/migrations/runner.ts
483
+ var DEFAULT_CONFIG = {
484
+ defaultSchema: "public"
485
+ };
486
+ var LOCK_DOMAIN = "prisma_next.contract.marker";
487
+ function cloneAndFreezeRecord(value) {
488
+ const cloned = {};
489
+ for (const [key, val] of Object.entries(value)) {
490
+ if (val === null || val === void 0) {
491
+ cloned[key] = val;
492
+ } else if (Array.isArray(val)) {
493
+ cloned[key] = Object.freeze([...val]);
494
+ } else if (typeof val === "object") {
495
+ cloned[key] = cloneAndFreezeRecord(val);
496
+ } else {
497
+ cloned[key] = val;
498
+ }
499
+ }
500
+ return Object.freeze(cloned);
501
+ }
502
+ function createPostgresMigrationRunner(family, config = {}) {
503
+ return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });
504
+ }
505
+ var PostgresMigrationRunner = class {
506
+ constructor(family, config) {
507
+ this.family = family;
508
+ this.config = config;
509
+ }
510
+ async execute(options) {
511
+ const schema = options.schemaName ?? this.config.defaultSchema;
512
+ const driver = options.driver;
513
+ const lockKey = `${LOCK_DOMAIN}:${schema}`;
514
+ const destinationCheck = this.ensurePlanMatchesDestinationContract(
515
+ options.plan.destination,
516
+ options.destinationContract
517
+ );
518
+ if (!destinationCheck.ok) {
519
+ return destinationCheck;
520
+ }
521
+ const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);
522
+ if (!policyCheck.ok) {
523
+ return policyCheck;
524
+ }
525
+ await this.beginTransaction(driver);
526
+ let committed = false;
527
+ try {
528
+ await this.acquireLock(driver, lockKey);
529
+ await this.ensureControlTables(driver);
530
+ const existingMarker = await readMarker(driver);
531
+ const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);
532
+ if (!markerCheck.ok) {
533
+ return markerCheck;
534
+ }
535
+ const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);
536
+ let applyValue;
537
+ if (markerAtDestination) {
538
+ applyValue = { operationsExecuted: 0, executedOperations: [] };
539
+ } else {
540
+ const applyResult = await this.applyPlan(driver, options);
541
+ if (!applyResult.ok) {
542
+ return applyResult;
543
+ }
544
+ applyValue = applyResult.value;
545
+ }
546
+ const schemaVerifyOptions = {
547
+ driver,
548
+ contractIR: options.destinationContract,
549
+ strict: options.strictVerification ?? true,
550
+ context: options.context ?? {}
551
+ };
552
+ const schemaVerifyResult = await this.family.schemaVerify(schemaVerifyOptions);
553
+ if (!schemaVerifyResult.ok) {
554
+ return runnerFailure("SCHEMA_VERIFY_FAILED", schemaVerifyResult.summary, {
555
+ why: "The resulting database schema does not satisfy the destination contract.",
556
+ meta: {
557
+ issues: schemaVerifyResult.schema.issues
558
+ }
559
+ });
560
+ }
561
+ await this.upsertMarker(driver, options, existingMarker);
562
+ await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);
563
+ await this.commitTransaction(driver);
564
+ committed = true;
565
+ return runnerSuccess({
566
+ operationsPlanned: options.plan.operations.length,
567
+ operationsExecuted: applyValue.operationsExecuted
568
+ });
569
+ } finally {
570
+ if (!committed) {
571
+ await this.rollbackTransaction(driver);
572
+ }
573
+ }
574
+ }
575
+ async applyPlan(driver, options) {
576
+ let operationsExecuted = 0;
577
+ const executedOperations = [];
578
+ for (const operation of options.plan.operations) {
579
+ options.callbacks?.onOperationStart?.(operation);
580
+ try {
581
+ const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(
582
+ driver,
583
+ operation.postcheck
584
+ );
585
+ if (postcheckAlreadySatisfied) {
586
+ executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));
587
+ continue;
588
+ }
589
+ const precheckResult = await this.runExpectationSteps(
590
+ driver,
591
+ operation.precheck,
592
+ operation,
593
+ "precheck"
594
+ );
595
+ if (!precheckResult.ok) {
596
+ return precheckResult;
597
+ }
598
+ const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);
599
+ if (!executeResult.ok) {
600
+ return executeResult;
601
+ }
602
+ const postcheckResult = await this.runExpectationSteps(
603
+ driver,
604
+ operation.postcheck,
605
+ operation,
606
+ "postcheck"
607
+ );
608
+ if (!postcheckResult.ok) {
609
+ return postcheckResult;
610
+ }
611
+ executedOperations.push(operation);
612
+ operationsExecuted += 1;
613
+ } finally {
614
+ options.callbacks?.onOperationComplete?.(operation);
615
+ }
616
+ }
617
+ return ok({ operationsExecuted, executedOperations });
618
+ }
619
+ async ensureControlTables(driver) {
620
+ await this.executeStatement(driver, ensurePrismaContractSchemaStatement);
621
+ await this.executeStatement(driver, ensureMarkerTableStatement);
622
+ await this.executeStatement(driver, ensureLedgerTableStatement);
623
+ }
624
+ async runExpectationSteps(driver, steps, operation, phase) {
625
+ for (const step of steps) {
626
+ const result = await driver.query(step.sql);
627
+ if (!this.stepResultIsTrue(result.rows)) {
628
+ const code = phase === "precheck" ? "PRECHECK_FAILED" : "POSTCHECK_FAILED";
629
+ return runnerFailure(
630
+ code,
631
+ `Operation ${operation.id} failed during ${phase}: ${step.description}`,
632
+ {
633
+ meta: {
634
+ operationId: operation.id,
635
+ phase,
636
+ stepDescription: step.description
637
+ }
638
+ }
639
+ );
640
+ }
641
+ }
642
+ return okVoid();
643
+ }
644
+ async runExecuteSteps(driver, steps, operation) {
645
+ for (const step of steps) {
646
+ try {
647
+ await driver.query(step.sql);
648
+ } catch (error) {
649
+ return runnerFailure(
650
+ "EXECUTION_FAILED",
651
+ `Operation ${operation.id} failed during execution: ${step.description}`,
652
+ {
653
+ why: error instanceof Error ? error.message : String(error),
654
+ meta: {
655
+ operationId: operation.id,
656
+ stepDescription: step.description,
657
+ sql: step.sql
658
+ }
659
+ }
660
+ );
661
+ }
662
+ }
663
+ return okVoid();
664
+ }
665
+ stepResultIsTrue(rows) {
666
+ if (!rows || rows.length === 0) {
667
+ return false;
668
+ }
669
+ const firstRow = rows[0];
670
+ const firstValue = firstRow ? Object.values(firstRow)[0] : void 0;
671
+ if (typeof firstValue === "boolean") {
672
+ return firstValue;
673
+ }
674
+ if (typeof firstValue === "number") {
675
+ return firstValue !== 0;
676
+ }
677
+ if (typeof firstValue === "string") {
678
+ const lower = firstValue.toLowerCase();
679
+ if (lower === "t" || lower === "true" || lower === "1") {
680
+ return true;
681
+ }
682
+ if (lower === "f" || lower === "false" || lower === "0") {
683
+ return false;
684
+ }
685
+ return firstValue.length > 0;
686
+ }
687
+ return Boolean(firstValue);
688
+ }
689
+ async expectationsAreSatisfied(driver, steps) {
690
+ if (steps.length === 0) {
691
+ return false;
692
+ }
693
+ for (const step of steps) {
694
+ const result = await driver.query(step.sql);
695
+ if (!this.stepResultIsTrue(result.rows)) {
696
+ return false;
697
+ }
698
+ }
699
+ return true;
700
+ }
701
+ createPostcheckPreSatisfiedSkipRecord(operation) {
702
+ const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : void 0;
703
+ const runnerMeta = Object.freeze({
704
+ skipped: true,
705
+ reason: "postcheck_pre_satisfied"
706
+ });
707
+ const mergedMeta = Object.freeze({
708
+ ...clonedMeta ?? {},
709
+ runner: runnerMeta
710
+ });
711
+ const frozenPostcheck = Object.freeze([...operation.postcheck]);
712
+ return Object.freeze({
713
+ id: operation.id,
714
+ label: operation.label,
715
+ ...operation.summary ? { summary: operation.summary } : {},
716
+ operationClass: operation.operationClass,
717
+ target: operation.target,
718
+ // Already frozen from plan creation
719
+ precheck: Object.freeze([]),
720
+ execute: Object.freeze([]),
721
+ postcheck: frozenPostcheck,
722
+ ...operation.meta || mergedMeta ? { meta: mergedMeta } : {}
723
+ });
724
+ }
725
+ markerMatchesDestination(marker, plan) {
726
+ if (!marker) {
727
+ return false;
728
+ }
729
+ if (marker.coreHash !== plan.destination.coreHash) {
730
+ return false;
731
+ }
732
+ if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {
733
+ return false;
734
+ }
735
+ return true;
736
+ }
737
+ enforcePolicyCompatibility(policy, operations) {
738
+ const allowedClasses = new Set(policy.allowedOperationClasses);
739
+ for (const operation of operations) {
740
+ if (!allowedClasses.has(operation.operationClass)) {
741
+ return runnerFailure(
742
+ "POLICY_VIOLATION",
743
+ `Operation ${operation.id} has class "${operation.operationClass}" which is not allowed by policy.`,
744
+ {
745
+ why: `Policy only allows: ${policy.allowedOperationClasses.join(", ")}.`,
746
+ meta: {
747
+ operationId: operation.id,
748
+ operationClass: operation.operationClass,
749
+ allowedClasses: policy.allowedOperationClasses
750
+ }
751
+ }
752
+ );
753
+ }
754
+ }
755
+ return okVoid();
756
+ }
757
+ ensureMarkerCompatibility(marker, plan) {
758
+ const origin = plan.origin ?? null;
759
+ if (!origin) {
760
+ if (!marker) {
761
+ return okVoid();
762
+ }
763
+ if (this.markerMatchesDestination(marker, plan)) {
764
+ return okVoid();
765
+ }
766
+ return runnerFailure(
767
+ "MARKER_ORIGIN_MISMATCH",
768
+ `Existing contract marker (${marker.coreHash}) does not match plan origin (no marker expected).`,
769
+ {
770
+ meta: {
771
+ markerCoreHash: marker.coreHash,
772
+ expectedOrigin: null
773
+ }
774
+ }
775
+ );
776
+ }
777
+ if (!marker) {
778
+ return runnerFailure(
779
+ "MARKER_ORIGIN_MISMATCH",
780
+ `Missing contract marker: expected origin core hash ${origin.coreHash}.`,
781
+ {
782
+ meta: {
783
+ expectedOriginCoreHash: origin.coreHash
784
+ }
785
+ }
786
+ );
787
+ }
788
+ if (marker.coreHash !== origin.coreHash) {
789
+ return runnerFailure(
790
+ "MARKER_ORIGIN_MISMATCH",
791
+ `Existing contract marker (${marker.coreHash}) does not match plan origin (${origin.coreHash}).`,
792
+ {
793
+ meta: {
794
+ markerCoreHash: marker.coreHash,
795
+ expectedOriginCoreHash: origin.coreHash
796
+ }
797
+ }
798
+ );
799
+ }
800
+ if (origin.profileHash && marker.profileHash !== origin.profileHash) {
801
+ return runnerFailure(
802
+ "MARKER_ORIGIN_MISMATCH",
803
+ `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`,
804
+ {
805
+ meta: {
806
+ markerProfileHash: marker.profileHash,
807
+ expectedOriginProfileHash: origin.profileHash
808
+ }
809
+ }
810
+ );
811
+ }
812
+ return okVoid();
813
+ }
814
+ ensurePlanMatchesDestinationContract(destination, contract) {
815
+ if (destination.coreHash !== contract.coreHash) {
816
+ return runnerFailure(
817
+ "DESTINATION_CONTRACT_MISMATCH",
818
+ `Plan destination core hash (${destination.coreHash}) does not match provided contract core hash (${contract.coreHash}).`,
819
+ {
820
+ meta: {
821
+ planCoreHash: destination.coreHash,
822
+ contractCoreHash: contract.coreHash
823
+ }
824
+ }
825
+ );
826
+ }
827
+ if (destination.profileHash && contract.profileHash && destination.profileHash !== contract.profileHash) {
828
+ return runnerFailure(
829
+ "DESTINATION_CONTRACT_MISMATCH",
830
+ `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`,
831
+ {
832
+ meta: {
833
+ planProfileHash: destination.profileHash,
834
+ contractProfileHash: contract.profileHash
835
+ }
836
+ }
837
+ );
838
+ }
839
+ return okVoid();
840
+ }
841
+ async upsertMarker(driver, options, existingMarker) {
842
+ const writeStatements = buildWriteMarkerStatements({
843
+ coreHash: options.plan.destination.coreHash,
844
+ profileHash: options.plan.destination.profileHash ?? options.destinationContract.profileHash ?? options.plan.destination.coreHash,
845
+ contractJson: options.destinationContract,
846
+ canonicalVersion: null,
847
+ meta: {}
848
+ });
849
+ const statement = existingMarker ? writeStatements.update : writeStatements.insert;
850
+ await this.executeStatement(driver, statement);
851
+ }
852
+ async recordLedgerEntry(driver, options, existingMarker, executedOperations) {
853
+ const ledgerStatement = buildLedgerInsertStatement({
854
+ originCoreHash: existingMarker?.coreHash ?? null,
855
+ originProfileHash: existingMarker?.profileHash ?? null,
856
+ destinationCoreHash: options.plan.destination.coreHash,
857
+ destinationProfileHash: options.plan.destination.profileHash ?? options.destinationContract.profileHash ?? options.plan.destination.coreHash,
858
+ contractJsonBefore: existingMarker?.contractJson ?? null,
859
+ contractJsonAfter: options.destinationContract,
860
+ operations: executedOperations
861
+ });
862
+ await this.executeStatement(driver, ledgerStatement);
863
+ }
864
+ async acquireLock(driver, key) {
865
+ await driver.query("select pg_advisory_xact_lock(hashtext($1))", [key]);
866
+ }
867
+ async beginTransaction(driver) {
868
+ await driver.query("BEGIN");
869
+ }
870
+ async commitTransaction(driver) {
871
+ await driver.query("COMMIT");
872
+ }
873
+ async rollbackTransaction(driver) {
874
+ await driver.query("ROLLBACK");
875
+ }
876
+ async executeStatement(driver, statement) {
877
+ if (statement.params.length > 0) {
878
+ await driver.query(statement.sql, statement.params);
879
+ return;
880
+ }
881
+ await driver.query(statement.sql);
882
+ }
883
+ };
884
+
350
885
  // src/exports/control.ts
351
886
  var __filename = fileURLToPath(import.meta.url);
352
887
  var __dirname = dirname(__filename);
@@ -394,6 +929,9 @@ var postgresTargetDescriptor = {
394
929
  },
395
930
  createPlanner(_family) {
396
931
  return createPostgresMigrationPlanner();
932
+ },
933
+ createRunner(family) {
934
+ return createPostgresMigrationRunner(family);
397
935
  }
398
936
  };
399
937
  var control_default = postgresTargetDescriptor;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/exports/control.ts","../../src/core/migrations/planner.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ExtensionPackManifest } from '@prisma-next/contract/pack-manifest-types';\nimport type { ControlTargetInstance } from '@prisma-next/core-control-plane/types';\nimport type {\n SqlControlFamilyInstance,\n SqlControlTargetDescriptor,\n} from '@prisma-next/family-sql/control';\nimport { type } from 'arktype';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nconst TypesImportSpecSchema = type({\n package: 'string',\n named: 'string',\n alias: 'string',\n});\n\nconst ExtensionPackManifestSchema = type({\n id: 'string',\n version: 'string',\n 'targets?': type({ '[string]': type({ 'minVersion?': 'string' }) }),\n 'capabilities?': 'Record<string, unknown>',\n 'types?': type({\n 'codecTypes?': type({\n import: TypesImportSpecSchema,\n }),\n 'operationTypes?': type({\n import: TypesImportSpecSchema,\n }),\n }),\n 'operations?': 'unknown[]',\n});\n\n/**\n * Loads the target manifest from packs/manifest.json.\n */\nfunction loadTargetManifest(): ExtensionPackManifest {\n const manifestPath = join(__dirname, '../../packs/manifest.json');\n const manifestJson = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n\n const result = ExtensionPackManifestSchema(manifestJson);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Invalid target manifest structure at ${manifestPath}: ${messages}`);\n }\n\n return result as ExtensionPackManifest;\n}\n\n/**\n * Postgres target descriptor for CLI config.\n */\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n kind: 'target',\n familyId: 'sql',\n targetId: 'postgres',\n id: 'postgres',\n manifest: loadTargetManifest(),\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n };\n\nexport default postgresTargetDescriptor;\n","import type {\n MigrationPlanner,\n MigrationPlannerPlanOptions,\n MigrationPlanOperation,\n MigrationPolicy,\n} from '@prisma-next/family-sql/control';\nimport {\n createMigrationPlan,\n plannerFailure,\n plannerSuccess,\n} from '@prisma-next/family-sql/control';\nimport type {\n SqlContract,\n SqlStorage,\n StorageColumn,\n StorageTable,\n} from '@prisma-next/sql-contract/types';\n\ntype OperationClass = 'extension' | 'table' | 'unique' | 'index' | 'foreignKey';\n\nexport interface PostgresPlanTargetDetails {\n readonly schema: string;\n readonly objectType: OperationClass;\n readonly name: string;\n readonly table?: string;\n}\n\ninterface PlannerConfig {\n readonly defaultSchema: string;\n}\n\nconst DEFAULT_PLANNER_CONFIG: PlannerConfig = {\n defaultSchema: 'public',\n};\n\nconst PG_EXTENSION_SQL: Record<string, string> = {\n pgvector: 'CREATE EXTENSION IF NOT EXISTS vector',\n};\n\nexport function createPostgresMigrationPlanner(\n config: Partial<PlannerConfig> = {},\n): MigrationPlanner<PostgresPlanTargetDetails> {\n return new PostgresMigrationPlanner({\n ...DEFAULT_PLANNER_CONFIG,\n ...config,\n });\n}\n\nclass PostgresMigrationPlanner implements MigrationPlanner<PostgresPlanTargetDetails> {\n constructor(private readonly config: PlannerConfig) {}\n\n plan(options: MigrationPlannerPlanOptions) {\n const schemaName = options.schemaName ?? this.config.defaultSchema;\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) {\n return policyResult;\n }\n\n const existingTables = Object.keys(options.schema.tables);\n if (existingTables.length > 0) {\n const tableList = existingTables.sort().join(', ');\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: `The Postgres migration planner currently supports only empty databases. Found ${existingTables.length} existing table(s): ${tableList}`,\n why: 'Remove existing tables or use a future planner mode that handles subsets/supersets.',\n },\n ]);\n }\n\n const operations: MigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n\n operations.push(\n ...this.buildExtensionOperations(options.contract, schemaName),\n ...this.buildTableOperations(options.contract.storage.tables, schemaName),\n ...this.buildUniqueOperations(options.contract.storage.tables, schemaName),\n ...this.buildIndexOperations(options.contract.storage.tables, schemaName),\n ...this.buildForeignKeyOperations(options.contract.storage.tables, schemaName),\n );\n\n const plan = createMigrationPlan<PostgresPlanTargetDetails>({\n targetId: 'postgres',\n policy: options.policy,\n contract: {\n coreHash: options.contract.coreHash,\n ...(options.contract.profileHash ? { profileHash: options.contract.profileHash } : {}),\n },\n operations,\n });\n\n return plannerSuccess(plan);\n }\n\n private ensureAdditivePolicy(policy: MigrationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Init planner requires additive operations be allowed',\n why: 'The init planner only emits additive operations. Update the policy to include \"additive\".',\n },\n ]);\n }\n return null;\n }\n\n private buildExtensionOperations(\n contract: SqlContract<SqlStorage>,\n schema: string,\n ): readonly MigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const extensions = contract.extensions ?? {};\n const extensionNames = Object.keys(extensions);\n const operations: MigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n\n // Check for unsupported extensions and fail fast\n const unsupportedExtensions = extensionNames.filter(\n (extensionName) => !PG_EXTENSION_SQL[extensionName],\n );\n if (unsupportedExtensions.length > 0) {\n const supportedExtensions = Object.keys(PG_EXTENSION_SQL).join(', ');\n const unsupportedList = unsupportedExtensions.join(', ');\n throw new Error(\n `Unsupported PostgreSQL extensions in contract: ${unsupportedList}. ` +\n `The Postgres migration planner currently only supports the following extensions: ${supportedExtensions}. ` +\n 'Extensions are defined in contract.extensions.',\n );\n }\n\n for (const extensionName of extensionNames) {\n const sql = PG_EXTENSION_SQL[extensionName];\n if (!sql) {\n // This should never happen since we validate extensions above, but TypeScript requires this check\n throw new Error(`Extension SQL not found for ${extensionName}`);\n }\n const details = this.buildTargetDetails('extension', extensionName, schema);\n operations.push({\n id: `extension.${extensionName}`,\n label: `Enable extension \"${extensionName}\"`,\n summary: `Ensures the ${extensionName} extension is available`,\n operationClass: 'additive',\n target: { id: 'postgres', details },\n precheck: [\n {\n description: `verify extension \"${extensionName}\" is not already enabled`,\n sql: `SELECT NOT EXISTS (SELECT 1 FROM pg_extension WHERE extname = '${escapeLiteral(\n this.extensionDatabaseName(extensionName),\n )}')`,\n },\n ],\n execute: [\n {\n description: `create extension \"${extensionName}\"`,\n sql,\n },\n ],\n postcheck: [\n {\n description: `confirm extension \"${extensionName}\" is enabled`,\n sql: `SELECT EXISTS (SELECT 1 FROM pg_extension WHERE extname = '${escapeLiteral(\n this.extensionDatabaseName(extensionName),\n )}')`,\n },\n ],\n });\n }\n\n return operations;\n }\n\n private extensionDatabaseName(extensionName: string): string {\n if (extensionName === 'pgvector') {\n return 'vector';\n }\n return extensionName;\n }\n\n private buildTableOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: string,\n ): readonly MigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: MigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n const qualified = qualifyTableName(schema, tableName);\n operations.push({\n id: `table.${tableName}`,\n label: `Create table ${tableName}`,\n summary: `Creates table ${tableName} with required columns`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schema),\n },\n precheck: [\n {\n description: `ensure table \"${tableName}\" does not exist`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schema, tableName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create table \"${tableName}\"`,\n sql: buildCreateTableSql(qualified, table),\n },\n ],\n postcheck: [\n {\n description: `verify table \"${tableName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schema, tableName)}) IS NOT NULL`,\n },\n ],\n });\n }\n return operations;\n }\n\n private buildUniqueOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: string,\n ): readonly MigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: MigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n for (const unique of table.uniques) {\n const constraintName = unique.name ?? `${tableName}_${unique.columns.join('_')}_key`;\n operations.push({\n id: `unique.${tableName}.${constraintName}`,\n label: `Add unique constraint ${constraintName} on ${tableName}`,\n summary: `Adds unique constraint ${constraintName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('unique', constraintName, schema, tableName),\n },\n precheck: [\n {\n description: `ensure unique constraint \"${constraintName}\" is missing`,\n sql: constraintExistsCheck({ constraintName, schema, exists: false }),\n },\n ],\n execute: [\n {\n description: `add unique constraint \"${constraintName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schema, tableName)}\nADD CONSTRAINT ${quoteIdentifier(constraintName)}\nUNIQUE (${unique.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify unique constraint \"${constraintName}\" exists`,\n sql: constraintExistsCheck({ constraintName, schema }),\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildIndexOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: string,\n ): readonly MigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: MigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n for (const index of table.indexes) {\n const indexName = index.name ?? `${tableName}_${index.columns.join('_')}_idx`;\n operations.push({\n id: `index.${tableName}.${indexName}`,\n label: `Create index ${indexName} on ${tableName}`,\n summary: `Creates index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('index', indexName, schema, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" is missing`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schema, indexName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create index \"${indexName}\"`,\n sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(\n schema,\n tableName,\n )} (${index.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schema, indexName)}) IS NOT NULL`,\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildForeignKeyOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: string,\n ): readonly MigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: MigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n for (const foreignKey of table.foreignKeys) {\n const fkName = foreignKey.name ?? `${tableName}_${foreignKey.columns.join('_')}_fkey`;\n operations.push({\n id: `foreignKey.${tableName}.${fkName}`,\n label: `Add foreign key ${fkName} on ${tableName}`,\n summary: `Adds foreign key ${fkName} referencing ${foreignKey.references.table}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('foreignKey', fkName, schema, tableName),\n },\n precheck: [\n {\n description: `ensure foreign key \"${fkName}\" is missing`,\n sql: constraintExistsCheck({ constraintName: fkName, schema, exists: false }),\n },\n ],\n execute: [\n {\n description: `add foreign key \"${fkName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schema, tableName)}\nADD CONSTRAINT ${quoteIdentifier(fkName)}\nFOREIGN KEY (${foreignKey.columns.map(quoteIdentifier).join(', ')})\nREFERENCES ${qualifyTableName(schema, foreignKey.references.table)} (${foreignKey.references.columns\n .map(quoteIdentifier)\n .join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify foreign key \"${fkName}\" exists`,\n sql: constraintExistsCheck({ constraintName: fkName, schema }),\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildTargetDetails(\n objectType: OperationClass,\n name: string,\n schema: string,\n table?: string,\n ): PostgresPlanTargetDetails {\n return {\n schema,\n objectType,\n name,\n ...(table ? { table } : {}),\n };\n }\n}\n\nfunction buildCreateTableSql(qualifiedTableName: string, table: StorageTable): string {\n const columnDefinitions = Object.entries(table.columns).map(\n ([columnName, column]: [string, StorageColumn]) => {\n const parts = [\n quoteIdentifier(columnName),\n column.nativeType,\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n },\n );\n\n const constraintDefinitions: string[] = [];\n if (table.primaryKey) {\n constraintDefinitions.push(\n `PRIMARY KEY (${table.primaryKey.columns.map(quoteIdentifier).join(', ')})`,\n );\n }\n\n const allDefinitions = [...columnDefinitions, ...constraintDefinitions];\n return `CREATE TABLE ${qualifiedTableName} (\\n ${allDefinitions.join(',\\n ')}\\n)`;\n}\n\nfunction qualifyTableName(schema: string, table: string): string {\n return `${quoteIdentifier(schema)}.${quoteIdentifier(table)}`;\n}\n\nfunction toRegclassLiteral(schema: string, name: string): string {\n const regclass = `${quoteIdentifier(schema)}.${quoteIdentifier(name)}`;\n return `'${escapeLiteral(regclass)}'`;\n}\n\nfunction quoteIdentifier(identifier: string): string {\n return `\"${identifier.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction escapeLiteral(value: string): string {\n return value.replace(/'/g, \"''\");\n}\n\nfunction sortedEntries<V>(record: Readonly<Record<string, V>>): Array<[string, V]> {\n return Object.entries(record).sort(([a], [b]) => a.localeCompare(b)) as Array<[string, V]>;\n}\n\nfunction constraintExistsCheck({\n constraintName,\n schema,\n exists = true,\n}: {\n constraintName: string;\n schema: string;\n exists?: boolean;\n}): string {\n const existsClause = exists ? 'EXISTS' : 'NOT EXISTS';\n return `SELECT ${existsClause} (\n SELECT 1 FROM pg_constraint c\n JOIN pg_namespace n ON c.connamespace = n.oid\n WHERE c.conname = '${escapeLiteral(constraintName)}'\n AND n.nspname = '${escapeLiteral(schema)}'\n)`;\n}\n"],"mappings":";AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAO9B,SAAS,YAAY;;;ACHrB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAqBP,IAAM,yBAAwC;AAAA,EAC5C,eAAe;AACjB;AAEA,IAAM,mBAA2C;AAAA,EAC/C,UAAU;AACZ;AAEO,SAAS,+BACd,SAAiC,CAAC,GACW;AAC7C,SAAO,IAAI,yBAAyB;AAAA,IAClC,GAAG;AAAA,IACH,GAAG;AAAA,EACL,CAAC;AACH;AAEA,IAAM,2BAAN,MAAsF;AAAA,EACpF,YAA6B,QAAuB;AAAvB;AAAA,EAAwB;AAAA,EAErD,KAAK,SAAsC;AACzC,UAAM,aAAa,QAAQ,cAAc,KAAK,OAAO;AACrD,UAAM,eAAe,KAAK,qBAAqB,QAAQ,MAAM;AAC7D,QAAI,cAAc;AAChB,aAAO;AAAA,IACT;AAEA,UAAM,iBAAiB,OAAO,KAAK,QAAQ,OAAO,MAAM;AACxD,QAAI,eAAe,SAAS,GAAG;AAC7B,YAAM,YAAY,e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AAA,EACH,CAAC;AAAA,EACD,eAAe;AACjB,CAAC;AAKD,SAAS,qBAA4C;AACnD,QAAM,eAAe,KAAK,WAAW,2BAA2B;AAChE,QAAM,eAAe,KAAK,MAAM,aAAa,cAAc,OAAO,CAAC;AAEnE,QAAM,SAAS,4BAA4B,YAAY;AACvD,MAAI,kBAAkB,KAAK,QAAQ;AACjC,UAAM,WAAW,OAAO,IAAI,CAAC,MAA2B,EAAE,OAAO,EAAE,KAAK,IAAI;AAC5E,UAAM,IAAI,MAAM,wCAAwC,YAAY,KAAK,QAAQ,EAAE;AAAA,EACrF;AAEA,SAAO;AACT;AAKA,IAAM,2BACJ;AAAA,EACE,MAAM;AAAA,EACN,UAAU;AAAA,EACV,UAAU;AAAA,EACV,IAAI;AAAA,EACJ,UAAU,mBAAmB;AAAA,EAC7B,SAAmD;AACjD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA,cAAc,SAAmC;AAC/C,WAAO,+BAA+B;AAAA,EACxC;AACF;AAEF,IAAO,kBAAQ;","names":[]}
1
+ {"version":3,"sources":["../../src/exports/control.ts","../../src/core/migrations/planner.ts","../../src/core/migrations/runner.ts","../../src/core/migrations/statement-builders.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ExtensionPackManifest } from '@prisma-next/contract/pack-manifest-types';\nimport type { ControlTargetInstance } from '@prisma-next/core-control-plane/types';\nimport type {\n SqlControlFamilyInstance,\n SqlControlTargetDescriptor,\n} from '@prisma-next/family-sql/control';\nimport { type } from 'arktype';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nconst TypesImportSpecSchema = type({\n package: 'string',\n named: 'string',\n alias: 'string',\n});\n\nconst ExtensionPackManifestSchema = type({\n id: 'string',\n version: 'string',\n 'targets?': type({ '[string]': type({ 'minVersion?': 'string' }) }),\n 'capabilities?': 'Record<string, unknown>',\n 'types?': type({\n 'codecTypes?': type({\n import: TypesImportSpecSchema,\n }),\n 'operationTypes?': type({\n import: TypesImportSpecSchema,\n }),\n }),\n 'operations?': 'unknown[]',\n});\n\n/**\n * Loads the target manifest from packs/manifest.json.\n */\nfunction loadTargetManifest(): ExtensionPackManifest {\n const manifestPath = join(__dirname, '../../packs/manifest.json');\n const manifestJson = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n\n const result = ExtensionPackManifestSchema(manifestJson);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Invalid target manifest structure at ${manifestPath}: ${messages}`);\n }\n\n return result as ExtensionPackManifest;\n}\n\n/**\n * Postgres target descriptor for CLI config.\n */\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n kind: 'target',\n familyId: 'sql',\n targetId: 'postgres',\n id: 'postgres',\n manifest: loadTargetManifest(),\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n","import type {\n MigrationOperationPolicy,\n MigrationPlanner,\n MigrationPlannerPlanOptions,\n MigrationPlanOperation,\n} from '@prisma-next/family-sql/control';\nimport {\n createMigrationPlan,\n plannerFailure,\n plannerSuccess,\n} from '@prisma-next/family-sql/control';\nimport type {\n SqlContract,\n SqlStorage,\n StorageColumn,\n StorageTable,\n} from '@prisma-next/sql-contract/types';\n\ntype OperationClass = 'extension' | 'table' | 'unique' | 'index' | 'foreignKey';\n\nexport interface PostgresPlanTargetDetails {\n readonly schema: string;\n readonly objectType: OperationClass;\n readonly name: string;\n readonly table?: string;\n}\n\ninterface PlannerConfig {\n readonly defaultSchema: string;\n}\n\nconst DEFAULT_PLANNER_CONFIG: PlannerConfig = {\n defaultSchema: 'public',\n};\n\nconst PG_EXTENSION_SQL: Record<string, string> = {\n pgvector: 'CREATE EXTENSION IF NOT EXISTS vector',\n};\n\nexport function createPostgresMigrationPlanner(\n config: Partial<PlannerConfig> = {},\n): MigrationPlanner<PostgresPlanTargetDetails> {\n return new PostgresMigrationPlanner({\n ...DEFAULT_PLANNER_CONFIG,\n ...config,\n });\n}\n\nclass PostgresMigrationPlanner implements MigrationPlanner<PostgresPlanTargetDetails> {\n constructor(private readonly config: PlannerConfig) {}\n\n plan(options: MigrationPlannerPlanOptions) {\n const schemaName = options.schemaName ?? this.config.defaultSchema;\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) {\n return policyResult;\n }\n\n const existingTables = Object.keys(options.schema.tables);\n if (existingTables.length > 0) {\n const tableList = existingTables.sort().join(', ');\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: `The Postgres migration planner currently supports only empty databases. Found ${existingTables.length} existing table(s): ${tableList}`,\n why: 'Remove existing tables or use a future planner mode that handles subsets/supersets.',\n },\n ]);\n }\n\n const extensionResult = this.validateExtensions(options.contract);\n if (extensionResult) {\n return extensionResult;\n }\n\n const operations: MigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n\n operations.push(\n ...this.buildExtensionOperations(options.contract, schemaName),\n ...this.buildTableOperations(options.contract.storage.tables, schemaName),\n ...this.buildUniqueOperations(options.contract.storage.tables, schemaName),\n ...this.buildIndexOperations(options.contract.storage.tables, schemaName),\n ...this.buildForeignKeyOperations(options.contract.storage.tables, schemaName),\n );\n\n const plan = createMigrationPlan<PostgresPlanTargetDetails>({\n targetId: 'postgres',\n origin: null,\n destination: {\n coreHash: options.contract.coreHash,\n ...(options.contract.profileHash ? { profileHash: options.contract.profileHash } : {}),\n },\n operations,\n });\n\n return plannerSuccess(plan);\n }\n\n private validateExtensions(contract: SqlContract<SqlStorage>) {\n const extensions = contract.extensions ?? {};\n const extensionNames = Object.keys(extensions);\n const unsupportedExtensions = extensionNames.filter(\n (extensionName) => !PG_EXTENSION_SQL[extensionName],\n );\n if (unsupportedExtensions.length > 0) {\n const supportedExtensions = Object.keys(PG_EXTENSION_SQL).join(', ');\n const unsupportedList = unsupportedExtensions.join(', ');\n return plannerFailure([\n {\n kind: 'unsupportedExtension' as const,\n summary: `Unsupported PostgreSQL extensions in contract: ${unsupportedList}`,\n why: `The Postgres migration planner currently only supports: ${supportedExtensions}. Extensions are defined in contract.extensions.`,\n location: { extension: unsupportedList },\n },\n ]);\n }\n return null;\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Init planner requires additive operations be allowed',\n why: 'The init planner only emits additive operations. Update the policy to include \"additive\".',\n },\n ]);\n }\n return null;\n }\n\n private buildExtensionOperations(\n contract: SqlContract<SqlStorage>,\n schema: string,\n ): readonly MigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const extensions = contract.extensions ?? {};\n const extensionNames = Object.keys(extensions);\n const operations: MigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n\n // Extensions are validated in validateExtensions() before this method is called\n for (const extensionName of extensionNames) {\n const sql = PG_EXTENSION_SQL[extensionName];\n if (!sql) {\n // This should never happen since we validate extensions in validateExtensions(), but TypeScript requires this check\n throw new Error(`Extension SQL not found for ${extensionName}`);\n }\n const details = this.buildTargetDetails('extension', extensionName, schema);\n operations.push({\n id: `extension.${extensionName}`,\n label: `Enable extension \"${extensionName}\"`,\n summary: `Ensures the ${extensionName} extension is available`,\n operationClass: 'additive',\n target: { id: 'postgres', details },\n precheck: [\n {\n description: `verify extension \"${extensionName}\" is not already enabled`,\n sql: `SELECT NOT EXISTS (SELECT 1 FROM pg_extension WHERE extname = '${escapeLiteral(\n this.extensionDatabaseName(extensionName),\n )}')`,\n },\n ],\n execute: [\n {\n description: `create extension \"${extensionName}\"`,\n sql,\n },\n ],\n postcheck: [\n {\n description: `confirm extension \"${extensionName}\" is enabled`,\n sql: `SELECT EXISTS (SELECT 1 FROM pg_extension WHERE extname = '${escapeLiteral(\n this.extensionDatabaseName(extensionName),\n )}')`,\n },\n ],\n });\n }\n\n return operations;\n }\n\n private extensionDatabaseName(extensionName: string): string {\n if (extensionName === 'pgvector') {\n return 'vector';\n }\n return extensionName;\n }\n\n private buildTableOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: string,\n ): readonly MigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: MigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n const qualified = qualifyTableName(schema, tableName);\n operations.push({\n id: `table.${tableName}`,\n label: `Create table ${tableName}`,\n summary: `Creates table ${tableName} with required columns`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schema),\n },\n precheck: [\n {\n description: `ensure table \"${tableName}\" does not exist`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schema, tableName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create table \"${tableName}\"`,\n sql: buildCreateTableSql(qualified, table),\n },\n ],\n postcheck: [\n {\n description: `verify table \"${tableName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schema, tableName)}) IS NOT NULL`,\n },\n ],\n });\n }\n return operations;\n }\n\n private buildUniqueOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: string,\n ): readonly MigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: MigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n for (const unique of table.uniques) {\n const constraintName = unique.name ?? `${tableName}_${unique.columns.join('_')}_key`;\n operations.push({\n id: `unique.${tableName}.${constraintName}`,\n label: `Add unique constraint ${constraintName} on ${tableName}`,\n summary: `Adds unique constraint ${constraintName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('unique', constraintName, schema, tableName),\n },\n precheck: [\n {\n description: `ensure unique constraint \"${constraintName}\" is missing`,\n sql: constraintExistsCheck({ constraintName, schema, exists: false }),\n },\n ],\n execute: [\n {\n description: `add unique constraint \"${constraintName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schema, tableName)}\nADD CONSTRAINT ${quoteIdentifier(constraintName)}\nUNIQUE (${unique.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify unique constraint \"${constraintName}\" exists`,\n sql: constraintExistsCheck({ constraintName, schema }),\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildIndexOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: string,\n ): readonly MigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: MigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n for (const index of table.indexes) {\n const indexName = index.name ?? `${tableName}_${index.columns.join('_')}_idx`;\n operations.push({\n id: `index.${tableName}.${indexName}`,\n label: `Create index ${indexName} on ${tableName}`,\n summary: `Creates index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('index', indexName, schema, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" is missing`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schema, indexName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create index \"${indexName}\"`,\n sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(\n schema,\n tableName,\n )} (${index.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schema, indexName)}) IS NOT NULL`,\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildForeignKeyOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: string,\n ): readonly MigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: MigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n for (const foreignKey of table.foreignKeys) {\n const fkName = foreignKey.name ?? `${tableName}_${foreignKey.columns.join('_')}_fkey`;\n operations.push({\n id: `foreignKey.${tableName}.${fkName}`,\n label: `Add foreign key ${fkName} on ${tableName}`,\n summary: `Adds foreign key ${fkName} referencing ${foreignKey.references.table}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('foreignKey', fkName, schema, tableName),\n },\n precheck: [\n {\n description: `ensure foreign key \"${fkName}\" is missing`,\n sql: constraintExistsCheck({ constraintName: fkName, schema, exists: false }),\n },\n ],\n execute: [\n {\n description: `add foreign key \"${fkName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schema, tableName)}\nADD CONSTRAINT ${quoteIdentifier(fkName)}\nFOREIGN KEY (${foreignKey.columns.map(quoteIdentifier).join(', ')})\nREFERENCES ${qualifyTableName(schema, foreignKey.references.table)} (${foreignKey.references.columns\n .map(quoteIdentifier)\n .join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify foreign key \"${fkName}\" exists`,\n sql: constraintExistsCheck({ constraintName: fkName, schema }),\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildTargetDetails(\n objectType: OperationClass,\n name: string,\n schema: string,\n table?: string,\n ): PostgresPlanTargetDetails {\n return {\n schema,\n objectType,\n name,\n ...(table ? { table } : {}),\n };\n }\n}\n\nfunction buildCreateTableSql(qualifiedTableName: string, table: StorageTable): string {\n const columnDefinitions = Object.entries(table.columns).map(\n ([columnName, column]: [string, StorageColumn]) => {\n const parts = [\n quoteIdentifier(columnName),\n column.nativeType,\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n },\n );\n\n const constraintDefinitions: string[] = [];\n if (table.primaryKey) {\n constraintDefinitions.push(\n `PRIMARY KEY (${table.primaryKey.columns.map(quoteIdentifier).join(', ')})`,\n );\n }\n\n const allDefinitions = [...columnDefinitions, ...constraintDefinitions];\n return `CREATE TABLE ${qualifiedTableName} (\\n ${allDefinitions.join(',\\n ')}\\n)`;\n}\n\nfunction qualifyTableName(schema: string, table: string): string {\n return `${quoteIdentifier(schema)}.${quoteIdentifier(table)}`;\n}\n\nfunction toRegclassLiteral(schema: string, name: string): string {\n const regclass = `${quoteIdentifier(schema)}.${quoteIdentifier(name)}`;\n return `'${escapeLiteral(regclass)}'`;\n}\n\nfunction quoteIdentifier(identifier: string): string {\n return `\"${identifier.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction escapeLiteral(value: string): string {\n return value.replace(/'/g, \"''\");\n}\n\nfunction sortedEntries<V>(record: Readonly<Record<string, V>>): Array<[string, V]> {\n return Object.entries(record).sort(([a], [b]) => a.localeCompare(b)) as Array<[string, V]>;\n}\n\nfunction constraintExistsCheck({\n constraintName,\n schema,\n exists = true,\n}: {\n constraintName: string;\n schema: string;\n exists?: boolean;\n}): string {\n const existsClause = exists ? 'EXISTS' : 'NOT EXISTS';\n return `SELECT ${existsClause} (\n SELECT 1 FROM pg_constraint c\n JOIN pg_namespace n ON c.connamespace = n.oid\n WHERE c.conname = '${escapeLiteral(constraintName)}'\n AND n.nspname = '${escapeLiteral(schema)}'\n)`;\n}\n","import type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type { Result } from '@prisma-next/core-control-plane/result';\nimport { ok, okVoid } from '@prisma-next/core-control-plane/result';\nimport type {\n MigrationOperationPolicy,\n MigrationPlanContractInfo,\n MigrationPlanOperation,\n MigrationPlanOperationStep,\n MigrationRunner,\n MigrationRunnerExecuteOptions,\n MigrationRunnerFailure,\n MigrationRunnerResult,\n SchemaVerifyOptions,\n SqlControlFamilyInstance,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { readMarker } from '@prisma-next/family-sql/verify';\nimport type { PostgresPlanTargetDetails } from './planner';\nimport {\n buildLedgerInsertStatement,\n buildWriteMarkerStatements,\n ensureLedgerTableStatement,\n ensureMarkerTableStatement,\n ensurePrismaContractSchemaStatement,\n type SqlStatement,\n} from './statement-builders';\n\ninterface RunnerConfig {\n readonly defaultSchema: string;\n}\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly MigrationPlanOperation<PostgresPlanTargetDetails>[];\n}\n\nconst DEFAULT_CONFIG: RunnerConfig = {\n defaultSchema: 'public',\n};\n\nconst LOCK_DOMAIN = 'prisma_next.contract.marker';\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n // Clone array (shallow clone of array elements)\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n // Recursively clone nested objects\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n // Primitives are copied as-is\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n config: Partial<RunnerConfig> = {},\n): MigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });\n}\n\nclass PostgresMigrationRunner implements MigrationRunner<PostgresPlanTargetDetails> {\n constructor(\n private readonly family: SqlControlFamilyInstance,\n private readonly config: RunnerConfig,\n ) {}\n\n async execute(\n options: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<MigrationRunnerResult> {\n const schema = options.schemaName ?? this.config.defaultSchema;\n const driver = options.driver;\n const lockKey = `${LOCK_DOMAIN}:${schema}`;\n\n // Static checks - fail fast before transaction\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) {\n return destinationCheck;\n }\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) {\n return policyCheck;\n }\n\n // Begin transaction for DB operations\n await this.beginTransaction(driver);\n let committed = false;\n try {\n await this.acquireLock(driver, lockKey);\n await this.ensureControlTables(driver);\n const existingMarker = await readMarker(driver);\n\n // Validate plan origin matches existing marker (needs marker from DB)\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) {\n return markerCheck;\n }\n\n // Apply plan operations or skip if marker already at destination\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n let applyValue: ApplyPlanSuccessValue;\n\n if (markerAtDestination) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) {\n return applyResult;\n }\n applyValue = applyResult.value;\n }\n\n // Verify resulting schema matches contract\n const schemaVerifyOptions: SchemaVerifyOptions = {\n driver,\n contractIR: options.destinationContract,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n };\n const schemaVerifyResult = await this.family.schemaVerify(schemaVerifyOptions);\n if (!schemaVerifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: {\n issues: schemaVerifyResult.schema.issues,\n },\n });\n }\n\n // Record marker and ledger entries\n await this.upsertMarker(driver, options, existingMarker);\n await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);\n\n await this.commitTransaction(driver);\n committed = true;\n return runnerSuccess({\n operationsPlanned: options.plan.operations.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<Result<ApplyPlanSuccessValue, MigrationRunnerFailure>> {\n let operationsExecuted = 0;\n const executedOperations: Array<MigrationPlanOperation<PostgresPlanTargetDetails>> = [];\n for (const operation of options.plan.operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(\n driver,\n operation.postcheck,\n );\n if (postcheckAlreadySatisfied) {\n executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));\n continue;\n }\n\n const precheckResult = await this.runExpectationSteps(\n driver,\n operation.precheck,\n operation,\n 'precheck',\n );\n if (!precheckResult.ok) {\n return precheckResult;\n }\n\n const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);\n if (!executeResult.ok) {\n return executeResult;\n }\n\n const postcheckResult = await this.runExpectationSteps(\n driver,\n operation.postcheck,\n operation,\n 'postcheck',\n );\n if (!postcheckResult.ok) {\n return postcheckResult;\n }\n\n executedOperations.push(operation);\n operationsExecuted += 1;\n } finally {\n options.callbacks?.onOperationComplete?.(operation);\n }\n }\n return ok({ operationsExecuted, executedOperations });\n }\n\n private async ensureControlTables(\n driver: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await this.executeStatement(driver, ensurePrismaContractSchemaStatement);\n await this.executeStatement(driver, ensureMarkerTableStatement);\n await this.executeStatement(driver, ensureLedgerTableStatement);\n }\n\n private async runExpectationSteps(\n driver: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly MigrationPlanOperationStep[],\n operation: MigrationPlanOperation<PostgresPlanTargetDetails>,\n phase: 'precheck' | 'postcheck',\n ): Promise<Result<void, MigrationRunnerFailure>> {\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n const code = phase === 'precheck' ? 'PRECHECK_FAILED' : 'POSTCHECK_FAILED';\n return runnerFailure(\n code,\n `Operation ${operation.id} failed during ${phase}: ${step.description}`,\n {\n meta: {\n operationId: operation.id,\n phase,\n stepDescription: step.description,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private async runExecuteSteps(\n driver: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly MigrationPlanOperationStep[],\n operation: MigrationPlanOperation<PostgresPlanTargetDetails>,\n ): Promise<Result<void, MigrationRunnerFailure>> {\n for (const step of steps) {\n try {\n await driver.query(step.sql);\n } catch (error) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error instanceof Error ? error.message : String(error),\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private stepResultIsTrue(rows: readonly Record<string, unknown>[]): boolean {\n if (!rows || rows.length === 0) {\n return false;\n }\n const firstRow = rows[0];\n const firstValue = firstRow ? Object.values(firstRow)[0] : undefined;\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n // PostgreSQL boolean representations: 't'/'f', 'true'/'false', '1'/'0'\n if (lower === 't' || lower === 'true' || lower === '1') {\n return true;\n }\n if (lower === 'f' || lower === 'false' || lower === '0') {\n return false;\n }\n // For other strings, non-empty is truthy (though this case shouldn't occur for boolean checks)\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly MigrationPlanOperationStep[],\n ): Promise<boolean> {\n if (steps.length === 0) {\n return false;\n }\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: MigrationPlanOperation<PostgresPlanTargetDetails>,\n ): MigrationPlanOperation<PostgresPlanTargetDetails> {\n // Clone and freeze existing meta if present\n const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : undefined;\n\n // Create frozen runner metadata\n const runnerMeta = Object.freeze({\n skipped: true,\n reason: 'postcheck_pre_satisfied',\n });\n\n // Merge and freeze the combined meta\n const mergedMeta = Object.freeze({\n ...(clonedMeta ?? {}),\n runner: runnerMeta,\n });\n\n // Clone and freeze arrays to prevent mutation\n const frozenPostcheck = Object.freeze([...operation.postcheck]);\n\n return Object.freeze({\n id: operation.id,\n label: operation.label,\n ...(operation.summary ? { summary: operation.summary } : {}),\n operationClass: operation.operationClass,\n target: operation.target, // Already frozen from plan creation\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: frozenPostcheck,\n ...(operation.meta || mergedMeta ? { meta: mergedMeta } : {}),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.coreHash !== plan.destination.coreHash) {\n return false;\n }\n if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {\n return false;\n }\n return true;\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly MigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, MigrationRunnerFailure> {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${policy.allowedOperationClasses.join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n allowedClasses: policy.allowedOperationClasses,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, MigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n if (!marker) {\n return okVoid();\n }\n if (this.markerMatchesDestination(marker, plan)) {\n return okVoid();\n }\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.coreHash}) does not match plan origin (no marker expected).`,\n {\n meta: {\n markerCoreHash: marker.coreHash,\n expectedOrigin: null,\n },\n },\n );\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin core hash ${origin.coreHash}.`,\n {\n meta: {\n expectedOriginCoreHash: origin.coreHash,\n },\n },\n );\n }\n if (marker.coreHash !== origin.coreHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.coreHash}) does not match plan origin (${origin.coreHash}).`,\n {\n meta: {\n markerCoreHash: marker.coreHash,\n expectedOriginCoreHash: origin.coreHash,\n },\n },\n );\n }\n if (origin.profileHash && marker.profileHash !== origin.profileHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`,\n {\n meta: {\n markerProfileHash: marker.profileHash,\n expectedOriginProfileHash: origin.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private ensurePlanMatchesDestinationContract(\n destination: MigrationPlanContractInfo,\n contract: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['destinationContract'],\n ): Result<void, MigrationRunnerFailure> {\n if (destination.coreHash !== contract.coreHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination core hash (${destination.coreHash}) does not match provided contract core hash (${contract.coreHash}).`,\n {\n meta: {\n planCoreHash: destination.coreHash,\n contractCoreHash: contract.coreHash,\n },\n },\n );\n }\n if (\n destination.profileHash &&\n contract.profileHash &&\n destination.profileHash !== contract.profileHash\n ) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`,\n {\n meta: {\n planProfileHash: destination.profileHash,\n contractProfileHash: contract.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async upsertMarker(\n driver: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n ): Promise<void> {\n const writeStatements = buildWriteMarkerStatements({\n coreHash: options.plan.destination.coreHash,\n profileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.coreHash,\n contractJson: options.destinationContract,\n canonicalVersion: null,\n meta: {},\n });\n const statement = existingMarker ? writeStatements.update : writeStatements.insert;\n await this.executeStatement(driver, statement);\n }\n\n private async recordLedgerEntry(\n driver: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n executedOperations: readonly MigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Promise<void> {\n const ledgerStatement = buildLedgerInsertStatement({\n originCoreHash: existingMarker?.coreHash ?? null,\n originProfileHash: existingMarker?.profileHash ?? null,\n destinationCoreHash: options.plan.destination.coreHash,\n destinationProfileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.coreHash,\n contractJsonBefore: existingMarker?.contractJson ?? null,\n contractJsonAfter: options.destinationContract,\n operations: executedOperations,\n });\n await this.executeStatement(driver, ledgerStatement);\n }\n\n private async acquireLock(\n driver: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n key: string,\n ): Promise<void> {\n await driver.query('select pg_advisory_xact_lock(hashtext($1))', [key]);\n }\n\n private async beginTransaction(\n driver: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN');\n }\n\n private async commitTransaction(\n driver: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: MigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n statement: SqlStatement,\n ): Promise<void> {\n if (statement.params.length > 0) {\n await driver.query(statement.sql, statement.params);\n return;\n }\n await driver.query(statement.sql);\n }\n}\n","export interface SqlStatement {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\nexport const ensurePrismaContractSchemaStatement: SqlStatement = {\n sql: 'create schema if not exists prisma_contract',\n params: [],\n};\n\nexport const ensureMarkerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n id smallint primary key default 1,\n core_hash text not null,\n profile_hash text not null,\n contract_json jsonb,\n canonical_version int,\n updated_at timestamptz not null default now(),\n app_tag text,\n meta jsonb not null default '{}'\n )`,\n params: [],\n};\n\nexport const ensureLedgerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.ledger (\n id bigserial primary key,\n created_at timestamptz not null default now(),\n origin_core_hash text,\n origin_profile_hash text,\n destination_core_hash text not null,\n destination_profile_hash text,\n contract_json_before jsonb,\n contract_json_after jsonb,\n operations jsonb not null\n )`,\n params: [],\n};\n\nexport interface WriteMarkerInput {\n readonly coreHash: string;\n readonly profileHash: string;\n readonly contractJson?: unknown;\n readonly canonicalVersion?: number | null;\n readonly appTag?: string | null;\n readonly meta?: Record<string, unknown>;\n}\n\nexport function buildWriteMarkerStatements(input: WriteMarkerInput): {\n readonly insert: SqlStatement;\n readonly update: SqlStatement;\n} {\n const params: readonly unknown[] = [\n 1,\n input.coreHash,\n input.profileHash,\n jsonParam(input.contractJson),\n input.canonicalVersion ?? null,\n input.appTag ?? null,\n jsonParam(input.meta ?? {}),\n ];\n\n return {\n insert: {\n sql: `insert into prisma_contract.marker (\n id,\n core_hash,\n profile_hash,\n contract_json,\n canonical_version,\n updated_at,\n app_tag,\n meta\n ) values (\n $1,\n $2,\n $3,\n $4::jsonb,\n $5,\n now(),\n $6,\n $7::jsonb\n )`,\n params,\n },\n update: {\n sql: `update prisma_contract.marker set\n core_hash = $2,\n profile_hash = $3,\n contract_json = $4::jsonb,\n canonical_version = $5,\n updated_at = now(),\n app_tag = $6,\n meta = $7::jsonb\n where id = $1`,\n params,\n },\n };\n}\n\nexport interface LedgerInsertInput {\n readonly originCoreHash?: string | null;\n readonly originProfileHash?: string | null;\n readonly destinationCoreHash: string;\n readonly destinationProfileHash?: string | null;\n readonly contractJsonBefore?: unknown;\n readonly contractJsonAfter?: unknown;\n readonly operations: unknown;\n}\n\nexport function buildLedgerInsertStatement(input: LedgerInsertInput): SqlStatement {\n return {\n sql: `insert into prisma_contract.ledger (\n origin_core_hash,\n origin_profile_hash,\n destination_core_hash,\n destination_profile_hash,\n contract_json_before,\n contract_json_after,\n operations\n ) values (\n $1,\n $2,\n $3,\n $4,\n $5::jsonb,\n $6::jsonb,\n $7::jsonb\n )`,\n params: [\n input.originCoreHash ?? null,\n input.originProfileHash ?? null,\n input.destinationCoreHash,\n input.destinationProfileHash ?? null,\n jsonParam(input.contractJsonBefore),\n jsonParam(input.contractJsonAfter),\n jsonParam(input.operations),\n ],\n };\n}\n\nfunction jsonParam(value: unknown): string {\n return JSON.stringify(value ?? null);\n}\n"],"mappings":";AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAO9B,SAAS,YAAY;;;ACHrB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAqBP,IAAM,yBAAwC;AAAA,EAC5C,eAAe;AACjB;AAEA,IAAM,mBAA2C;AAAA,EAC/C,UAAU;AACZ;AAEO,SAAS,+BACd,SAAiC,C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J,UAAU,mBAAmB;AAAA,EAC7B,SAAmD;AACjD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA,cAAc,SAAmC;AAC/C,WAAO,+BAA+B;AAAA,EACxC;AAAA,EACA,aAAa,QAAQ;AACnB,WAAO,8BAA8B,MAAM;AAAA,EAC7C;AACF;AAEF,IAAO,kBAAQ;","names":[]}
package/package.json CHANGED
@@ -1,24 +1,27 @@
1
1
  {
2
2
  "name": "@prisma-next/target-postgres",
3
- "version": "0.1.0-dev.14",
3
+ "version": "0.1.0-dev.15",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "Postgres target pack for Prisma Next",
7
7
  "dependencies": {
8
8
  "arktype": "^2.0.0",
9
- "@prisma-next/family-sql": "0.1.0-dev.14",
10
- "@prisma-next/cli": "0.1.0-dev.14",
11
- "@prisma-next/contract": "0.1.0-dev.14",
12
- "@prisma-next/sql-contract": "0.1.0-dev.14",
13
- "@prisma-next/sql-schema-ir": "0.1.0-dev.14",
14
- "@prisma-next/core-control-plane": "0.1.0-dev.14",
15
- "@prisma-next/core-execution-plane": "0.1.0-dev.14"
9
+ "@prisma-next/family-sql": "0.1.0-dev.15",
10
+ "@prisma-next/cli": "0.1.0-dev.15",
11
+ "@prisma-next/contract": "0.1.0-dev.15",
12
+ "@prisma-next/sql-contract": "0.1.0-dev.15",
13
+ "@prisma-next/core-control-plane": "0.1.0-dev.15",
14
+ "@prisma-next/core-execution-plane": "0.1.0-dev.15",
15
+ "@prisma-next/sql-schema-ir": "0.1.0-dev.15"
16
16
  },
17
17
  "devDependencies": {
18
+ "vite-tsconfig-paths": "^5.1.4",
18
19
  "tsup": "^8.3.0",
19
20
  "typescript": "^5.9.3",
20
21
  "vitest": "^2.1.1",
21
- "@prisma-next/test-utils": "0.0.1"
22
+ "@prisma-next/driver-postgres": "0.1.0-dev.15",
23
+ "@prisma-next/test-utils": "0.0.1",
24
+ "@prisma-next/adapter-postgres": "0.1.0-dev.15"
22
25
  },
23
26
  "files": [
24
27
  "dist",