@prisma-next/target-postgres 0.5.0-dev.67 → 0.5.0-dev.68
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/dist/control.mjs +91 -39
- package/dist/control.mjs.map +1 -1
- package/dist/{planner-8hkq9lQH.mjs → planner-JmqeNfGa.mjs} +10 -3
- package/dist/{planner-8hkq9lQH.mjs.map → planner-JmqeNfGa.mjs.map} +1 -1
- package/dist/planner.d.mts.map +1 -1
- package/dist/planner.mjs +1 -1
- package/dist/{statement-builders-Dsix6Dl5.mjs → statement-builders-BT889jV0.mjs} +4 -4
- package/dist/statement-builders-BT889jV0.mjs.map +1 -0
- package/dist/statement-builders.mjs +1 -1
- package/package.json +14 -14
- package/src/core/migrations/planner.ts +30 -2
- package/src/core/migrations/runner.ts +126 -82
- package/dist/statement-builders-Dsix6Dl5.mjs.map +0 -1
package/dist/control.mjs
CHANGED
|
@@ -2,12 +2,13 @@ import { t as postgresTargetDescriptorMeta } from "./descriptor-meta-Dde_BS3K.mj
|
|
|
2
2
|
import { t as parsePostgresDefault } from "./default-normalizer-C8XyZj85.mjs";
|
|
3
3
|
import { t as normalizeSchemaNativeType } from "./native-type-normalizer-Cry4QoLf.mjs";
|
|
4
4
|
import { o as renderDefaultLiteral } from "./planner-ddl-builders-CLB7Umhh.mjs";
|
|
5
|
-
import { t as createPostgresMigrationPlanner } from "./planner-
|
|
6
|
-
import { a as ensureMarkerTableStatement, i as ensureLedgerTableStatement, n as buildLedgerInsertStatement, o as ensurePrismaContractSchemaStatement, r as buildMergeMarkerStatements } from "./statement-builders-
|
|
5
|
+
import { t as createPostgresMigrationPlanner } from "./planner-JmqeNfGa.mjs";
|
|
6
|
+
import { a as ensureMarkerTableStatement, i as ensureLedgerTableStatement, n as buildLedgerInsertStatement, o as ensurePrismaContractSchemaStatement, r as buildMergeMarkerStatements } from "./statement-builders-BT889jV0.mjs";
|
|
7
7
|
import { contractToSchemaIR, extractCodecControlHooks, runnerFailure, runnerSuccess } from "@prisma-next/family-sql/control";
|
|
8
8
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
9
9
|
import { verifySqlSchema } from "@prisma-next/family-sql/schema-verify";
|
|
10
|
-
import { ok, okVoid } from "@prisma-next/utils/result";
|
|
10
|
+
import { notOk, ok, okVoid } from "@prisma-next/utils/result";
|
|
11
|
+
import { APP_SPACE_ID } from "@prisma-next/framework-components/control";
|
|
11
12
|
import { SqlQueryError } from "@prisma-next/sql-errors";
|
|
12
13
|
//#region src/core/migrations/runner.ts
|
|
13
14
|
const DEFAULT_CONFIG = { defaultSchema: "public" };
|
|
@@ -38,9 +39,7 @@ var PostgresMigrationRunner = class {
|
|
|
38
39
|
this.config = config;
|
|
39
40
|
}
|
|
40
41
|
async execute(options) {
|
|
41
|
-
const schema = options.schemaName ?? this.config.defaultSchema;
|
|
42
42
|
const driver = options.driver;
|
|
43
|
-
const lockKey = `${LOCK_DOMAIN}:${schema}`;
|
|
44
43
|
const destinationCheck = this.ensurePlanMatchesDestinationContract(options.plan.destination, options.destinationContract);
|
|
45
44
|
if (!destinationCheck.ok) return destinationCheck;
|
|
46
45
|
const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);
|
|
@@ -48,28 +47,54 @@ var PostgresMigrationRunner = class {
|
|
|
48
47
|
await this.beginTransaction(driver);
|
|
49
48
|
let committed = false;
|
|
50
49
|
try {
|
|
51
|
-
await this.
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
50
|
+
const result = await this.executeOnConnection(options);
|
|
51
|
+
if (!result.ok) return result;
|
|
52
|
+
await this.commitTransaction(driver);
|
|
53
|
+
committed = true;
|
|
54
|
+
return result;
|
|
55
|
+
} finally {
|
|
56
|
+
if (!committed) await this.rollbackTransaction(driver);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Body of the migration runner without transaction management. The
|
|
61
|
+
* caller (single-space `execute(...)` above, or the multi-space
|
|
62
|
+
* outer-tx orchestrator at the SQL family level) owns the
|
|
63
|
+
* `BEGIN`/`COMMIT`/`ROLLBACK` lifecycle.
|
|
64
|
+
*/
|
|
65
|
+
async executeOnConnection(options) {
|
|
66
|
+
const schema = options.schemaName ?? this.config.defaultSchema;
|
|
67
|
+
const driver = options.driver;
|
|
68
|
+
if (options.space !== void 0 && options.space !== options.plan.spaceId) throw new Error(`SqlMigrationRunner: options.space (${options.space}) does not match plan.spaceId (${options.plan.spaceId})`);
|
|
69
|
+
const space = options.plan.spaceId;
|
|
70
|
+
const lockKey = `${LOCK_DOMAIN}:${schema}:${space}`;
|
|
71
|
+
const destinationCheck = this.ensurePlanMatchesDestinationContract(options.plan.destination, options.destinationContract);
|
|
72
|
+
if (!destinationCheck.ok) return destinationCheck;
|
|
73
|
+
const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);
|
|
74
|
+
if (!policyCheck.ok) return policyCheck;
|
|
75
|
+
await this.acquireLock(driver, lockKey);
|
|
76
|
+
const ensureResult = await this.ensureControlTables(driver);
|
|
77
|
+
if (!ensureResult.ok) return ensureResult;
|
|
78
|
+
const existingMarker = await this.family.readMarker({
|
|
79
|
+
driver,
|
|
80
|
+
space
|
|
81
|
+
});
|
|
82
|
+
const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);
|
|
83
|
+
if (!markerCheck.ok) return markerCheck;
|
|
84
|
+
const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);
|
|
85
|
+
const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;
|
|
86
|
+
const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;
|
|
87
|
+
let applyValue;
|
|
88
|
+
if (skipOperations) applyValue = {
|
|
89
|
+
operationsExecuted: 0,
|
|
90
|
+
executedOperations: []
|
|
91
|
+
};
|
|
92
|
+
else {
|
|
93
|
+
const applyResult = await this.applyPlan(driver, options);
|
|
94
|
+
if (!applyResult.ok) return applyResult;
|
|
95
|
+
applyValue = applyResult.value;
|
|
96
|
+
}
|
|
97
|
+
if (space === APP_SPACE_ID) {
|
|
73
98
|
const schemaIR = await this.family.introspect({
|
|
74
99
|
driver,
|
|
75
100
|
contract: options.destinationContract
|
|
@@ -88,19 +113,46 @@ var PostgresMigrationRunner = class {
|
|
|
88
113
|
why: "The resulting database schema does not satisfy the destination contract.",
|
|
89
114
|
meta: { issues: schemaVerifyResult.schema.issues }
|
|
90
115
|
});
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
116
|
+
}
|
|
117
|
+
const incomingInvariants = options.plan.providedInvariants ?? [];
|
|
118
|
+
const existingInvariants = new Set(existingMarker?.invariants ?? []);
|
|
119
|
+
const incomingIsSubsetOfExisting = incomingInvariants.every((id) => existingInvariants.has(id));
|
|
120
|
+
if (!(isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting)) {
|
|
121
|
+
await this.upsertMarker(driver, options, existingMarker, space);
|
|
122
|
+
await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);
|
|
123
|
+
}
|
|
124
|
+
return runnerSuccess({
|
|
125
|
+
operationsPlanned: options.plan.operations.length,
|
|
126
|
+
operationsExecuted: applyValue.operationsExecuted
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
async executeAcrossSpaces(options) {
|
|
130
|
+
const driver = options.driver;
|
|
131
|
+
const perSpaceOptions = options.perSpaceOptions;
|
|
132
|
+
if (perSpaceOptions.length === 0) return ok({ perSpaceResults: [] });
|
|
133
|
+
await this.beginTransaction(driver);
|
|
134
|
+
let committed = false;
|
|
135
|
+
try {
|
|
136
|
+
const perSpaceResults = [];
|
|
137
|
+
for (const spaceOptions of perSpaceOptions) {
|
|
138
|
+
const space = spaceOptions.space ?? spaceOptions.plan.spaceId;
|
|
139
|
+
const result = await this.executeOnConnection({
|
|
140
|
+
...spaceOptions,
|
|
141
|
+
driver,
|
|
142
|
+
space
|
|
143
|
+
});
|
|
144
|
+
if (!result.ok) return notOk({
|
|
145
|
+
...result.failure,
|
|
146
|
+
failingSpace: space
|
|
147
|
+
});
|
|
148
|
+
perSpaceResults.push({
|
|
149
|
+
space,
|
|
150
|
+
value: result.value
|
|
151
|
+
});
|
|
97
152
|
}
|
|
98
153
|
await this.commitTransaction(driver);
|
|
99
154
|
committed = true;
|
|
100
|
-
return
|
|
101
|
-
operationsPlanned: options.plan.operations.length,
|
|
102
|
-
operationsExecuted: applyValue.operationsExecuted
|
|
103
|
-
});
|
|
155
|
+
return ok({ perSpaceResults });
|
|
104
156
|
} finally {
|
|
105
157
|
if (!committed) await this.rollbackTransaction(driver);
|
|
106
158
|
}
|
|
@@ -283,10 +335,10 @@ var PostgresMigrationRunner = class {
|
|
|
283
335
|
} });
|
|
284
336
|
return okVoid();
|
|
285
337
|
}
|
|
286
|
-
async upsertMarker(driver, options, existingMarker) {
|
|
338
|
+
async upsertMarker(driver, options, existingMarker, space) {
|
|
287
339
|
const incomingInvariants = options.plan.providedInvariants ?? [];
|
|
288
340
|
const writeStatements = buildMergeMarkerStatements({
|
|
289
|
-
space
|
|
341
|
+
space,
|
|
290
342
|
storageHash: options.plan.destination.storageHash,
|
|
291
343
|
profileHash: options.plan.destination.profileHash ?? options.destinationContract.profileHash ?? options.plan.destination.storageHash,
|
|
292
344
|
contractJson: options.destinationContract,
|
package/dist/control.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"control.mjs","names":[],"sources":["../src/core/migrations/runner.ts","../src/exports/control.ts"],"sourcesContent":["import type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { ok, okVoid } from '@prisma-next/utils/result';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\nimport {\n buildLedgerInsertStatement,\n buildMergeMarkerStatements,\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 SqlMigrationPlanOperation<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): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(\n private readonly family: SqlControlFamilyInstance,\n private readonly config: RunnerConfig,\n ) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\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 const ensureResult = await this.ensureControlTables(driver);\n if (!ensureResult.ok) {\n return ensureResult;\n }\n const existingMarker = await this.family.readMarker({\n driver,\n space: options.plan.spaceId,\n });\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 // db update (origin: null) always applies; migration-apply (origin set,\n // origin !== destination) skips if marker already matches destination.\n // Self-edges (origin === destination) intentionally bypass the skip:\n // the migration is data-only, and the data transform's own check\n // decides whether `run` fires.\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;\n const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\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 // Step 1: Introspect live schema (DB I/O, family-owned)\n const schemaIR = await this.family.introspect({\n driver,\n contract: options.destinationContract,\n });\n\n // Step 2: Pure verification (no DB I/O)\n const schemaVerifyResult = verifySqlSchema({\n contract: options.destinationContract,\n schema: schemaIR,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n typeMetadataRegistry: this.family.typeMetadataRegistry,\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\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 // Self-edge no-op detection: a self-edge migration whose ops all\n // self-skipped (every op pre-satisfied) and that brings no new\n // invariants produced no observable change. Skip the marker +\n // ledger writes so an idempotent re-apply of a self-edge data\n // transform doesn't churn updatedAt or pile up empty ledger\n // entries. With data transforms now flowing through the unified\n // op loop, a pre-satisfied DT lands in the\n // `postcheckAlreadySatisfied` skip path which does not increment\n // `operationsExecuted`, so the check below correctly distinguishes\n // \"every op self-skipped\" from \"the plan had ops that ran\". `db\n // update` no-ops still write a ledger entry as audit trail.\n const incomingInvariants = options.plan.providedInvariants ?? [];\n const existingInvariants = new Set(existingMarker?.invariants ?? []);\n const incomingIsSubsetOfExisting = incomingInvariants.every((id) =>\n existingInvariants.has(id),\n );\n const isSelfEdgeNoOp =\n isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting;\n\n if (!isSelfEdgeNoOp) {\n await this.upsertMarker(driver, options, existingMarker);\n await this.recordLedgerEntry(\n driver,\n options,\n existingMarker,\n applyValue.executedOperations,\n );\n }\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: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<Result<ApplyPlanSuccessValue, SqlMigrationRunnerFailure>> {\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false; // Default true\n const runPostchecks = checks?.postchecks !== false; // Default true\n const runIdempotency = checks?.idempotencyChecks !== false; // Default true\n\n let operationsExecuted = 0;\n const executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> = [];\n for (const operation of options.plan.operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n // Idempotency probe: only run if both postchecks and idempotency checks are enabled\n if (runPostchecks && runIdempotency) {\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\n // Prechecks: only run if enabled\n if (runPrechecks) {\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\n const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);\n if (!executeResult.ok) {\n return executeResult;\n }\n\n // Postchecks: only run if enabled\n if (runPostchecks) {\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\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: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n await this.executeStatement(driver, ensurePrismaContractSchemaStatement);\n // Pre-1.0 zero-range guardrail: detect a pre-cleanup single-row\n // marker table (no `space` column) and surface a structured failure\n // rather than silently auto-migrating it to the per-space shape.\n // See `specs/framework-mechanism.spec.md § 2`.\n const legacyDetection = await this.detectLegacyMarkerShape(driver);\n if (!legacyDetection.ok) {\n return legacyDetection;\n }\n await this.executeStatement(driver, ensureMarkerTableStatement);\n await this.executeStatement(driver, ensureLedgerTableStatement);\n return okVoid();\n }\n\n private async detectLegacyMarkerShape(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const result = await driver.query<{ column_name: string }>(\n `select column_name\n from information_schema.columns\n where table_schema = 'prisma_contract'\n and table_name = 'marker'`,\n );\n if (result.rows.length === 0) {\n return okVoid();\n }\n const columns = new Set(result.rows.map((row) => row.column_name));\n if (columns.has('space')) {\n return okVoid();\n }\n return runnerFailure(\n 'LEGACY_MARKER_SHAPE',\n 'Legacy marker-table shape detected on prisma_contract.marker (no `space` column). ' +\n 'Prisma Next is in pre-1.0; the previous transitional auto-migration to the per-space-row schema has been removed. ' +\n 'Drop `prisma_contract.marker` and re-run `dbInit` to reinitialise from a clean baseline.',\n {\n meta: {\n table: 'prisma_contract.marker',\n columns: [...columns].sort(),\n },\n },\n );\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n phase: 'precheck' | 'postcheck',\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n const result = await driver.query(step.sql, step.params ?? []);\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: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n try {\n await driver.query(step.sql, step.params ?? []);\n } catch (error: unknown) {\n // Catch SqlQueryError and include normalized metadata\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n // Let SqlConnectionError and other errors propagate (fail-fast)\n throw error;\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: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\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, step.params ?? []);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<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 ...ifDefined('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 ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\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 SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\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: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n // No origin assertion on the plan — the caller does not want origin validation.\n // This is the case for `db update`, which introspects the live schema and does not\n // rely on marker continuity. `db init` handles its own marker checks before the runner.\n return okVoid();\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n {\n meta: {\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\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: SqlMigrationPlanContractInfo,\n contract: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['destinationContract'],\n ): Result<void, SqlMigrationRunnerFailure> {\n if (destination.storageHash !== contract.storage.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storage.storageHash,\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: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n ): Promise<void> {\n const incomingInvariants = options.plan.providedInvariants ?? [];\n const writeStatements = buildMergeMarkerStatements({\n space: options.plan.spaceId,\n storageHash: options.plan.destination.storageHash,\n profileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJson: options.destinationContract,\n canonicalVersion: null,\n meta: {},\n invariants: incomingInvariants,\n });\n const statement = existingMarker ? writeStatements.update : writeStatements.insert;\n await this.executeStatement(driver, statement);\n }\n\n private async recordLedgerEntry(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Promise<void> {\n const ledgerStatement = buildLedgerInsertStatement({\n originStorageHash: existingMarker?.storageHash ?? null,\n originProfileHash: existingMarker?.profileHash ?? null,\n destinationStorageHash: options.plan.destination.storageHash,\n destinationProfileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\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: SqlMigrationRunnerExecuteOptions<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: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<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","import type { ColumnDefault, Contract } from '@prisma-next/contract/types';\nimport type {\n SqlControlFamilyInstance,\n SqlControlTargetDescriptor,\n} from '@prisma-next/family-sql/control';\nimport { contractToSchemaIR, extractCodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlTargetInstance,\n MigrationRunner,\n} from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nfunction buildNativeTypeExpander(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n if (!frameworkComponents) {\n return undefined;\n }\n const codecHooks = extractCodecControlHooks(frameworkComponents);\n return (input: {\n readonly nativeType: string;\n readonly codecId?: string;\n readonly typeParams?: Record<string, unknown>;\n }) => {\n if (!input.typeParams) return input.nativeType;\n // Mirror `renderExpectedNativeType` in verify-sql-schema: when a codec\n // has no `expandNativeType` hook (e.g. `pg/enum@1`, whose typeParams\n // describe the value set rather than a DDL suffix), fall back to the\n // bare native type rather than throwing. Throwing here would reject\n // every plan involving an enum-/values-typed column as soon as its\n // `typeRef` resolved to a `StorageTypeInstance` carrying typeParams.\n if (!input.codecId) return input.nativeType;\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) return input.nativeType;\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n migrations: {\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n return contractToSchemaIR(contract as Contract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n frameworkComponents: frameworkComponents ?? [],\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;AAuCA,MAAM,iBAA+B,EACnC,eAAe,UAChB;AAED,MAAM,cAAc;;;;;AAMpB,SAAS,qBAAwD,OAAa;CAC5E,MAAM,SAAkC,EAAE;CAC1C,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,MAAM,EAC5C,IAAI,QAAQ,QAAQ,QAAQ,KAAA,GAC1B,OAAO,OAAO;MACT,IAAI,MAAM,QAAQ,IAAI,EAE3B,OAAO,OAAO,OAAO,OAAO,CAAC,GAAG,IAAI,CAAC;MAChC,IAAI,OAAO,QAAQ,UAExB,OAAO,OAAO,qBAAqB,IAA+B;MAGlE,OAAO,OAAO;CAGlB,OAAO,OAAO,OAAO,OAAO;;AAG9B,SAAgB,8BACd,QACA,SAAgC,EAAE,EACa;CAC/C,OAAO,IAAI,wBAAwB,QAAQ;EAAE,GAAG;EAAgB,GAAG;EAAQ,CAAC;;AAG9E,IAAM,0BAAN,MAAuF;CAElE;CACA;CAFnB,YACE,QACA,QACA;EAFiB,KAAA,SAAA;EACA,KAAA,SAAA;;CAGnB,MAAM,QACJ,SACmC;EACnC,MAAM,SAAS,QAAQ,cAAc,KAAK,OAAO;EACjD,MAAM,SAAS,QAAQ;EACvB,MAAM,UAAU,GAAG,YAAY,GAAG;EAGlC,MAAM,mBAAmB,KAAK,qCAC5B,QAAQ,KAAK,aACb,QAAQ,oBACT;EACD,IAAI,CAAC,iBAAiB,IACpB,OAAO;EAGT,MAAM,cAAc,KAAK,2BAA2B,QAAQ,QAAQ,QAAQ,KAAK,WAAW;EAC5F,IAAI,CAAC,YAAY,IACf,OAAO;EAIT,MAAM,KAAK,iBAAiB,OAAO;EACnC,IAAI,YAAY;EAChB,IAAI;GACF,MAAM,KAAK,YAAY,QAAQ,QAAQ;GACvC,MAAM,eAAe,MAAM,KAAK,oBAA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ACf,qBAAqB,uBAAuB,EAAE;IAC/C,CAAC;;EAEL;CACD,SAAmD;EACjD,OAAO;GACL,UAAU;GACV,UAAU;GACX;;;;;;CAMH,cAAc,SAAmC;EAC/C,OAAO,gCAAgC;;;;;;CAMzC,aAAa,QAAQ;EACnB,OAAO,8BAA8B,OAAO;;CAE/C"}
|
|
1
|
+
{"version":3,"file":"control.mjs","names":[],"sources":["../src/core/migrations/runner.ts","../src/exports/control.ts"],"sourcesContent":["import type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n MultiSpaceRunnerResult,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n SqlMigrationRunnerSuccessValue,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { ControlDriverInstance } from '@prisma-next/framework-components/control';\nimport { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok, okVoid } from '@prisma-next/utils/result';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\nimport {\n buildLedgerInsertStatement,\n buildMergeMarkerStatements,\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 SqlMigrationPlanOperation<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): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(\n private readonly family: SqlControlFamilyInstance,\n private readonly config: RunnerConfig,\n ) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const driver = options.driver;\n\n // Static checks fail fast before any transaction work — no point\n // burning a BEGIN/ROLLBACK round-trip on a destination-contract\n // mismatch the caller can fix locally.\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) return destinationCheck;\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) return policyCheck;\n\n await this.beginTransaction(driver);\n let committed = false;\n try {\n const result = await this.executeOnConnection(options);\n if (!result.ok) {\n return result;\n }\n await this.commitTransaction(driver);\n committed = true;\n return result;\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n /**\n * Body of the migration runner without transaction management. The\n * caller (single-space `execute(...)` above, or the multi-space\n * outer-tx orchestrator at the SQL family level) owns the\n * `BEGIN`/`COMMIT`/`ROLLBACK` lifecycle.\n */\n async executeOnConnection(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema = options.schemaName ?? this.config.defaultSchema;\n const driver = options.driver;\n if (options.space !== undefined && options.space !== options.plan.spaceId) {\n throw new Error(\n `SqlMigrationRunner: options.space (${options.space}) does not match plan.spaceId (${options.plan.spaceId})`,\n );\n }\n const space = options.plan.spaceId;\n const lockKey = `${LOCK_DOMAIN}:${schema}:${space}`;\n\n // Static checks (idempotent — safe to run again when the caller is\n // `execute(...)` because the cost is a single object comparison).\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) return destinationCheck;\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) return policyCheck;\n\n await this.acquireLock(driver, lockKey);\n const ensureResult = await this.ensureControlTables(driver);\n if (!ensureResult.ok) return ensureResult;\n const existingMarker = await this.family.readMarker({ driver, space });\n\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) return markerCheck;\n\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;\n const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) return applyResult;\n applyValue = applyResult.value;\n }\n\n // Schema verification on app-space only — extension spaces don't\n // own user-facing tables in the live schema, and `verifySqlSchema`\n // matches the destination contract against the database, which\n // would flag every app-space table as \"extra\" when called against\n // an extension contract.\n if (space === APP_SPACE_ID) {\n const schemaIR = await this.family.introspect({\n driver,\n contract: options.destinationContract,\n });\n const schemaVerifyResult = verifySqlSchema({\n contract: options.destinationContract,\n schema: schemaIR,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n typeMetadataRegistry: this.family.typeMetadataRegistry,\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\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: { issues: schemaVerifyResult.schema.issues },\n });\n }\n }\n\n const incomingInvariants = options.plan.providedInvariants ?? [];\n const existingInvariants = new Set(existingMarker?.invariants ?? []);\n const incomingIsSubsetOfExisting = incomingInvariants.every((id) => existingInvariants.has(id));\n const isSelfEdgeNoOp =\n isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting;\n\n if (!isSelfEdgeNoOp) {\n await this.upsertMarker(driver, options, existingMarker, space);\n await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);\n }\n\n return runnerSuccess({\n operationsPlanned: options.plan.operations.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n }\n\n async executeAcrossSpaces(options: {\n readonly driver: ControlDriverInstance<'sql', string>;\n readonly perSpaceOptions: ReadonlyArray<\n SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>\n >;\n }): Promise<MultiSpaceRunnerResult> {\n const driver = options.driver;\n const perSpaceOptions = options.perSpaceOptions;\n\n if (perSpaceOptions.length === 0) {\n return ok({ perSpaceResults: [] });\n }\n\n await this.beginTransaction(driver);\n let committed = false;\n try {\n const perSpaceResults: Array<{\n space: string;\n value: SqlMigrationRunnerSuccessValue;\n }> = [];\n for (const spaceOptions of perSpaceOptions) {\n const space = spaceOptions.space ?? spaceOptions.plan.spaceId;\n const result = await this.executeOnConnection({ ...spaceOptions, driver, space });\n if (!result.ok) {\n return notOk({ ...result.failure, failingSpace: space });\n }\n perSpaceResults.push({ space, value: result.value });\n }\n\n await this.commitTransaction(driver);\n committed = true;\n return ok({ perSpaceResults });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<Result<ApplyPlanSuccessValue, SqlMigrationRunnerFailure>> {\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false; // Default true\n const runPostchecks = checks?.postchecks !== false; // Default true\n const runIdempotency = checks?.idempotencyChecks !== false; // Default true\n\n let operationsExecuted = 0;\n const executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> = [];\n for (const operation of options.plan.operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n // Idempotency probe: only run if both postchecks and idempotency checks are enabled\n if (runPostchecks && runIdempotency) {\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\n // Prechecks: only run if enabled\n if (runPrechecks) {\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\n const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);\n if (!executeResult.ok) {\n return executeResult;\n }\n\n // Postchecks: only run if enabled\n if (runPostchecks) {\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\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: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n await this.executeStatement(driver, ensurePrismaContractSchemaStatement);\n // Pre-1.0 zero-range guardrail: detect a pre-cleanup single-row\n // marker table (no `space` column) and surface a structured failure\n // rather than silently auto-migrating it to the per-space shape.\n // See `specs/framework-mechanism.spec.md § 2`.\n const legacyDetection = await this.detectLegacyMarkerShape(driver);\n if (!legacyDetection.ok) {\n return legacyDetection;\n }\n await this.executeStatement(driver, ensureMarkerTableStatement);\n await this.executeStatement(driver, ensureLedgerTableStatement);\n return okVoid();\n }\n\n private async detectLegacyMarkerShape(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const result = await driver.query<{ column_name: string }>(\n `select column_name\n from information_schema.columns\n where table_schema = 'prisma_contract'\n and table_name = 'marker'`,\n );\n if (result.rows.length === 0) {\n return okVoid();\n }\n const columns = new Set(result.rows.map((row) => row.column_name));\n if (columns.has('space')) {\n return okVoid();\n }\n return runnerFailure(\n 'LEGACY_MARKER_SHAPE',\n 'Legacy marker-table shape detected on prisma_contract.marker (no `space` column). ' +\n 'Prisma Next is in pre-1.0; the previous transitional auto-migration to the per-space-row schema has been removed. ' +\n 'Drop `prisma_contract.marker` and re-run `dbInit` to reinitialise from a clean baseline.',\n {\n meta: {\n table: 'prisma_contract.marker',\n columns: [...columns].sort(),\n },\n },\n );\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n phase: 'precheck' | 'postcheck',\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n const result = await driver.query(step.sql, step.params ?? []);\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: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n try {\n await driver.query(step.sql, step.params ?? []);\n } catch (error: unknown) {\n // Catch SqlQueryError and include normalized metadata\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n // Let SqlConnectionError and other errors propagate (fail-fast)\n throw error;\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: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\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, step.params ?? []);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<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 ...ifDefined('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 ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\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 SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\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: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n // No origin assertion on the plan — the caller does not want origin validation.\n // This is the case for `db update`, which introspects the live schema and does not\n // rely on marker continuity. `db init` handles its own marker checks before the runner.\n return okVoid();\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n {\n meta: {\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\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: SqlMigrationPlanContractInfo,\n contract: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['destinationContract'],\n ): Result<void, SqlMigrationRunnerFailure> {\n if (destination.storageHash !== contract.storage.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storage.storageHash,\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: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n space: string,\n ): Promise<void> {\n const incomingInvariants = options.plan.providedInvariants ?? [];\n const writeStatements = buildMergeMarkerStatements({\n space,\n storageHash: options.plan.destination.storageHash,\n profileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJson: options.destinationContract,\n canonicalVersion: null,\n meta: {},\n invariants: incomingInvariants,\n });\n const statement = existingMarker ? writeStatements.update : writeStatements.insert;\n await this.executeStatement(driver, statement);\n }\n\n private async recordLedgerEntry(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Promise<void> {\n const ledgerStatement = buildLedgerInsertStatement({\n originStorageHash: existingMarker?.storageHash ?? null,\n originProfileHash: existingMarker?.profileHash ?? null,\n destinationStorageHash: options.plan.destination.storageHash,\n destinationProfileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\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: SqlMigrationRunnerExecuteOptions<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: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<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","import type { ColumnDefault, Contract } from '@prisma-next/contract/types';\nimport type {\n SqlControlFamilyInstance,\n SqlControlTargetDescriptor,\n} from '@prisma-next/family-sql/control';\nimport { contractToSchemaIR, extractCodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlTargetInstance,\n MigrationRunner,\n} from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nfunction buildNativeTypeExpander(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n if (!frameworkComponents) {\n return undefined;\n }\n const codecHooks = extractCodecControlHooks(frameworkComponents);\n return (input: {\n readonly nativeType: string;\n readonly codecId?: string;\n readonly typeParams?: Record<string, unknown>;\n }) => {\n if (!input.typeParams) return input.nativeType;\n // Mirror `renderExpectedNativeType` in verify-sql-schema: when a codec\n // has no `expandNativeType` hook (e.g. `pg/enum@1`, whose typeParams\n // describe the value set rather than a DDL suffix), fall back to the\n // bare native type rather than throwing. Throwing here would reject\n // every plan involving an enum-/values-typed column as soon as its\n // `typeRef` resolved to a `StorageTypeInstance` carrying typeParams.\n if (!input.codecId) return input.nativeType;\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) return input.nativeType;\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n migrations: {\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n return contractToSchemaIR(contract as Contract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n frameworkComponents: frameworkComponents ?? [],\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;AA2CA,MAAM,iBAA+B,EACnC,eAAe,UAChB;AAED,MAAM,cAAc;;;;;AAMpB,SAAS,qBAAwD,OAAa;CAC5E,MAAM,SAAkC,EAAE;CAC1C,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,MAAM,EAC5C,IAAI,QAAQ,QAAQ,QAAQ,KAAA,GAC1B,OAAO,OAAO;MACT,IAAI,MAAM,QAAQ,IAAI,EAE3B,OAAO,OAAO,OAAO,OAAO,CAAC,GAAG,IAAI,CAAC;MAChC,IAAI,OAAO,QAAQ,UAExB,OAAO,OAAO,qBAAqB,IAA+B;MAGlE,OAAO,OAAO;CAGlB,OAAO,OAAO,OAAO,OAAO;;AAG9B,SAAgB,8BACd,QACA,SAAgC,EAAE,EACa;CAC/C,OAAO,IAAI,wBAAwB,QAAQ;EAAE,GAAG;EAAgB,GAAG;EAAQ,CAAC;;AAG9E,IAAM,0BAAN,MAAuF;CAElE;CACA;CAFnB,YACE,QACA,QACA;EAFiB,KAAA,SAAA;EACA,KAAA,SAAA;;CAGnB,MAAM,QACJ,SACmC;EACnC,MAAM,SAAS,QAAQ;EAKvB,MAAM,mBAAmB,KAAK,qCAC5B,QAAQ,KAAK,aACb,QAAQ,oBACT;EACD,IAAI,CAAC,iBAAiB,IAAI,OAAO;EAEjC,MAAM,cAAc,KAAK,2BAA2B,QAAQ,QAAQ,QAAQ,KAAK,WAAW;EAC5F,IAAI,CAAC,YAAY,IAAI,OAAO;EAE5B,MAAM,KAAK,iBAAiB,OAAO;EACnC,IAAI,YAAY;EAChB,IAAI;GACF,MAAM,SAAS,MAAM,KAAK,oBAAoB,QAAQ;GACtD,IAAI,CAAC,OAAO,IACV,OAAO;GAET,MAAM,KAAK,kBAAkB,OAAO;GACpC,YAAY;G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rB,GAAG,UAAU,oBAHE,wBAAwB,oBAGE,CAAC;IAC1C,eAAe;IACf,qBAAqB,uBAAuB,EAAE;IAC/C,CAAC;;EAEL;CACD,SAAmD;EACjD,OAAO;GACL,UAAU;GACV,UAAU;GACX;;;;;;CAMH,cAAc,SAAmC;EAC/C,OAAO,gCAAgC;;;;;;CAMzC,aAAa,QAAQ;EACnB,OAAO,8BAA8B,OAAO;;CAE/C"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { t as parsePostgresDefault } from "./default-normalizer-C8XyZj85.mjs";
|
|
2
2
|
import { t as normalizeSchemaNativeType } from "./native-type-normalizer-Cry4QoLf.mjs";
|
|
3
|
+
import { b as RawSqlCall } from "./op-factory-call-Cq8s4Fz1.mjs";
|
|
3
4
|
import { n as postgresPlannerStrategies, t as planIssues } from "./issue-planner-B10B70JF.mjs";
|
|
4
5
|
import { t as TypeScriptRenderablePostgresMigration } from "./planner-produced-postgres-migration-Br3NgwpH.mjs";
|
|
5
|
-
import { extractCodecControlHooks, plannerFailure } from "@prisma-next/family-sql/control";
|
|
6
|
+
import { extractCodecControlHooks, planFieldEventOperations, plannerFailure } from "@prisma-next/family-sql/control";
|
|
6
7
|
import { verifySqlSchema } from "@prisma-next/family-sql/schema-verify";
|
|
7
8
|
//#region src/core/migrations/planner.ts
|
|
8
9
|
const DEFAULT_PLANNER_CONFIG = { defaultSchema: "public" };
|
|
@@ -62,9 +63,15 @@ var PostgresMigrationPlanner = class {
|
|
|
62
63
|
strategies: postgresPlannerStrategies
|
|
63
64
|
});
|
|
64
65
|
if (!result.ok) return plannerFailure(result.failure);
|
|
66
|
+
const fieldEventOps = planFieldEventOperations({
|
|
67
|
+
priorContract: options.fromContract,
|
|
68
|
+
newContract: options.contract,
|
|
69
|
+
codecHooks
|
|
70
|
+
});
|
|
71
|
+
const calls = [...result.value.calls, ...fieldEventOps.map((op) => new RawSqlCall(op))];
|
|
65
72
|
return Object.freeze({
|
|
66
73
|
kind: "success",
|
|
67
|
-
plan: new TypeScriptRenderablePostgresMigration(
|
|
74
|
+
plan: new TypeScriptRenderablePostgresMigration(calls, {
|
|
68
75
|
from: options.fromContract?.storage.storageHash ?? null,
|
|
69
76
|
to: options.contract.storage.storageHash
|
|
70
77
|
}, options.spaceId)
|
|
@@ -95,4 +102,4 @@ var PostgresMigrationPlanner = class {
|
|
|
95
102
|
//#endregion
|
|
96
103
|
export { createPostgresMigrationPlanner as t };
|
|
97
104
|
|
|
98
|
-
//# sourceMappingURL=planner-
|
|
105
|
+
//# sourceMappingURL=planner-JmqeNfGa.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"planner-8hkq9lQH.mjs","names":[],"sources":["../src/core/migrations/planner.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlMigrationPlannerPlanOptions,\n SqlPlannerFailureResult,\n} from '@prisma-next/family-sql/control';\nimport { extractCodecControlHooks, plannerFailure } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationPlanner,\n MigrationPlanWithAuthoringSurface,\n MigrationScaffoldContext,\n SchemaIssue,\n} from '@prisma-next/framework-components/control';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport { planIssues } from './issue-planner';\nimport { TypeScriptRenderablePostgresMigration } from './planner-produced-postgres-migration';\nimport { postgresPlannerStrategies } from './planner-strategies';\n\ntype PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {\n readonly frameworkComponents: infer T;\n}\n ? T\n : ReadonlyArray<unknown>;\n\ntype PlannerOptionsWithComponents = SqlMigrationPlannerPlanOptions & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype VerifySqlSchemaOptionsWithComponents = Parameters<typeof verifySqlSchema>[0] & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ninterface PlannerConfig {\n readonly defaultSchema: string;\n}\n\nconst DEFAULT_PLANNER_CONFIG: PlannerConfig = {\n defaultSchema: 'public',\n};\n\nexport function createPostgresMigrationPlanner(\n config: Partial<PlannerConfig> = {},\n): PostgresMigrationPlanner {\n return new PostgresMigrationPlanner({\n ...DEFAULT_PLANNER_CONFIG,\n ...config,\n });\n}\n\n/**\n * Result of `PostgresMigrationPlanner.plan()`. A discriminated union whose\n * success variant carries a `TypeScriptRenderablePostgresMigration` — a\n * migration object that both the CLI (via `renderTypeScript()`) and the\n * SQL-typed callers (via `operations`, `describe()`, etc.) consume\n * uniformly.\n */\nexport type PostgresPlanResult =\n | { readonly kind: 'success'; readonly plan: TypeScriptRenderablePostgresMigration }\n | SqlPlannerFailureResult;\n\n/**\n * Postgres migration planner — a thin wrapper over `planIssues`.\n *\n * `plan()` verifies the live schema against the target contract (producing\n * `SchemaIssue[]`) and delegates to `planIssues` with the unified\n * `postgresPlannerStrategies` list: enum-change, NOT-NULL backfill,\n * type-change, nullable-tightening, codec-hook storage types,\n * component-declared dependency installs, and shared-temp-default /\n * empty-table-guarded NOT-NULL add-column. The same strategy list runs for\n * `migration plan`, `db update`, and `db init`; behavior diverges purely on\n * `policy.allowedOperationClasses` (the data-safe strategies short-circuit\n * when `'data'` is excluded). The issue planner applies operation-class\n * policy gates and emits a single `PostgresOpFactoryCall[]` that drives both\n * the runtime-ops view (via `renderOps`) and the `renderTypeScript()`\n * authoring surface.\n */\nexport class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgres'> {\n constructor(private readonly config: PlannerConfig) {}\n\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n /**\n * The \"from\" contract (state the planner assumes the database starts\n * at), or `null` for reconciliation flows. Only `migration plan` ever\n * supplies a non-null value; `db update` / `db init` reconcile against\n * the live schema and pass `null`. When present alongside the\n * `'data'` operation class, strategies that need from/to column-shape\n * comparisons (unsafe type change, nullability tightening) activate.\n *\n * Typed as the framework `Contract | null` to satisfy the\n * `MigrationPlanner` interface contract; `planSql` narrows to the SQL\n * shape via `SqlMigrationPlannerPlanOptions`. Used to populate\n * `describe().from` on the produced plan as\n * `fromContract?.storage.storageHash ?? null`.\n */\n readonly fromContract: Contract | null;\n readonly schemaName?: string;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n /**\n * Contract space this plan applies to. Stamped onto the produced\n * {@link TypeScriptRenderablePostgresMigration.spaceId} so the runner keys\n * the marker row by the right space.\n */\n readonly spaceId: string;\n }): PostgresPlanResult {\n return this.planSql(options as SqlMigrationPlannerPlanOptions);\n }\n\n emptyMigration(\n context: MigrationScaffoldContext,\n spaceId: string,\n ): MigrationPlanWithAuthoringSurface {\n return new TypeScriptRenderablePostgresMigration(\n [],\n {\n from: context.fromHash,\n to: context.toHash,\n },\n spaceId,\n );\n }\n\n private planSql(options: SqlMigrationPlannerPlanOptions): PostgresPlanResult {\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 schemaIssues = this.collectSchemaIssues(options);\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n const storageTypes = options.contract.storage.types ?? {};\n\n const result = planIssues({\n issues: schemaIssues,\n toContract: options.contract,\n // `fromContract` is only supplied by `migration plan`. It is `null` for\n // `db update` / `db init`, which means data-safety strategies needing\n // from/to comparisons (unsafe type change, nullable tightening) are\n // inapplicable there — reconciliation falls through to\n // `mapIssueToCall`'s direct destructive handlers.\n fromContract: options.fromContract,\n schemaName,\n codecHooks,\n storageTypes,\n schema: options.schema,\n policy: options.policy,\n frameworkComponents: options.frameworkComponents,\n strategies: postgresPlannerStrategies,\n });\n\n if (!result.ok) {\n return plannerFailure(result.failure);\n }\n\n return Object.freeze({\n kind: 'success' as const,\n plan: new TypeScriptRenderablePostgresMigration(\n result.value.calls,\n {\n from: options.fromContract?.storage.storageHash ?? null,\n to: options.contract.storage.storageHash,\n },\n options.spaceId,\n ),\n });\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n private collectSchemaIssues(options: PlannerOptionsWithComponents): readonly SchemaIssue[] {\n // `db init` uses additive-only policy and intentionally ignores extra\n // schema objects. Any reconciliation-capable policy (widening or\n // destructive) must inspect extras to reconcile strict equality.\n const allowed = options.policy.allowedOperationClasses;\n const strict = allowed.includes('widening') || allowed.includes('destructive');\n const verifyOptions: VerifySqlSchemaOptionsWithComponents = {\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n };\n const verifyResult = verifySqlSchema(verifyOptions);\n return verifyResult.schema.issues;\n }\n}\n"],"mappings":";;;;;;;AAuCA,MAAM,yBAAwC,EAC5C,eAAe,UAChB;AAED,SAAgB,+BACd,SAAiC,EAAE,EACT;CAC1B,OAAO,IAAI,yBAAyB;EAClC,GAAG;EACH,GAAG;EACJ,CAAC;;;;;;;;;;;;;;;;;;AA8BJ,IAAa,2BAAb,MAAqF;CACtD;CAA7B,YAAY,QAAwC;EAAvB,KAAA,SAAA;;CAE7B,KAAK,SA2BkB;EACrB,OAAO,KAAK,QAAQ,QAA0C;;CAGhE,eACE,SACA,SACmC;EACnC,OAAO,IAAI,sCACT,EAAE,EACF;GACE,MAAM,QAAQ;GACd,IAAI,QAAQ;GACb,EACD,QACD;;CAGH,QAAgB,SAA6D;EAC3E,MAAM,aAAa,QAAQ,cAAc,KAAK,OAAO;EACrD,MAAM,eAAe,KAAK,qBAAqB,QAAQ,OAAO;EAC9D,IAAI,cACF,OAAO;EAGT,MAAM,eAAe,KAAK,oBAAoB,QAAQ;EACtD,MAAM,aAAa,yBAAyB,QAAQ,oBAAoB;EACxE,MAAM,eAAe,QAAQ,SAAS,QAAQ,SAAS,EAAE;EAEzD,MAAM,SAAS,WAAW;GACxB,QAAQ;GACR,YAAY,QAAQ;GAMpB,cAAc,QAAQ;GACtB;GACA;GACA;GACA,QAAQ,QAAQ;GAChB,QAAQ,QAAQ;GAChB,qBAAqB,QAAQ;GAC7B,YAAY;GACb,CAAC;EAEF,IAAI,CAAC,OAAO,IACV,OAAO,eAAe,OAAO,QAAQ;EAGvC,OAAO,OAAO,OAAO;GACnB,MAAM;GACN,MAAM,IAAI,sCACR,OAAO,MAAM,OACb;IACE,MAAM,QAAQ,cAAc,QAAQ,eAAe;IACnD,IAAI,QAAQ,SAAS,QAAQ;IAC9B,EACD,QAAQ,QACT;GACF,CAAC;;CAGJ,qBAA6B,QAAkC;EAC7D,IAAI,CAAC,OAAO,wBAAwB,SAAS,WAAW,EACtD,OAAO,eAAe,CACpB;GACE,MAAM;GACN,SAAS;GACT,KAAK;GACN,CACF,CAAC;EAEJ,OAAO;;CAGT,oBAA4B,SAA+D;EAIzF,MAAM,UAAU,QAAQ,OAAO;EAC/B,MAAM,SAAS,QAAQ,SAAS,WAAW,IAAI,QAAQ,SAAS,cAAc;EAW9E,OADqB,gBAAgB;GARnC,UAAU,QAAQ;GAClB,QAAQ,QAAQ;GAChB;GACA,sCAAsB,IAAI,KAAK;GAC/B,qBAAqB,QAAQ;GAC7B,kBAAkB;GAClB,qBAAqB;GAE2B,CAC/B,CAAC,OAAO"}
|
|
1
|
+
{"version":3,"file":"planner-JmqeNfGa.mjs","names":[],"sources":["../src/core/migrations/planner.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlMigrationPlannerPlanOptions,\n SqlMigrationPlanOperation,\n SqlPlannerFailureResult,\n} from '@prisma-next/family-sql/control';\nimport {\n extractCodecControlHooks,\n planFieldEventOperations,\n plannerFailure,\n} from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationPlanner,\n MigrationPlanWithAuthoringSurface,\n MigrationScaffoldContext,\n SchemaIssue,\n} from '@prisma-next/framework-components/control';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport { planIssues } from './issue-planner';\nimport { RawSqlCall } from './op-factory-call';\nimport { TypeScriptRenderablePostgresMigration } from './planner-produced-postgres-migration';\nimport { postgresPlannerStrategies } from './planner-strategies';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\n\ntype PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {\n readonly frameworkComponents: infer T;\n}\n ? T\n : ReadonlyArray<unknown>;\n\ntype PlannerOptionsWithComponents = SqlMigrationPlannerPlanOptions & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype VerifySqlSchemaOptionsWithComponents = Parameters<typeof verifySqlSchema>[0] & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ninterface PlannerConfig {\n readonly defaultSchema: string;\n}\n\nconst DEFAULT_PLANNER_CONFIG: PlannerConfig = {\n defaultSchema: 'public',\n};\n\nexport function createPostgresMigrationPlanner(\n config: Partial<PlannerConfig> = {},\n): PostgresMigrationPlanner {\n return new PostgresMigrationPlanner({\n ...DEFAULT_PLANNER_CONFIG,\n ...config,\n });\n}\n\n/**\n * Result of `PostgresMigrationPlanner.plan()`. A discriminated union whose\n * success variant carries a `TypeScriptRenderablePostgresMigration` — a\n * migration object that both the CLI (via `renderTypeScript()`) and the\n * SQL-typed callers (via `operations`, `describe()`, etc.) consume\n * uniformly.\n */\nexport type PostgresPlanResult =\n | { readonly kind: 'success'; readonly plan: TypeScriptRenderablePostgresMigration }\n | SqlPlannerFailureResult;\n\n/**\n * Postgres migration planner — a thin wrapper over `planIssues`.\n *\n * `plan()` verifies the live schema against the target contract (producing\n * `SchemaIssue[]`) and delegates to `planIssues` with the unified\n * `postgresPlannerStrategies` list: enum-change, NOT-NULL backfill,\n * type-change, nullable-tightening, codec-hook storage types,\n * component-declared dependency installs, and shared-temp-default /\n * empty-table-guarded NOT-NULL add-column. The same strategy list runs for\n * `migration plan`, `db update`, and `db init`; behavior diverges purely on\n * `policy.allowedOperationClasses` (the data-safe strategies short-circuit\n * when `'data'` is excluded). The issue planner applies operation-class\n * policy gates and emits a single `PostgresOpFactoryCall[]` that drives both\n * the runtime-ops view (via `renderOps`) and the `renderTypeScript()`\n * authoring surface.\n */\nexport class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgres'> {\n constructor(private readonly config: PlannerConfig) {}\n\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n /**\n * The \"from\" contract (state the planner assumes the database starts\n * at), or `null` for reconciliation flows. Only `migration plan` ever\n * supplies a non-null value; `db update` / `db init` reconcile against\n * the live schema and pass `null`. When present alongside the\n * `'data'` operation class, strategies that need from/to column-shape\n * comparisons (unsafe type change, nullability tightening) activate.\n *\n * Typed as the framework `Contract | null` to satisfy the\n * `MigrationPlanner` interface contract; `planSql` narrows to the SQL\n * shape via `SqlMigrationPlannerPlanOptions`. Used to populate\n * `describe().from` on the produced plan as\n * `fromContract?.storage.storageHash ?? null`.\n */\n readonly fromContract: Contract | null;\n readonly schemaName?: string;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n /**\n * Contract space this plan applies to. Stamped onto the produced\n * {@link TypeScriptRenderablePostgresMigration.spaceId} so the runner keys\n * the marker row by the right space.\n */\n readonly spaceId: string;\n }): PostgresPlanResult {\n return this.planSql(options as SqlMigrationPlannerPlanOptions);\n }\n\n emptyMigration(\n context: MigrationScaffoldContext,\n spaceId: string,\n ): MigrationPlanWithAuthoringSurface {\n return new TypeScriptRenderablePostgresMigration(\n [],\n {\n from: context.fromHash,\n to: context.toHash,\n },\n spaceId,\n );\n }\n\n private planSql(options: SqlMigrationPlannerPlanOptions): PostgresPlanResult {\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 schemaIssues = this.collectSchemaIssues(options);\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n const storageTypes = options.contract.storage.types ?? {};\n\n const result = planIssues({\n issues: schemaIssues,\n toContract: options.contract,\n // `fromContract` is only supplied by `migration plan`. It is `null` for\n // `db update` / `db init`, which means data-safety strategies needing\n // from/to comparisons (unsafe type change, nullable tightening) are\n // inapplicable there — reconciliation falls through to\n // `mapIssueToCall`'s direct destructive handlers.\n fromContract: options.fromContract,\n schemaName,\n codecHooks,\n storageTypes,\n schema: options.schema,\n policy: options.policy,\n frameworkComponents: options.frameworkComponents,\n strategies: postgresPlannerStrategies,\n });\n\n if (!result.ok) {\n return plannerFailure(result.failure);\n }\n\n // Inline `onFieldEvent`-emitted ops after structural DDL. The fixed\n // ordering is `structural → added → dropped → altered`, with\n // within-group sorting by `(tableName, fieldName)` so re-emits are\n // byte-stable. The hook fires only at the application emitter —\n // extension-space planning never reaches this helper.\n const fieldEventOps = planFieldEventOperations({\n priorContract: options.fromContract,\n newContract: options.contract,\n codecHooks,\n });\n // `extractCodecControlHooks` erases target-details to `unknown`; codec\n // authors target a specific lane (here, postgres) and produce ops whose\n // target-details are `PostgresPlanTargetDetails`-shaped by construction.\n // The cast re-specializes the type at this trust boundary.\n const calls = [\n ...result.value.calls,\n ...fieldEventOps.map(\n (op) => new RawSqlCall(op as SqlMigrationPlanOperation<PostgresPlanTargetDetails>),\n ),\n ];\n\n return Object.freeze({\n kind: 'success' as const,\n plan: new TypeScriptRenderablePostgresMigration(\n calls,\n {\n from: options.fromContract?.storage.storageHash ?? null,\n to: options.contract.storage.storageHash,\n },\n options.spaceId,\n ),\n });\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n private collectSchemaIssues(options: PlannerOptionsWithComponents): readonly SchemaIssue[] {\n // `db init` uses additive-only policy and intentionally ignores extra\n // schema objects. Any reconciliation-capable policy (widening or\n // destructive) must inspect extras to reconcile strict equality.\n const allowed = options.policy.allowedOperationClasses;\n const strict = allowed.includes('widening') || allowed.includes('destructive');\n const verifyOptions: VerifySqlSchemaOptionsWithComponents = {\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n };\n const verifyResult = verifySqlSchema(verifyOptions);\n return verifyResult.schema.issues;\n }\n}\n"],"mappings":";;;;;;;;AA8CA,MAAM,yBAAwC,EAC5C,eAAe,UAChB;AAED,SAAgB,+BACd,SAAiC,EAAE,EACT;CAC1B,OAAO,IAAI,yBAAyB;EAClC,GAAG;EACH,GAAG;EACJ,CAAC;;;;;;;;;;;;;;;;;;AA8BJ,IAAa,2BAAb,MAAqF;CACtD;CAA7B,YAAY,QAAwC;EAAvB,KAAA,SAAA;;CAE7B,KAAK,SA2BkB;EACrB,OAAO,KAAK,QAAQ,QAA0C;;CAGhE,eACE,SACA,SACmC;EACnC,OAAO,IAAI,sCACT,EAAE,EACF;GACE,MAAM,QAAQ;GACd,IAAI,QAAQ;GACb,EACD,QACD;;CAGH,QAAgB,SAA6D;EAC3E,MAAM,aAAa,QAAQ,cAAc,KAAK,OAAO;EACrD,MAAM,eAAe,KAAK,qBAAqB,QAAQ,OAAO;EAC9D,IAAI,cACF,OAAO;EAGT,MAAM,eAAe,KAAK,oBAAoB,QAAQ;EACtD,MAAM,aAA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;;;;;;
|
|
1
|
+
{"version":3,"file":"planner.d.mts","names":[],"sources":["../src/core/migrations/planner.ts"],"mappings":";;;;;;;UA0CU,aAAA;EAAA,SACC,aAAA;AAAA;AAAA,iBAOK,8BAAA,CACd,MAAA,GAAQ,OAAA,CAAQ,aAAA,IACf,wBAAA;;;;AAFH;;;;KAgBY,kBAAA;EAAA,SACG,IAAA;EAAA,SAA0B,IAAA,EAAM,qCAAA;AAAA,IAC3C,uBAAA;;;;;;;AAFJ;;;;;;;;;;cAoBa,wBAAA,YAAoC,gBAAA;EAAA,iBAClB,MAAA;cAAA,MAAA,EAAQ,aAAA;EAErC,IAAA,CAAK,OAAA;IAAA,SACM,QAAA;IAAA,SACA,MAAA;IAAA,SACA,MAAA,EAAQ,wBAAA;IAiBa;;;;;;;;;;;;;;IAAA,SAFrB,YAAA,EAAc,QAAA;IAAA,SACd,UAAA;IAAA,SACA,mBAAA,EAAqB,aAAA,CAAc,8BAAA;IAFnC;;;;;IAAA,SAQA,OAAA;EAAA,IACP,kBAAA;EAIJ,cAAA,CACE,OAAA,EAAS,wBAAA,EACT,OAAA,WACC,iCAAA;EAAA,QAWK,OAAA;EAAA,QAmEA,oBAAA;EAAA,QAaA,mBAAA;AAAA"}
|
package/dist/planner.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as createPostgresMigrationPlanner } from "./planner-
|
|
1
|
+
import { t as createPostgresMigrationPlanner } from "./planner-JmqeNfGa.mjs";
|
|
2
2
|
export { createPostgresMigrationPlanner };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { APP_SPACE_ID } from "@prisma-next/framework-components/control";
|
|
1
|
+
import { APP_SPACE_ID as APP_SPACE_ID$1 } from "@prisma-next/framework-components/control";
|
|
2
2
|
//#region src/core/migrations/statement-builders.ts
|
|
3
3
|
const ensurePrismaContractSchemaStatement = {
|
|
4
4
|
sql: "create schema if not exists prisma_contract",
|
|
@@ -15,7 +15,7 @@ const ensurePrismaContractSchemaStatement = {
|
|
|
15
15
|
*/
|
|
16
16
|
const ensureMarkerTableStatement = {
|
|
17
17
|
sql: `create table if not exists prisma_contract.marker (
|
|
18
|
-
space text not null primary key default '${APP_SPACE_ID}',
|
|
18
|
+
space text not null primary key default '${APP_SPACE_ID$1}',
|
|
19
19
|
core_hash text not null,
|
|
20
20
|
profile_hash text not null,
|
|
21
21
|
contract_json jsonb,
|
|
@@ -126,6 +126,6 @@ function jsonParam(value) {
|
|
|
126
126
|
return JSON.stringify(value ?? null);
|
|
127
127
|
}
|
|
128
128
|
//#endregion
|
|
129
|
-
export { ensureMarkerTableStatement as a, ensureLedgerTableStatement as i, buildLedgerInsertStatement as n, ensurePrismaContractSchemaStatement as o, buildMergeMarkerStatements as r, APP_SPACE_ID as t };
|
|
129
|
+
export { ensureMarkerTableStatement as a, ensureLedgerTableStatement as i, buildLedgerInsertStatement as n, ensurePrismaContractSchemaStatement as o, buildMergeMarkerStatements as r, APP_SPACE_ID$1 as t };
|
|
130
130
|
|
|
131
|
-
//# sourceMappingURL=statement-builders-
|
|
131
|
+
//# sourceMappingURL=statement-builders-BT889jV0.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"statement-builders-BT889jV0.mjs","names":["APP_SPACE_ID"],"sources":["../src/core/migrations/statement-builders.ts"],"sourcesContent":["import { APP_SPACE_ID } from '@prisma-next/framework-components/control';\n\nexport { APP_SPACE_ID };\n\nexport 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\n/**\n * Schema for `prisma_contract.marker`. The `space text` primary key\n * supports one row per loaded contract space (`'app'`,\n * `'<extension-id>'`, …); on a brand-new database `CREATE TABLE IF NOT\n * EXISTS` produces this shape directly. The migration runner detects\n * pre-1.0 single-row markers (no `space` column) at boot and fails with\n * a structured `LEGACY_MARKER_SHAPE` error rather than auto-migrating —\n * see `specs/framework-mechanism.spec.md § 2`.\n */\nexport const ensureMarkerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n space text not null primary key default '${APP_SPACE_ID}',\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 invariants text[] 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 MergeMarkerInput {\n /**\n * Logical space identifier for this marker row. Required at every\n * call site so the type system surfaces every place that needs to\n * thread the value (rather than letting an `?? APP_SPACE_ID`\n * fall-through silently collapse multi-space markers onto the\n * `'app'` row). App-plan callers pass {@link APP_SPACE_ID}\n * (`'app'`); per-extension callers (planner / runner / verifier\n * extensions over contract spaces) pass the extension's space id.\n */\n readonly space: string;\n readonly storageHash: 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 * Invariants to merge into `marker.invariants`. INSERT writes them as\n * the initial value (callers are expected to pass a sorted, deduped\n * array). UPDATE merges them with the existing column server-side via\n * a single atomic SQL expression.\n */\n readonly invariants: readonly string[];\n}\n\nexport function buildMergeMarkerStatements(input: MergeMarkerInput): {\n readonly insert: SqlStatement;\n readonly update: SqlStatement;\n} {\n const params: readonly unknown[] = [\n input.space,\n input.storageHash,\n input.profileHash,\n jsonParam(input.contractJson),\n input.canonicalVersion ?? null,\n input.appTag ?? null,\n jsonParam(input.meta ?? {}),\n input.invariants,\n ];\n\n return {\n insert: {\n sql: `insert into prisma_contract.marker (\n space,\n core_hash,\n profile_hash,\n contract_json,\n canonical_version,\n updated_at,\n app_tag,\n meta,\n invariants\n ) values (\n $1,\n $2,\n $3,\n $4::jsonb,\n $5,\n now(),\n $6,\n $7::jsonb,\n $8::text[]\n )`,\n params,\n },\n update: {\n // `invariants = array(select distinct unnest(invariants || $8::text[]) order by 1)`\n // reads the current column value under the UPDATE's row lock, unions\n // with the incoming array, dedupes, and sorts ascending — single\n // statement, atomic, no read-then-write window.\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 invariants = array(select distinct unnest(invariants || $8::text[]) order by 1)\n where space = $1`,\n params,\n },\n };\n}\n\nexport interface LedgerInsertInput {\n readonly originStorageHash?: string | null;\n readonly originProfileHash?: string | null;\n readonly destinationStorageHash: 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.originStorageHash ?? null,\n input.originProfileHash ?? null,\n input.destinationStorageHash,\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":";;AASA,MAAa,sCAAoD;CAC/D,KAAK;CACL,QAAQ,EAAE;CACX;;;;;;;;;;AAWD,MAAa,6BAA2C;CACtD,KAAK;+CACwCA,eAAa;;;;;;;;;;CAU1D,QAAQ,EAAE;CACX;AAED,MAAa,6BAA2C;CACtD,KAAK;;;;;;;;;;;CAWL,QAAQ,EAAE;CACX;AA4BD,SAAgB,2BAA2B,OAGzC;CACA,MAAM,SAA6B;EACjC,MAAM;EACN,MAAM;EACN,MAAM;EACN,UAAU,MAAM,aAAa;EAC7B,MAAM,oBAAoB;EAC1B,MAAM,UAAU;EAChB,UAAU,MAAM,QAAQ,EAAE,CAAC;EAC3B,MAAM;EACP;CAED,OAAO;EACL,QAAQ;GACN,KAAK;;;;;;;;;;;;;;;;;;;;;GAqBL;GACD;EACD,QAAQ;GAKN,KAAK;;;;;;;;;;GAUL;GACD;EACF;;AAaH,SAAgB,2BAA2B,OAAwC;CACjF,OAAO;EACL,KAAK;;;;;;;;;;;;;;;;;EAiBL,QAAQ;GACN,MAAM,qBAAqB;GAC3B,MAAM,qBAAqB;GAC3B,MAAM;GACN,MAAM,0BAA0B;GAChC,UAAU,MAAM,mBAAmB;GACnC,UAAU,MAAM,kBAAkB;GAClC,UAAU,MAAM,WAAW;GAC5B;EACF;;AAGH,SAAS,UAAU,OAAwB;CACzC,OAAO,KAAK,UAAU,SAAS,KAAK"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as ensureMarkerTableStatement, i as ensureLedgerTableStatement, o as ensurePrismaContractSchemaStatement, r as buildMergeMarkerStatements, t as APP_SPACE_ID } from "./statement-builders-
|
|
1
|
+
import { a as ensureMarkerTableStatement, i as ensureLedgerTableStatement, o as ensurePrismaContractSchemaStatement, r as buildMergeMarkerStatements, t as APP_SPACE_ID } from "./statement-builders-BT889jV0.mjs";
|
|
2
2
|
export { APP_SPACE_ID, buildMergeMarkerStatements, ensureLedgerTableStatement, ensureMarkerTableStatement, ensurePrismaContractSchemaStatement };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/target-postgres",
|
|
3
|
-
"version": "0.5.0-dev.
|
|
3
|
+
"version": "0.5.0-dev.68",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -9,19 +9,19 @@
|
|
|
9
9
|
"@standard-schema/spec": "^1.1.0",
|
|
10
10
|
"arktype": "^2.1.29",
|
|
11
11
|
"pathe": "^2.0.3",
|
|
12
|
-
"@prisma-next/cli": "0.5.0-dev.
|
|
13
|
-
"@prisma-next/errors": "0.5.0-dev.
|
|
14
|
-
"@prisma-next/family-sql": "0.5.0-dev.
|
|
15
|
-
"@prisma-next/contract": "0.5.0-dev.
|
|
16
|
-
"@prisma-next/
|
|
17
|
-
"@prisma-next/
|
|
18
|
-
"@prisma-next/sql-contract": "0.5.0-dev.
|
|
19
|
-
"@prisma-next/ts-render": "0.5.0-dev.
|
|
20
|
-
"@prisma-next/sql-errors": "0.5.0-dev.
|
|
21
|
-
"@prisma-next/sql-
|
|
22
|
-
"@prisma-next/sql-
|
|
23
|
-
"@prisma-next/
|
|
24
|
-
"@prisma-next/
|
|
12
|
+
"@prisma-next/cli": "0.5.0-dev.68",
|
|
13
|
+
"@prisma-next/errors": "0.5.0-dev.68",
|
|
14
|
+
"@prisma-next/family-sql": "0.5.0-dev.68",
|
|
15
|
+
"@prisma-next/contract": "0.5.0-dev.68",
|
|
16
|
+
"@prisma-next/migration-tools": "0.5.0-dev.68",
|
|
17
|
+
"@prisma-next/framework-components": "0.5.0-dev.68",
|
|
18
|
+
"@prisma-next/sql-contract": "0.5.0-dev.68",
|
|
19
|
+
"@prisma-next/ts-render": "0.5.0-dev.68",
|
|
20
|
+
"@prisma-next/sql-errors": "0.5.0-dev.68",
|
|
21
|
+
"@prisma-next/sql-relational-core": "0.5.0-dev.68",
|
|
22
|
+
"@prisma-next/sql-schema-ir": "0.5.0-dev.68",
|
|
23
|
+
"@prisma-next/utils": "0.5.0-dev.68",
|
|
24
|
+
"@prisma-next/sql-operations": "0.5.0-dev.68"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"tsdown": "0.22.0",
|
|
@@ -2,9 +2,14 @@ import type { Contract } from '@prisma-next/contract/types';
|
|
|
2
2
|
import type {
|
|
3
3
|
MigrationOperationPolicy,
|
|
4
4
|
SqlMigrationPlannerPlanOptions,
|
|
5
|
+
SqlMigrationPlanOperation,
|
|
5
6
|
SqlPlannerFailureResult,
|
|
6
7
|
} from '@prisma-next/family-sql/control';
|
|
7
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
extractCodecControlHooks,
|
|
10
|
+
planFieldEventOperations,
|
|
11
|
+
plannerFailure,
|
|
12
|
+
} from '@prisma-next/family-sql/control';
|
|
8
13
|
import { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';
|
|
9
14
|
import type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';
|
|
10
15
|
import type {
|
|
@@ -16,8 +21,10 @@ import type {
|
|
|
16
21
|
import { parsePostgresDefault } from '../default-normalizer';
|
|
17
22
|
import { normalizeSchemaNativeType } from '../native-type-normalizer';
|
|
18
23
|
import { planIssues } from './issue-planner';
|
|
24
|
+
import { RawSqlCall } from './op-factory-call';
|
|
19
25
|
import { TypeScriptRenderablePostgresMigration } from './planner-produced-postgres-migration';
|
|
20
26
|
import { postgresPlannerStrategies } from './planner-strategies';
|
|
27
|
+
import type { PostgresPlanTargetDetails } from './planner-target-details';
|
|
21
28
|
|
|
22
29
|
type PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {
|
|
23
30
|
readonly frameworkComponents: infer T;
|
|
@@ -158,10 +165,31 @@ export class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgr
|
|
|
158
165
|
return plannerFailure(result.failure);
|
|
159
166
|
}
|
|
160
167
|
|
|
168
|
+
// Inline `onFieldEvent`-emitted ops after structural DDL. The fixed
|
|
169
|
+
// ordering is `structural → added → dropped → altered`, with
|
|
170
|
+
// within-group sorting by `(tableName, fieldName)` so re-emits are
|
|
171
|
+
// byte-stable. The hook fires only at the application emitter —
|
|
172
|
+
// extension-space planning never reaches this helper.
|
|
173
|
+
const fieldEventOps = planFieldEventOperations({
|
|
174
|
+
priorContract: options.fromContract,
|
|
175
|
+
newContract: options.contract,
|
|
176
|
+
codecHooks,
|
|
177
|
+
});
|
|
178
|
+
// `extractCodecControlHooks` erases target-details to `unknown`; codec
|
|
179
|
+
// authors target a specific lane (here, postgres) and produce ops whose
|
|
180
|
+
// target-details are `PostgresPlanTargetDetails`-shaped by construction.
|
|
181
|
+
// The cast re-specializes the type at this trust boundary.
|
|
182
|
+
const calls = [
|
|
183
|
+
...result.value.calls,
|
|
184
|
+
...fieldEventOps.map(
|
|
185
|
+
(op) => new RawSqlCall(op as SqlMigrationPlanOperation<PostgresPlanTargetDetails>),
|
|
186
|
+
),
|
|
187
|
+
];
|
|
188
|
+
|
|
161
189
|
return Object.freeze({
|
|
162
190
|
kind: 'success' as const,
|
|
163
191
|
plan: new TypeScriptRenderablePostgresMigration(
|
|
164
|
-
|
|
192
|
+
calls,
|
|
165
193
|
{
|
|
166
194
|
from: options.fromContract?.storage.storageHash ?? null,
|
|
167
195
|
to: options.contract.storage.storageHash,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ContractMarkerRecord } from '@prisma-next/contract/types';
|
|
2
2
|
import type {
|
|
3
3
|
MigrationOperationPolicy,
|
|
4
|
+
MultiSpaceRunnerResult,
|
|
4
5
|
SqlControlFamilyInstance,
|
|
5
6
|
SqlMigrationPlanContractInfo,
|
|
6
7
|
SqlMigrationPlanOperation,
|
|
@@ -9,13 +10,16 @@ import type {
|
|
|
9
10
|
SqlMigrationRunnerExecuteOptions,
|
|
10
11
|
SqlMigrationRunnerFailure,
|
|
11
12
|
SqlMigrationRunnerResult,
|
|
13
|
+
SqlMigrationRunnerSuccessValue,
|
|
12
14
|
} from '@prisma-next/family-sql/control';
|
|
13
15
|
import { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';
|
|
14
16
|
import { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';
|
|
17
|
+
import type { ControlDriverInstance } from '@prisma-next/framework-components/control';
|
|
18
|
+
import { APP_SPACE_ID } from '@prisma-next/framework-components/control';
|
|
15
19
|
import { SqlQueryError } from '@prisma-next/sql-errors';
|
|
16
20
|
import { ifDefined } from '@prisma-next/utils/defined';
|
|
17
21
|
import type { Result } from '@prisma-next/utils/result';
|
|
18
|
-
import { ok, okVoid } from '@prisma-next/utils/result';
|
|
22
|
+
import { notOk, ok, okVoid } from '@prisma-next/utils/result';
|
|
19
23
|
import { parsePostgresDefault } from '../default-normalizer';
|
|
20
24
|
import { normalizeSchemaNativeType } from '../native-type-normalizer';
|
|
21
25
|
import type { PostgresPlanTargetDetails } from './planner-target-details';
|
|
@@ -82,72 +86,98 @@ class PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDe
|
|
|
82
86
|
async execute(
|
|
83
87
|
options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,
|
|
84
88
|
): Promise<SqlMigrationRunnerResult> {
|
|
85
|
-
const schema = options.schemaName ?? this.config.defaultSchema;
|
|
86
89
|
const driver = options.driver;
|
|
87
|
-
const lockKey = `${LOCK_DOMAIN}:${schema}`;
|
|
88
90
|
|
|
89
|
-
// Static checks
|
|
91
|
+
// Static checks fail fast before any transaction work — no point
|
|
92
|
+
// burning a BEGIN/ROLLBACK round-trip on a destination-contract
|
|
93
|
+
// mismatch the caller can fix locally.
|
|
90
94
|
const destinationCheck = this.ensurePlanMatchesDestinationContract(
|
|
91
95
|
options.plan.destination,
|
|
92
96
|
options.destinationContract,
|
|
93
97
|
);
|
|
94
|
-
if (!destinationCheck.ok)
|
|
95
|
-
return destinationCheck;
|
|
96
|
-
}
|
|
98
|
+
if (!destinationCheck.ok) return destinationCheck;
|
|
97
99
|
|
|
98
100
|
const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);
|
|
99
|
-
if (!policyCheck.ok)
|
|
100
|
-
return policyCheck;
|
|
101
|
-
}
|
|
101
|
+
if (!policyCheck.ok) return policyCheck;
|
|
102
102
|
|
|
103
|
-
// Begin transaction for DB operations
|
|
104
103
|
await this.beginTransaction(driver);
|
|
105
104
|
let committed = false;
|
|
106
105
|
try {
|
|
107
|
-
await this.
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
return ensureResult;
|
|
106
|
+
const result = await this.executeOnConnection(options);
|
|
107
|
+
if (!result.ok) {
|
|
108
|
+
return result;
|
|
111
109
|
}
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);
|
|
119
|
-
if (!markerCheck.ok) {
|
|
120
|
-
return markerCheck;
|
|
110
|
+
await this.commitTransaction(driver);
|
|
111
|
+
committed = true;
|
|
112
|
+
return result;
|
|
113
|
+
} finally {
|
|
114
|
+
if (!committed) {
|
|
115
|
+
await this.rollbackTransaction(driver);
|
|
121
116
|
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
122
119
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
120
|
+
/**
|
|
121
|
+
* Body of the migration runner without transaction management. The
|
|
122
|
+
* caller (single-space `execute(...)` above, or the multi-space
|
|
123
|
+
* outer-tx orchestrator at the SQL family level) owns the
|
|
124
|
+
* `BEGIN`/`COMMIT`/`ROLLBACK` lifecycle.
|
|
125
|
+
*/
|
|
126
|
+
async executeOnConnection(
|
|
127
|
+
options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,
|
|
128
|
+
): Promise<SqlMigrationRunnerResult> {
|
|
129
|
+
const schema = options.schemaName ?? this.config.defaultSchema;
|
|
130
|
+
const driver = options.driver;
|
|
131
|
+
if (options.space !== undefined && options.space !== options.plan.spaceId) {
|
|
132
|
+
throw new Error(
|
|
133
|
+
`SqlMigrationRunner: options.space (${options.space}) does not match plan.spaceId (${options.plan.spaceId})`,
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
const space = options.plan.spaceId;
|
|
137
|
+
const lockKey = `${LOCK_DOMAIN}:${schema}:${space}`;
|
|
138
|
+
|
|
139
|
+
// Static checks (idempotent — safe to run again when the caller is
|
|
140
|
+
// `execute(...)` because the cost is a single object comparison).
|
|
141
|
+
const destinationCheck = this.ensurePlanMatchesDestinationContract(
|
|
142
|
+
options.plan.destination,
|
|
143
|
+
options.destinationContract,
|
|
144
|
+
);
|
|
145
|
+
if (!destinationCheck.ok) return destinationCheck;
|
|
146
|
+
|
|
147
|
+
const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);
|
|
148
|
+
if (!policyCheck.ok) return policyCheck;
|
|
142
149
|
|
|
143
|
-
|
|
144
|
-
|
|
150
|
+
await this.acquireLock(driver, lockKey);
|
|
151
|
+
const ensureResult = await this.ensureControlTables(driver);
|
|
152
|
+
if (!ensureResult.ok) return ensureResult;
|
|
153
|
+
const existingMarker = await this.family.readMarker({ driver, space });
|
|
154
|
+
|
|
155
|
+
const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);
|
|
156
|
+
if (!markerCheck.ok) return markerCheck;
|
|
157
|
+
|
|
158
|
+
const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);
|
|
159
|
+
const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;
|
|
160
|
+
const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;
|
|
161
|
+
let applyValue: ApplyPlanSuccessValue;
|
|
162
|
+
|
|
163
|
+
if (skipOperations) {
|
|
164
|
+
applyValue = { operationsExecuted: 0, executedOperations: [] };
|
|
165
|
+
} else {
|
|
166
|
+
const applyResult = await this.applyPlan(driver, options);
|
|
167
|
+
if (!applyResult.ok) return applyResult;
|
|
168
|
+
applyValue = applyResult.value;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Schema verification on app-space only — extension spaces don't
|
|
172
|
+
// own user-facing tables in the live schema, and `verifySqlSchema`
|
|
173
|
+
// matches the destination contract against the database, which
|
|
174
|
+
// would flag every app-space table as "extra" when called against
|
|
175
|
+
// an extension contract.
|
|
176
|
+
if (space === APP_SPACE_ID) {
|
|
145
177
|
const schemaIR = await this.family.introspect({
|
|
146
178
|
driver,
|
|
147
179
|
contract: options.destinationContract,
|
|
148
180
|
});
|
|
149
|
-
|
|
150
|
-
// Step 2: Pure verification (no DB I/O)
|
|
151
181
|
const schemaVerifyResult = verifySqlSchema({
|
|
152
182
|
contract: options.destinationContract,
|
|
153
183
|
schema: schemaIR,
|
|
@@ -161,47 +191,60 @@ class PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDe
|
|
|
161
191
|
if (!schemaVerifyResult.ok) {
|
|
162
192
|
return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {
|
|
163
193
|
why: 'The resulting database schema does not satisfy the destination contract.',
|
|
164
|
-
meta: {
|
|
165
|
-
issues: schemaVerifyResult.schema.issues,
|
|
166
|
-
},
|
|
194
|
+
meta: { issues: schemaVerifyResult.schema.issues },
|
|
167
195
|
});
|
|
168
196
|
}
|
|
197
|
+
}
|
|
169
198
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
199
|
+
const incomingInvariants = options.plan.providedInvariants ?? [];
|
|
200
|
+
const existingInvariants = new Set(existingMarker?.invariants ?? []);
|
|
201
|
+
const incomingIsSubsetOfExisting = incomingInvariants.every((id) => existingInvariants.has(id));
|
|
202
|
+
const isSelfEdgeNoOp =
|
|
203
|
+
isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting;
|
|
204
|
+
|
|
205
|
+
if (!isSelfEdgeNoOp) {
|
|
206
|
+
await this.upsertMarker(driver, options, existingMarker, space);
|
|
207
|
+
await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return runnerSuccess({
|
|
211
|
+
operationsPlanned: options.plan.operations.length,
|
|
212
|
+
operationsExecuted: applyValue.operationsExecuted,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async executeAcrossSpaces(options: {
|
|
217
|
+
readonly driver: ControlDriverInstance<'sql', string>;
|
|
218
|
+
readonly perSpaceOptions: ReadonlyArray<
|
|
219
|
+
SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>
|
|
220
|
+
>;
|
|
221
|
+
}): Promise<MultiSpaceRunnerResult> {
|
|
222
|
+
const driver = options.driver;
|
|
223
|
+
const perSpaceOptions = options.perSpaceOptions;
|
|
224
|
+
|
|
225
|
+
if (perSpaceOptions.length === 0) {
|
|
226
|
+
return ok({ perSpaceResults: [] });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
await this.beginTransaction(driver);
|
|
230
|
+
let committed = false;
|
|
231
|
+
try {
|
|
232
|
+
const perSpaceResults: Array<{
|
|
233
|
+
space: string;
|
|
234
|
+
value: SqlMigrationRunnerSuccessValue;
|
|
235
|
+
}> = [];
|
|
236
|
+
for (const spaceOptions of perSpaceOptions) {
|
|
237
|
+
const space = spaceOptions.space ?? spaceOptions.plan.spaceId;
|
|
238
|
+
const result = await this.executeOnConnection({ ...spaceOptions, driver, space });
|
|
239
|
+
if (!result.ok) {
|
|
240
|
+
return notOk({ ...result.failure, failingSpace: space });
|
|
241
|
+
}
|
|
242
|
+
perSpaceResults.push({ space, value: result.value });
|
|
197
243
|
}
|
|
198
244
|
|
|
199
245
|
await this.commitTransaction(driver);
|
|
200
246
|
committed = true;
|
|
201
|
-
return
|
|
202
|
-
operationsPlanned: options.plan.operations.length,
|
|
203
|
-
operationsExecuted: applyValue.operationsExecuted,
|
|
204
|
-
});
|
|
247
|
+
return ok({ perSpaceResults });
|
|
205
248
|
} finally {
|
|
206
249
|
if (!committed) {
|
|
207
250
|
await this.rollbackTransaction(driver);
|
|
@@ -590,10 +633,11 @@ class PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDe
|
|
|
590
633
|
driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],
|
|
591
634
|
options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,
|
|
592
635
|
existingMarker: ContractMarkerRecord | null,
|
|
636
|
+
space: string,
|
|
593
637
|
): Promise<void> {
|
|
594
638
|
const incomingInvariants = options.plan.providedInvariants ?? [];
|
|
595
639
|
const writeStatements = buildMergeMarkerStatements({
|
|
596
|
-
space
|
|
640
|
+
space,
|
|
597
641
|
storageHash: options.plan.destination.storageHash,
|
|
598
642
|
profileHash:
|
|
599
643
|
options.plan.destination.profileHash ??
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"statement-builders-Dsix6Dl5.mjs","names":[],"sources":["../src/core/migrations/statement-builders.ts"],"sourcesContent":["import { APP_SPACE_ID } from '@prisma-next/framework-components/control';\n\nexport { APP_SPACE_ID };\n\nexport 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\n/**\n * Schema for `prisma_contract.marker`. The `space text` primary key\n * supports one row per loaded contract space (`'app'`,\n * `'<extension-id>'`, …); on a brand-new database `CREATE TABLE IF NOT\n * EXISTS` produces this shape directly. The migration runner detects\n * pre-1.0 single-row markers (no `space` column) at boot and fails with\n * a structured `LEGACY_MARKER_SHAPE` error rather than auto-migrating —\n * see `specs/framework-mechanism.spec.md § 2`.\n */\nexport const ensureMarkerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n space text not null primary key default '${APP_SPACE_ID}',\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 invariants text[] 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 MergeMarkerInput {\n /**\n * Logical space identifier for this marker row. Required at every\n * call site so the type system surfaces every place that needs to\n * thread the value (rather than letting an `?? APP_SPACE_ID`\n * fall-through silently collapse multi-space markers onto the\n * `'app'` row). App-plan callers pass {@link APP_SPACE_ID}\n * (`'app'`); per-extension callers (planner / runner / verifier\n * extensions over contract spaces) pass the extension's space id.\n */\n readonly space: string;\n readonly storageHash: 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 * Invariants to merge into `marker.invariants`. INSERT writes them as\n * the initial value (callers are expected to pass a sorted, deduped\n * array). UPDATE merges them with the existing column server-side via\n * a single atomic SQL expression.\n */\n readonly invariants: readonly string[];\n}\n\nexport function buildMergeMarkerStatements(input: MergeMarkerInput): {\n readonly insert: SqlStatement;\n readonly update: SqlStatement;\n} {\n const params: readonly unknown[] = [\n input.space,\n input.storageHash,\n input.profileHash,\n jsonParam(input.contractJson),\n input.canonicalVersion ?? null,\n input.appTag ?? null,\n jsonParam(input.meta ?? {}),\n input.invariants,\n ];\n\n return {\n insert: {\n sql: `insert into prisma_contract.marker (\n space,\n core_hash,\n profile_hash,\n contract_json,\n canonical_version,\n updated_at,\n app_tag,\n meta,\n invariants\n ) values (\n $1,\n $2,\n $3,\n $4::jsonb,\n $5,\n now(),\n $6,\n $7::jsonb,\n $8::text[]\n )`,\n params,\n },\n update: {\n // `invariants = array(select distinct unnest(invariants || $8::text[]) order by 1)`\n // reads the current column value under the UPDATE's row lock, unions\n // with the incoming array, dedupes, and sorts ascending — single\n // statement, atomic, no read-then-write window.\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 invariants = array(select distinct unnest(invariants || $8::text[]) order by 1)\n where space = $1`,\n params,\n },\n };\n}\n\nexport interface LedgerInsertInput {\n readonly originStorageHash?: string | null;\n readonly originProfileHash?: string | null;\n readonly destinationStorageHash: 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.originStorageHash ?? null,\n input.originProfileHash ?? null,\n input.destinationStorageHash,\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":";;AASA,MAAa,sCAAoD;CAC/D,KAAK;CACL,QAAQ,EAAE;CACX;;;;;;;;;;AAWD,MAAa,6BAA2C;CACtD,KAAK;+CACwC,aAAa;;;;;;;;;;CAU1D,QAAQ,EAAE;CACX;AAED,MAAa,6BAA2C;CACtD,KAAK;;;;;;;;;;;CAWL,QAAQ,EAAE;CACX;AA4BD,SAAgB,2BAA2B,OAGzC;CACA,MAAM,SAA6B;EACjC,MAAM;EACN,MAAM;EACN,MAAM;EACN,UAAU,MAAM,aAAa;EAC7B,MAAM,oBAAoB;EAC1B,MAAM,UAAU;EAChB,UAAU,MAAM,QAAQ,EAAE,CAAC;EAC3B,MAAM;EACP;CAED,OAAO;EACL,QAAQ;GACN,KAAK;;;;;;;;;;;;;;;;;;;;;GAqBL;GACD;EACD,QAAQ;GAKN,KAAK;;;;;;;;;;GAUL;GACD;EACF;;AAaH,SAAgB,2BAA2B,OAAwC;CACjF,OAAO;EACL,KAAK;;;;;;;;;;;;;;;;;EAiBL,QAAQ;GACN,MAAM,qBAAqB;GAC3B,MAAM,qBAAqB;GAC3B,MAAM;GACN,MAAM,0BAA0B;GAChC,UAAU,MAAM,mBAAmB;GACnC,UAAU,MAAM,kBAAkB;GAClC,UAAU,MAAM,WAAW;GAC5B;EACF;;AAGH,SAAS,UAAU,OAAwB;CACzC,OAAO,KAAK,UAAU,SAAS,KAAK"}
|