@prisma-next/target-postgres 0.12.0 → 0.13.0-dev.1

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.
Files changed (207) hide show
  1. package/dist/{codec-ids-D9fJ4HP5.d.mts → codec-ids-B1vOchLE.d.mts} +3 -2
  2. package/dist/codec-ids-B1vOchLE.d.mts.map +1 -0
  3. package/dist/{codec-ids-C5qzBqus.mjs → codec-ids-CTikp1if.mjs} +3 -2
  4. package/dist/codec-ids-CTikp1if.mjs.map +1 -0
  5. package/dist/codec-ids.d.mts +2 -2
  6. package/dist/codec-ids.mjs +2 -2
  7. package/dist/{codec-types-CRlHq7Cz.d.mts → codec-types-CnFiNML4.d.mts} +8 -9
  8. package/dist/codec-types-CnFiNML4.d.mts.map +1 -0
  9. package/dist/codec-types.d.mts +2 -2
  10. package/dist/{codecs-Dud5KDNk.d.mts → codecs-CBpEv4s5.d.mts} +33 -35
  11. package/dist/codecs-CBpEv4s5.d.mts.map +1 -0
  12. package/dist/codecs.d.mts +1 -1
  13. package/dist/codecs.mjs +37 -2
  14. package/dist/codecs.mjs.map +1 -1
  15. package/dist/contract-free.d.mts +80 -0
  16. package/dist/contract-free.d.mts.map +1 -0
  17. package/dist/contract-free.mjs +117 -0
  18. package/dist/contract-free.mjs.map +1 -0
  19. package/dist/control.d.mts +1 -1
  20. package/dist/control.d.mts.map +1 -1
  21. package/dist/control.mjs +66 -40
  22. package/dist/control.mjs.map +1 -1
  23. package/dist/{data-transform-CdtGUWp2.mjs → data-transform-D25tLeYU.mjs} +1 -1
  24. package/dist/{data-transform-CdtGUWp2.mjs.map → data-transform-D25tLeYU.mjs.map} +1 -1
  25. package/dist/{data-transform-bmOKkygi.d.mts → data-transform-DGOqcLrf.d.mts} +2 -2
  26. package/dist/{data-transform-bmOKkygi.d.mts.map → data-transform-DGOqcLrf.d.mts.map} +1 -1
  27. package/dist/data-transform.d.mts +1 -1
  28. package/dist/data-transform.mjs +1 -1
  29. package/dist/ddl-77SyXgFt.mjs +30 -0
  30. package/dist/ddl-77SyXgFt.mjs.map +1 -0
  31. package/dist/ddl.d.mts +2 -0
  32. package/dist/ddl.mjs +2 -0
  33. package/dist/{default-normalizer-CRscvhS5.mjs → default-normalizer-DyyCHQWs.mjs} +1 -1
  34. package/dist/{default-normalizer-CRscvhS5.mjs.map → default-normalizer-DyyCHQWs.mjs.map} +1 -1
  35. package/dist/default-normalizer.mjs +1 -1
  36. package/dist/descriptor-meta-DKmj-IMN.mjs +14 -0
  37. package/dist/descriptor-meta-DKmj-IMN.mjs.map +1 -0
  38. package/dist/{descriptor-meta-DLA2xV6B.mjs → descriptor-meta-runtime-My8_s4cs.mjs} +82 -78
  39. package/dist/descriptor-meta-runtime-My8_s4cs.mjs.map +1 -0
  40. package/dist/{enum-planning-Dz0Ye3Lb.mjs → enum-planning-BCyvlFHk.mjs} +0 -0
  41. package/dist/{enum-planning-Dz0Ye3Lb.mjs.map → enum-planning-BCyvlFHk.mjs.map} +1 -1
  42. package/dist/enum-planning.d.mts +1 -1
  43. package/dist/enum-planning.mjs +1 -1
  44. package/dist/{errors--zafB5_n.mjs → errors-CUk87ByX.mjs} +1 -1
  45. package/dist/{errors--zafB5_n.mjs.map → errors-CUk87ByX.mjs.map} +1 -1
  46. package/dist/errors.d.mts.map +1 -1
  47. package/dist/errors.mjs +1 -1
  48. package/dist/{issue-planner-ByQhUzS4.mjs → issue-planner-Br0pt1Ea.mjs} +130 -28
  49. package/dist/issue-planner-Br0pt1Ea.mjs.map +1 -0
  50. package/dist/issue-planner.d.mts +1 -1
  51. package/dist/issue-planner.d.mts.map +1 -1
  52. package/dist/issue-planner.mjs +1 -1
  53. package/dist/migration.d.mts +7 -8
  54. package/dist/migration.d.mts.map +1 -1
  55. package/dist/migration.mjs +5 -4
  56. package/dist/migration.mjs.map +1 -1
  57. package/dist/{native-type-normalizer-ClNPq__-.mjs → native-type-normalizer-Bc9XJzWC.mjs} +1 -1
  58. package/dist/{native-type-normalizer-ClNPq__-.mjs.map → native-type-normalizer-Bc9XJzWC.mjs.map} +1 -1
  59. package/dist/native-type-normalizer.mjs +1 -1
  60. package/dist/nodes-779hmCfL.d.mts +40 -0
  61. package/dist/nodes-779hmCfL.d.mts.map +1 -0
  62. package/dist/nodes-DZk2JZG3.mjs +47 -0
  63. package/dist/nodes-DZk2JZG3.mjs.map +1 -0
  64. package/dist/op-factory-call-D2aAUhmS.mjs +1307 -0
  65. package/dist/op-factory-call-D2aAUhmS.mjs.map +1 -0
  66. package/dist/{op-factory-call-Drccm_JD.d.mts → op-factory-call-DMA86_2D.d.mts} +39 -14
  67. package/dist/op-factory-call-DMA86_2D.d.mts.map +1 -0
  68. package/dist/op-factory-call.d.mts +2 -2
  69. package/dist/op-factory-call.mjs +2 -2
  70. package/dist/pack.d.mts +13 -12
  71. package/dist/pack.d.mts.map +1 -1
  72. package/dist/pack.mjs +1 -1
  73. package/dist/planner-CAYPJObw.mjs +344 -0
  74. package/dist/planner-CAYPJObw.mjs.map +1 -0
  75. package/dist/{planner-ddl-builders-BxRCSn_b.mjs → planner-ddl-builders-Cw2n2llW.mjs} +7 -30
  76. package/dist/planner-ddl-builders-Cw2n2llW.mjs.map +1 -0
  77. package/dist/planner-ddl-builders.d.mts +6 -7
  78. package/dist/planner-ddl-builders.d.mts.map +1 -1
  79. package/dist/planner-ddl-builders.mjs +2 -2
  80. package/dist/{planner-identity-values-ojX-6cPV.mjs → planner-identity-values-BIpa5p2I.mjs} +1 -1
  81. package/dist/{planner-identity-values-ojX-6cPV.mjs.map → planner-identity-values-BIpa5p2I.mjs.map} +1 -1
  82. package/dist/planner-identity-values.mjs +1 -1
  83. package/dist/{planner-produced-postgres-migration-p-VKkCia.d.mts → planner-produced-postgres-migration-B4EDvLdz.d.mts} +5 -4
  84. package/dist/planner-produced-postgres-migration-B4EDvLdz.d.mts.map +1 -0
  85. package/dist/{planner-produced-postgres-migration-N1yqYg20.mjs → planner-produced-postgres-migration-NSEhWL0L.mjs} +8 -6
  86. package/dist/planner-produced-postgres-migration-NSEhWL0L.mjs.map +1 -0
  87. package/dist/planner-produced-postgres-migration.d.mts +1 -1
  88. package/dist/planner-produced-postgres-migration.mjs +1 -1
  89. package/dist/{planner-schema-lookup-BGyukuzG.mjs → planner-schema-lookup-CiVaAQP-.mjs} +1 -1
  90. package/dist/{planner-schema-lookup-BGyukuzG.mjs.map → planner-schema-lookup-CiVaAQP-.mjs.map} +1 -1
  91. package/dist/planner-schema-lookup.mjs +1 -1
  92. package/dist/{planner-sql-checks-D3H-xOO1.mjs → planner-sql-checks-DAdhnI2c.mjs} +41 -30
  93. package/dist/planner-sql-checks-DAdhnI2c.mjs.map +1 -0
  94. package/dist/planner-sql-checks.d.mts.map +1 -1
  95. package/dist/planner-sql-checks.mjs +1 -1
  96. package/dist/{planner-target-details-CIj61DUj.d.mts → planner-target-details-CIY6tLeo.d.mts} +2 -2
  97. package/dist/planner-target-details-CIY6tLeo.d.mts.map +1 -0
  98. package/dist/planner-target-details.d.mts +2 -2
  99. package/dist/planner-type-resolution-836DExFN.mjs +20 -0
  100. package/dist/planner-type-resolution-836DExFN.mjs.map +1 -0
  101. package/dist/planner.d.mts +7 -3
  102. package/dist/planner.d.mts.map +1 -1
  103. package/dist/planner.mjs +1 -1
  104. package/dist/{postgres-contract-serializer-YJvjKrmo.mjs → postgres-contract-serializer-DYTyXjPf.mjs} +33 -24
  105. package/dist/postgres-contract-serializer-DYTyXjPf.mjs.map +1 -0
  106. package/dist/{postgres-enum-type-CNhPTDhy.d.mts → postgres-enum-type-BVn63a89.d.mts} +4 -1
  107. package/dist/postgres-enum-type-BVn63a89.d.mts.map +1 -0
  108. package/dist/{postgres-enum-type-DS-KLVRH.mjs → postgres-enum-type-DPKqCBem.mjs} +2 -1
  109. package/dist/postgres-enum-type-DPKqCBem.mjs.map +1 -0
  110. package/dist/{postgres-migration-uADmx0dW.mjs → postgres-migration-COore9Mz.mjs} +23 -3
  111. package/dist/postgres-migration-COore9Mz.mjs.map +1 -0
  112. package/dist/{postgres-migration-Fd4fQkBw.d.mts → postgres-migration-DZ_gLUOW.d.mts} +25 -3
  113. package/dist/postgres-migration-DZ_gLUOW.d.mts.map +1 -0
  114. package/dist/{postgres-schema-Bm7vjlOv.mjs → postgres-schema-BuxCxbvB.mjs} +29 -14
  115. package/dist/postgres-schema-BuxCxbvB.mjs.map +1 -0
  116. package/dist/{render-ops-BC2PtCkj.mjs → render-ops-BpjstrKQ.mjs} +4 -3
  117. package/dist/{render-ops-BC2PtCkj.mjs.map → render-ops-BpjstrKQ.mjs.map} +1 -1
  118. package/dist/render-ops.d.mts +3 -2
  119. package/dist/render-ops.d.mts.map +1 -1
  120. package/dist/render-ops.mjs +1 -1
  121. package/dist/{render-typescript-CPk7hhWH.mjs → render-typescript-KMgosran.mjs} +5 -2
  122. package/dist/render-typescript-KMgosran.mjs.map +1 -0
  123. package/dist/render-typescript.mjs +1 -1
  124. package/dist/runtime.d.mts.map +1 -1
  125. package/dist/runtime.mjs +3 -3
  126. package/dist/runtime.mjs.map +1 -1
  127. package/dist/{shared-ByhSooBS.d.mts → shared-DarONYBZ.d.mts} +5 -5
  128. package/dist/{shared-ByhSooBS.d.mts.map → shared-DarONYBZ.d.mts.map} +1 -1
  129. package/dist/{sql-utils-B_ruBD-M.mjs → sql-utils-DcfMz4MQ.mjs} +1 -1
  130. package/dist/{sql-utils-B_ruBD-M.mjs.map → sql-utils-DcfMz4MQ.mjs.map} +1 -1
  131. package/dist/sql-utils.mjs +1 -1
  132. package/dist/{types-D-XIpzHA.d.mts → types-BDKkx8MA.d.mts} +1 -1
  133. package/dist/types-BDKkx8MA.d.mts.map +1 -0
  134. package/dist/types.d.mts +16 -11
  135. package/dist/types.d.mts.map +1 -1
  136. package/dist/types.mjs +2 -2
  137. package/package.json +21 -20
  138. package/src/contract-free/columns.ts +49 -0
  139. package/src/contract-free/control-bootstrap.ts +55 -0
  140. package/src/contract-free/ddl.ts +37 -0
  141. package/src/core/ast/table-source.ts +23 -0
  142. package/src/core/authoring.ts +1 -1
  143. package/src/core/codec-ids.ts +1 -0
  144. package/src/core/codecs.ts +44 -0
  145. package/src/core/ddl/nodes.ts +72 -0
  146. package/src/core/descriptor-meta-runtime.ts +28 -0
  147. package/src/core/descriptor-meta.ts +3 -6
  148. package/src/core/migrations/control-policy.ts +234 -0
  149. package/src/core/migrations/issue-planner.ts +81 -13
  150. package/src/core/migrations/op-factory-call.ts +289 -46
  151. package/src/core/migrations/operations/constraints.ts +79 -10
  152. package/src/core/migrations/operations/dependencies.ts +0 -17
  153. package/src/core/migrations/operations/shared.ts +3 -3
  154. package/src/core/migrations/operations/tables.ts +1 -39
  155. package/src/core/migrations/planner-ddl-builders.ts +7 -48
  156. package/src/core/migrations/planner-produced-postgres-migration.ts +11 -6
  157. package/src/core/migrations/planner-sql-checks.ts +9 -9
  158. package/src/core/migrations/planner-strategies.ts +149 -11
  159. package/src/core/migrations/planner-target-details.ts +2 -1
  160. package/src/core/migrations/planner.ts +66 -8
  161. package/src/core/migrations/postgres-migration.ts +41 -0
  162. package/src/core/migrations/render-ops.ts +7 -2
  163. package/src/core/migrations/render-typescript.ts +5 -1
  164. package/src/core/migrations/runner.ts +78 -50
  165. package/src/core/postgres-contract-serializer.ts +52 -46
  166. package/src/core/postgres-enum-type.ts +4 -0
  167. package/src/core/postgres-schema.ts +43 -25
  168. package/src/exports/contract-free.ts +7 -0
  169. package/src/exports/control.ts +6 -8
  170. package/src/exports/ddl.ts +7 -0
  171. package/src/exports/migration.ts +11 -2
  172. package/src/exports/op-factory-call.ts +2 -0
  173. package/src/exports/planner-ddl-builders.ts +0 -1
  174. package/src/exports/runtime.ts +2 -2
  175. package/dist/codec-ids-C5qzBqus.mjs.map +0 -1
  176. package/dist/codec-ids-D9fJ4HP5.d.mts.map +0 -1
  177. package/dist/codec-types-CRlHq7Cz.d.mts.map +0 -1
  178. package/dist/codecs-Dud5KDNk.d.mts.map +0 -1
  179. package/dist/descriptor-meta-DLA2xV6B.mjs.map +0 -1
  180. package/dist/issue-planner-ByQhUzS4.mjs.map +0 -1
  181. package/dist/op-factory-call-B0WNg30h.mjs +0 -625
  182. package/dist/op-factory-call-B0WNg30h.mjs.map +0 -1
  183. package/dist/op-factory-call-Drccm_JD.d.mts.map +0 -1
  184. package/dist/planner-ClF0y0YR.mjs +0 -177
  185. package/dist/planner-ClF0y0YR.mjs.map +0 -1
  186. package/dist/planner-ddl-builders-BxRCSn_b.mjs.map +0 -1
  187. package/dist/planner-produced-postgres-migration-N1yqYg20.mjs.map +0 -1
  188. package/dist/planner-produced-postgres-migration-p-VKkCia.d.mts.map +0 -1
  189. package/dist/planner-sql-checks-D3H-xOO1.mjs.map +0 -1
  190. package/dist/planner-target-details-CIj61DUj.d.mts.map +0 -1
  191. package/dist/postgres-contract-serializer-YJvjKrmo.mjs.map +0 -1
  192. package/dist/postgres-enum-type-CNhPTDhy.d.mts.map +0 -1
  193. package/dist/postgres-enum-type-DS-KLVRH.mjs.map +0 -1
  194. package/dist/postgres-migration-Fd4fQkBw.d.mts.map +0 -1
  195. package/dist/postgres-migration-uADmx0dW.mjs.map +0 -1
  196. package/dist/postgres-schema-Bm7vjlOv.mjs.map +0 -1
  197. package/dist/render-typescript-CPk7hhWH.mjs.map +0 -1
  198. package/dist/statement-builders-vImtdfmM.mjs +0 -131
  199. package/dist/statement-builders-vImtdfmM.mjs.map +0 -1
  200. package/dist/statement-builders.d.mts +0 -51
  201. package/dist/statement-builders.d.mts.map +0 -1
  202. package/dist/statement-builders.mjs +0 -2
  203. package/dist/tables-Dcb2q9zV.mjs +0 -516
  204. package/dist/tables-Dcb2q9zV.mjs.map +0 -1
  205. package/dist/types-D-XIpzHA.d.mts.map +0 -1
  206. package/src/core/migrations/statement-builders.ts +0 -183
  207. package/src/exports/statement-builders.ts +0 -8
package/dist/control.mjs CHANGED
@@ -1,11 +1,10 @@
1
- import { t as postgresTargetDescriptorMeta } from "./descriptor-meta-DLA2xV6B.mjs";
2
- import { r as enumStorageCompoundKey, s as resolveDdlSchemaForNamespaceStorage, t as createResolveExistingEnumValues } from "./enum-planning-Dz0Ye3Lb.mjs";
3
- import { t as parsePostgresDefault } from "./default-normalizer-CRscvhS5.mjs";
4
- import { t as normalizeSchemaNativeType } from "./native-type-normalizer-ClNPq__-.mjs";
5
- import { o as renderDefaultLiteral } from "./planner-ddl-builders-BxRCSn_b.mjs";
6
- import { t as createPostgresMigrationPlanner } from "./planner-ClF0y0YR.mjs";
7
- import { a as ensureMarkerTableStatement, i as ensureLedgerTableStatement, n as buildLedgerInsertStatement, o as ensurePrismaContractSchemaStatement, r as buildMergeMarkerStatements } from "./statement-builders-vImtdfmM.mjs";
8
- import { t as PostgresContractSerializer } from "./postgres-contract-serializer-YJvjKrmo.mjs";
1
+ import { t as postgresTargetDescriptorMeta } from "./descriptor-meta-DKmj-IMN.mjs";
2
+ import { r as enumStorageCompoundKey, s as resolveDdlSchemaForNamespaceStorage, t as createResolveExistingEnumValues } from "./enum-planning-BCyvlFHk.mjs";
3
+ import { t as parsePostgresDefault } from "./default-normalizer-DyyCHQWs.mjs";
4
+ import { t as normalizeSchemaNativeType } from "./native-type-normalizer-Bc9XJzWC.mjs";
5
+ import { t as createPostgresMigrationPlanner } from "./planner-CAYPJObw.mjs";
6
+ import { a as renderDefaultLiteral } from "./planner-ddl-builders-Cw2n2llW.mjs";
7
+ import { t as PostgresContractSerializer } from "./postgres-contract-serializer-DYTyXjPf.mjs";
9
8
  import { contractToSchemaIR, extractCodecControlHooks, runnerFailure, runnerSuccess } from "@prisma-next/family-sql/control";
10
9
  import { ifDefined } from "@prisma-next/utils/defined";
11
10
  import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
@@ -52,7 +51,7 @@ var PostgresMigrationRunner = class {
52
51
  const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);
53
52
  if (!policyCheck.ok) return policyCheck;
54
53
  await this.acquireLock(driver, lockKey);
55
- const ensureResult = await this.ensureControlTables(driver);
54
+ const ensureResult = await this.ensureControlTables(driver, options.destinationContract);
56
55
  if (!ensureResult.ok) return ensureResult;
57
56
  const existingMarker = await this.family.readMarker({
58
57
  driver,
@@ -98,8 +97,9 @@ var PostgresMigrationRunner = class {
98
97
  const existingInvariants = new Set(existingMarker?.invariants ?? []);
99
98
  const incomingIsSubsetOfExisting = incomingInvariants.every((id) => existingInvariants.has(id));
100
99
  if (!(isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting)) {
101
- await this.upsertMarker(driver, options, existingMarker, space);
102
- await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);
100
+ const markerResult = await this.upsertMarker(driver, options, existingMarker, space);
101
+ if (!markerResult.ok) return markerResult;
102
+ await this.recordLedgerEntries(driver, options, applyValue.executedOperations);
103
103
  }
104
104
  return runnerSuccess({
105
105
  operationsPlanned: options.plan.operations.length,
@@ -174,12 +174,14 @@ var PostgresMigrationRunner = class {
174
174
  executedOperations
175
175
  });
176
176
  }
177
- async ensureControlTables(driver) {
178
- await this.executeStatement(driver, ensurePrismaContractSchemaStatement);
177
+ async ensureControlTables(driver, contract) {
178
+ const lowererContext = { contract };
179
+ const [schemaQuery, ...tableQueries] = this.family.bootstrapControlTableQueries();
180
+ if (schemaQuery === void 0) throw new Error("Postgres control-table bootstrap must include CREATE SCHEMA");
181
+ await this.executeStatement(driver, this.family.lowerAst(schemaQuery, lowererContext));
179
182
  const legacyDetection = await this.detectLegacyMarkerShape(driver);
180
183
  if (!legacyDetection.ok) return legacyDetection;
181
- await this.executeStatement(driver, ensureMarkerTableStatement);
182
- await this.executeStatement(driver, ensureLedgerTableStatement);
184
+ for (const query of tableQueries) await this.executeStatement(driver, this.family.lowerAst(query, lowererContext));
183
185
  return okVoid();
184
186
  }
185
187
  async detectLegacyMarkerShape(driver) {
@@ -316,30 +318,54 @@ var PostgresMigrationRunner = class {
316
318
  return okVoid();
317
319
  }
318
320
  async upsertMarker(driver, options, existingMarker, space) {
319
- const incomingInvariants = options.plan.providedInvariants ?? [];
320
- const writeStatements = buildMergeMarkerStatements({
321
- space,
321
+ const destination = {
322
322
  storageHash: options.plan.destination.storageHash,
323
323
  profileHash: options.plan.destination.profileHash ?? options.destinationContract.profileHash ?? options.plan.destination.storageHash,
324
- contractJson: options.destinationContract,
325
- canonicalVersion: null,
326
- meta: {},
327
- invariants: incomingInvariants
328
- });
329
- const statement = existingMarker ? writeStatements.update : writeStatements.insert;
330
- await this.executeStatement(driver, statement);
324
+ invariants: options.plan.providedInvariants ?? []
325
+ };
326
+ if (!existingMarker) {
327
+ await this.family.initMarker({
328
+ driver,
329
+ space,
330
+ destination
331
+ });
332
+ return okVoid();
333
+ }
334
+ if (!await this.family.updateMarker({
335
+ driver,
336
+ space,
337
+ expectedFrom: existingMarker.storageHash,
338
+ destination
339
+ })) return runnerFailure("MARKER_CAS_FAILURE", "Marker was modified by another process during migration execution.", { meta: {
340
+ space,
341
+ expectedStorageHash: existingMarker.storageHash,
342
+ destinationStorageHash: options.plan.destination.storageHash
343
+ } });
344
+ return okVoid();
331
345
  }
332
- async recordLedgerEntry(driver, options, existingMarker, executedOperations) {
333
- const ledgerStatement = buildLedgerInsertStatement({
334
- originStorageHash: existingMarker?.storageHash ?? null,
335
- originProfileHash: existingMarker?.profileHash ?? null,
336
- destinationStorageHash: options.plan.destination.storageHash,
337
- destinationProfileHash: options.plan.destination.profileHash ?? options.destinationContract.profileHash ?? options.plan.destination.storageHash,
338
- contractJsonBefore: existingMarker?.contractJson ?? null,
339
- contractJsonAfter: options.destinationContract,
340
- operations: executedOperations
341
- });
342
- await this.executeStatement(driver, ledgerStatement);
346
+ async recordLedgerEntries(driver, options, executedOperations) {
347
+ const plan = options.plan;
348
+ const space = plan.spaceId;
349
+ const edges = options.migrationEdges;
350
+ const totalEdgeOps = edges.reduce((sum, edge) => sum + edge.operationCount, 0);
351
+ if (totalEdgeOps !== plan.operations.length) throw new Error(`Ledger write: plan.operations length (${plan.operations.length}) does not match sum of migrationEdges operationCount (${totalEdgeOps})`);
352
+ let offset = 0;
353
+ for (const edge of edges) {
354
+ const edgeOps = executedOperations.slice(offset, offset + edge.operationCount);
355
+ offset += edge.operationCount;
356
+ await this.family.writeLedgerEntry({
357
+ driver,
358
+ space,
359
+ entry: {
360
+ edgeId: `${edge.from}->${edge.to}`,
361
+ from: edge.from,
362
+ to: edge.to,
363
+ migrationName: edge.dirName,
364
+ migrationHash: edge.migrationHash,
365
+ operations: edgeOps
366
+ }
367
+ });
368
+ }
343
369
  }
344
370
  async acquireLock(driver, key) {
345
371
  await driver.query("select pg_advisory_xact_lock(hashtext($1))", [key]);
@@ -408,8 +434,8 @@ const postgresTargetDescriptor = {
408
434
  contractSerializer: new PostgresContractSerializer(),
409
435
  schemaVerifier: new PostgresSchemaVerifier(),
410
436
  migrations: {
411
- createPlanner(_family) {
412
- return createPostgresMigrationPlanner();
437
+ createPlanner(adapter) {
438
+ return createPostgresMigrationPlanner(adapter);
413
439
  },
414
440
  createRunner(family) {
415
441
  return createPostgresMigrationRunner(family);
@@ -433,8 +459,8 @@ const postgresTargetDescriptor = {
433
459
  * Direct method for SQL-specific usage.
434
460
  * @deprecated Use migrations.createPlanner() for CLI compatibility.
435
461
  */
436
- createPlanner(_family) {
437
- return createPostgresMigrationPlanner();
462
+ createPlanner(adapter) {
463
+ return createPostgresMigrationPlanner(adapter);
438
464
  },
439
465
  /**
440
466
  * Direct method for SQL-specific usage.
@@ -1 +1 @@
1
- {"version":3,"file":"control.mjs","names":[],"sources":["../src/core/migrations/runner.ts","../src/core/postgres-schema-verifier.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 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 {\n ControlDriverInstance,\n MigrationRunnerResult,\n} from '@prisma-next/framework-components/control';\nimport { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\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 { createResolveExistingEnumValues } from './enum-planning';\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 ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\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 cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family);\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(private readonly family: SqlControlFamilyInstance) {}\n\n /**\n * Body of the migration runner without transaction management. The\n * caller ({@link PostgresMigrationRunner.execute}) owns the\n * `BEGIN`/`COMMIT`/`ROLLBACK` lifecycle.\n */\n async executeOnConnection(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema =\n options.schemaName ??\n Object.keys(options.destinationContract.storage.namespaces).find(\n (id) => id !== UNBOUND_NAMESPACE_ID,\n ) ??\n UNBOUND_NAMESPACE_ID;\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 resolveExistingEnumValues: createResolveExistingEnumValues(\n options.destinationContract.storage,\n ),\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 execute(options: {\n readonly driver: ControlDriverInstance<'sql', string>;\n readonly perSpaceOptions: ReadonlyArray<\n SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>\n >;\n }): Promise<MigrationRunnerResult> {\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 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 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 { Contract } from '@prisma-next/contract/types';\nimport { SqlSchemaVerifierBase } from '@prisma-next/family-sql/ir';\nimport type { SchemaIssue, SchemaVerifyOptions } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\n\n/**\n * Postgres target `SchemaVerifier` concretion. Plugs into the\n * SQL-shared verification surface; production verification today still\n * routes through the legacy `verifySqlSchema` entry point, which\n * carries options (codec hooks, normalizers, framework components)\n * that the framework-level `SchemaVerifyOptions` shape does not yet\n * surface.\n *\n * The hooks return the empty list pending the call-site migration that\n * routes the existing verifier behaviour through the SPI — at that\n * point `verifyCommonSqlSchema` will likely lift onto the family base\n * (mirroring `verifyCommonMongoSchema`) and `verifyTargetExtensions`\n * will house Postgres-only kinds (functions, RLS policies in a future\n * project).\n */\nexport class PostgresSchemaVerifier extends SqlSchemaVerifierBase<\n Contract<SqlStorage>,\n SqlSchemaIR\n> {\n protected verifyCommonSqlSchema(\n _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\n }\n\n protected verifyTargetExtensions(\n _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\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 {\n enumStorageCompoundKey,\n resolveDdlSchemaForNamespaceStorage,\n} from '../core/migrations/enum-planning';\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';\nimport { PostgresContractSerializer } from '../core/postgres-contract-serializer';\nimport { PostgresSchemaVerifier } from '../core/postgres-schema-verifier';\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 contractSerializer: new PostgresContractSerializer(),\n schemaVerifier: new PostgresSchemaVerifier(),\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 // Blind cast: the framework SPI signature\n // (`control-migration-types.ts § contractToSchema`) types\n // `contract` as the generic `Contract | null`. Inside the\n // postgres target descriptor we know any contract reaching\n // this method is SQL-family — the family contract resolver\n // would have refused to construct a postgres target binding\n // otherwise — so we narrow the generic to\n // `Contract<SqlStorage>` for the lowering call.\n return contractToSchemaIR(contract as unknown as Contract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n // Schema-qualify enum annotation keys so the projected \"from\" IR's\n // `storageTypes` match `readExistingEnumValues` on the read side\n // (the contract-to-contract `migration plan` path). The DDL-schema\n // resolution + compound-key format stay here in the target layer;\n // the family projector treats the returned string as opaque.\n // `undefined` schema IR ⇒ the unbound coordinate resolves to the\n // default `public` landing schema, matching the read-side fallback.\n resolveEnumStorageKey: (storage, namespaceId, nativeType) =>\n enumStorageCompoundKey(\n resolveDdlSchemaForNamespaceStorage(storage, namespaceId, undefined),\n nativeType,\n ),\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,cAAc;;;;;AAMpB,SAAS,qBAAwD,OAAa;CAC5E,MAAM,SAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,KAAK,GAC3C,IAAI,QAAQ,QAAQ,QAAQ,KAAA,GAC1B,OAAO,OAAO;MACT,IAAI,MAAM,QAAQ,GAAG,GAC1B,OAAO,OAAO,OAAO,OAAO,CAAC,GAAG,GAAG,CAAC;MAC/B,IAAI,OAAO,QAAQ,UACxB,OAAO,OAAO,qBAAqB,GAA8B;MAEjE,OAAO,OAAO;CAGlB,OAAO,OAAO,OAAO,MAAM;AAC7B;AAEA,SAAgB,8BACd,QAC+C;CAC/C,OAAO,IAAI,wBAAwB,MAAM;AAC3C;AAEA,IAAM,0BAAN,MAAuF;CACxD;CAA7B,YAAY,QAAmD;EAAlC,KAAA,SAAA;CAAmC;;;;;;CAOhE,MAAM,oBACJ,SACmC;EACnC,MAAM,SACJ,QAAQ,cACR,OAAO,KAAK,QAAQ,oBAAoB,QAAQ,UAAU,EAAE,MACzD,OAAO,OAAO,oBACjB,KACA;EACF,MAAM,SAAS,QAA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CACH,oBAAoB,IAAI,2BAA2B;CACnD,gBAAgB,IAAI,uBAAuB;CAC3C,YAAY;EACV,cAAc,SAAmC;GAC/C,OAAO,+BAA+B;EACxC;EACA,aAAa,QAAQ;GACnB,OAAO,8BAA8B,MAAM;EAC7C;EACA,iBAAiB,UAAU,qBAAqB;GAU9C,OAAO,mBAAmB,UAAoD;IAC5E,qBAAqB;IACrB,GAAG,UAAU,oBAXE,wBAAwB,mBAWC,CAAC;IACzC,eAAe;IAQf,wBAAwB,SAAS,aAAa,eAC5C,uBACE,oCAAoC,SAAS,aAAa,KAAA,CAAS,GACnE,UACF;GACJ,CAAC;EACH;CACF;CACA,SAAmD;EACjD,OAAO;GACL,UAAU;GACV,UAAU;EACZ;CACF;;;;;CAKA,cAAc,SAAmC;EAC/C,OAAO,+BAA+B;CACxC;;;;;CAKA,aAAa,QAAQ;EACnB,OAAO,8BAA8B,MAAM;CAC7C;AACF"}
1
+ {"version":3,"file":"control.mjs","names":[],"sources":["../src/core/migrations/runner.ts","../src/core/postgres-schema-verifier.ts","../src/exports/control.ts"],"sourcesContent":["import type { Contract, 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 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 { MigrationRunnerResult } from '@prisma-next/framework-components/control';\nimport { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlControlDriverInstance, SqlStorage } from '@prisma-next/sql-contract/types';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport type { LoweredStatement } from '@prisma-next/sql-relational-core/ast';\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 { createResolveExistingEnumValues } from './enum-planning';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\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 cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family);\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(private readonly family: SqlControlFamilyInstance) {}\n\n /**\n * Body of the migration runner without transaction management. The\n * caller ({@link PostgresMigrationRunner.execute}) owns the\n * `BEGIN`/`COMMIT`/`ROLLBACK` lifecycle.\n */\n async executeOnConnection(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema =\n options.schemaName ??\n Object.keys(options.destinationContract.storage.namespaces).find(\n (id) => id !== UNBOUND_NAMESPACE_ID,\n ) ??\n UNBOUND_NAMESPACE_ID;\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, options.destinationContract);\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 resolveExistingEnumValues: createResolveExistingEnumValues(\n options.destinationContract.storage,\n ),\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 const markerResult = await this.upsertMarker(driver, options, existingMarker, space);\n if (!markerResult.ok) return markerResult;\n await this.recordLedgerEntries(driver, options, applyValue.executedOperations);\n }\n\n return runnerSuccess({\n operationsPlanned: options.plan.operations.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n }\n\n async execute(options: {\n readonly driver: SqlControlDriverInstance<string>;\n readonly perSpaceOptions: ReadonlyArray<\n SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>\n >;\n }): Promise<MigrationRunnerResult> {\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 contract: Contract<SqlStorage>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const lowererContext = { contract };\n const bootstrapQueries = this.family.bootstrapControlTableQueries();\n const [schemaQuery, ...tableQueries] = bootstrapQueries;\n if (schemaQuery === undefined) {\n throw new Error('Postgres control-table bootstrap must include CREATE SCHEMA');\n }\n await this.executeStatement(driver, this.family.lowerAst(schemaQuery, lowererContext));\n const legacyDetection = await this.detectLegacyMarkerShape(driver);\n if (!legacyDetection.ok) {\n return legacyDetection;\n }\n for (const query of tableQueries) {\n await this.executeStatement(driver, this.family.lowerAst(query, lowererContext));\n }\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 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 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<Result<void, SqlMigrationRunnerFailure>> {\n const destination = {\n storageHash: options.plan.destination.storageHash,\n profileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n invariants: options.plan.providedInvariants ?? [],\n };\n if (!existingMarker) {\n await this.family.initMarker({ driver, space, destination });\n return okVoid();\n }\n const updated = await this.family.updateMarker({\n driver,\n space,\n expectedFrom: existingMarker.storageHash,\n destination,\n });\n if (!updated) {\n return runnerFailure(\n 'MARKER_CAS_FAILURE',\n 'Marker was modified by another process during migration execution.',\n {\n meta: {\n space,\n expectedStorageHash: existingMarker.storageHash,\n destinationStorageHash: options.plan.destination.storageHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async recordLedgerEntries(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Promise<void> {\n const plan = options.plan;\n const space = plan.spaceId;\n const edges = options.migrationEdges;\n const totalEdgeOps = edges.reduce((sum, edge) => sum + edge.operationCount, 0);\n if (totalEdgeOps !== plan.operations.length) {\n throw new Error(\n `Ledger write: plan.operations length (${plan.operations.length}) does not match sum of migrationEdges operationCount (${totalEdgeOps})`,\n );\n }\n // The ledger records the operations as executed — idempotency-skipped ops\n // are substituted with skip records (empty `execute`) by `applyPlan`, so the\n // journal reflects what actually ran rather than the raw plan.\n let offset = 0;\n for (const edge of edges) {\n const edgeOps = executedOperations.slice(offset, offset + edge.operationCount);\n offset += edge.operationCount;\n await this.family.writeLedgerEntry({\n driver,\n space,\n entry: {\n edgeId: `${edge.from}->${edge.to}`,\n from: edge.from,\n to: edge.to,\n migrationName: edge.dirName,\n migrationHash: edge.migrationHash,\n operations: edgeOps,\n },\n });\n }\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: LoweredStatement,\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 { Contract } from '@prisma-next/contract/types';\nimport { SqlSchemaVerifierBase } from '@prisma-next/family-sql/ir';\nimport type { SchemaIssue, SchemaVerifyOptions } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\n\n/**\n * Postgres target `SchemaVerifier` concretion. Plugs into the\n * SQL-shared verification surface; production verification today still\n * routes through the legacy `verifySqlSchema` entry point, which\n * carries options (codec hooks, normalizers, framework components)\n * that the framework-level `SchemaVerifyOptions` shape does not yet\n * surface.\n *\n * The hooks return the empty list pending the call-site migration that\n * routes the existing verifier behaviour through the SPI — at that\n * point `verifyCommonSqlSchema` will likely lift onto the family base\n * (mirroring `verifyCommonMongoSchema`) and `verifyTargetExtensions`\n * will house Postgres-only kinds (functions, RLS policies in a future\n * project).\n */\nexport class PostgresSchemaVerifier extends SqlSchemaVerifierBase<\n Contract<SqlStorage>,\n SqlSchemaIR\n> {\n protected verifyCommonSqlSchema(\n _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\n }\n\n protected verifyTargetExtensions(\n _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\n }\n}\n","import type { ColumnDefault, Contract } from '@prisma-next/contract/types';\nimport type { SqlControlTargetDescriptor } from '@prisma-next/family-sql/control';\nimport { contractToSchemaIR, extractCodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\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 {\n enumStorageCompoundKey,\n resolveDdlSchemaForNamespaceStorage,\n} from '../core/migrations/enum-planning';\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';\nimport { PostgresContractSerializer } from '../core/postgres-contract-serializer';\nimport { PostgresSchemaVerifier } from '../core/postgres-schema-verifier';\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 contractSerializer: new PostgresContractSerializer(),\n schemaVerifier: new PostgresSchemaVerifier(),\n migrations: {\n createPlanner(adapter: SqlControlAdapter<'postgres'>) {\n return createPostgresMigrationPlanner(adapter);\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n // Blind cast: the framework SPI signature\n // (`control-migration-types.ts § contractToSchema`) types\n // `contract` as the generic `Contract | null`. Inside the\n // postgres target descriptor we know any contract reaching\n // this method is SQL-family — the family contract resolver\n // would have refused to construct a postgres target binding\n // otherwise — so we narrow the generic to\n // `Contract<SqlStorage>` for the lowering call.\n return contractToSchemaIR(contract as unknown as Contract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n // Schema-qualify enum annotation keys so the projected \"from\" IR's\n // `storageTypes` match `readExistingEnumValues` on the read side\n // (the contract-to-contract `migration plan` path). The DDL-schema\n // resolution + compound-key format stay here in the target layer;\n // the family projector treats the returned string as opaque.\n // `undefined` schema IR ⇒ the unbound coordinate resolves to the\n // default `public` landing schema, matching the read-side fallback.\n resolveEnumStorageKey: (storage, namespaceId, nativeType) =>\n enumStorageCompoundKey(\n resolveDdlSchemaForNamespaceStorage(storage, namespaceId, undefined),\n nativeType,\n ),\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(adapter: SqlControlAdapter<'postgres'>) {\n return createPostgresMigrationPlanner(adapter);\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":";;;;;;;;;;;;;;;;AAkCA,MAAM,cAAc;;;;;AAMpB,SAAS,qBAAwD,OAAa;CAC5E,MAAM,SAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,KAAK,GAC3C,IAAI,QAAQ,QAAQ,QAAQ,KAAA,GAC1B,OAAO,OAAO;MACT,IAAI,MAAM,QAAQ,GAAG,GAC1B,OAAO,OAAO,OAAO,OAAO,CAAC,GAAG,GAAG,CAAC;MAC/B,IAAI,OAAO,QAAQ,UACxB,OAAO,OAAO,qBAAqB,GAA8B;MAEjE,OAAO,OAAO;CAGlB,OAAO,OAAO,OAAO,MAAM;AAC7B;AAEA,SAAgB,8BACd,QAC+C;CAC/C,OAAO,IAAI,wBAAwB,MAAM;AAC3C;AAEA,IAAM,0BAAN,MAAuF;CACxD;CAA7B,YAAY,QAAmD;EAAlC,KAAA,SAAA;CAAmC;;;;;;CAOhE,MAAM,oBACJ,SACmC;EAC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;GACV,UAAU;EACZ;CACF;;;;;CAKA,cAAc,SAAwC;EACpD,OAAO,+BAA+B,OAAO;CAC/C;;;;;CAKA,aAAa,QAAQ;EACnB,OAAO,8BAA8B,MAAM;CAC7C;AACF"}
@@ -58,4 +58,4 @@ function assertContractMatches(plan, contract, name) {
58
58
  //#endregion
59
59
  export { dataTransform as t };
60
60
 
61
- //# sourceMappingURL=data-transform-CdtGUWp2.mjs.map
61
+ //# sourceMappingURL=data-transform-D25tLeYU.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"data-transform-CdtGUWp2.mjs","names":[],"sources":["../src/core/migrations/operations/data-transform.ts"],"sourcesContent":["/**\n * User-facing `dataTransform` factory for the Postgres migration authoring\n * surface. Invoked directly inside a `migration.ts` file via the\n * `PostgresMigration` instance method (`this.dataTransform(...)`), which\n * supplies the control adapter from the migration's injected stack:\n *\n * ```ts\n * import endContract from './end-contract.json' with { type: 'json' };\n *\n * class M extends Migration {\n * override get operations() {\n * return [\n * this.dataTransform(endContract, 'backfill emails', {\n * check: () => db.users.select('id').where(({ email }) => email.isNull()).limit(1),\n * run: () => db.users.update({ email: '' }).where(({ email }) => email.isNull()),\n * }),\n * ];\n * }\n * }\n * ```\n *\n * The factory accepts lazy closures (`() => SqlQueryPlan | Buildable`),\n * invokes each one, asserts that its `meta.storageHash` matches the\n * `contract` it was handed (→ `PN-MIG-2005` on mismatch), and lowers the\n * plan via the supplied control adapter to a serialized `{sql, params}`\n * payload.\n *\n * The factory then lowers the data transform to the unified migration-op\n * shape `{ precheck, execute, postcheck }`. The user's `check` plan is\n * wrapped twice with opposite truth values:\n *\n * - precheck `SELECT EXISTS (<check>) AS ok` asserts there is work to do\n * (precheck is short-circuited by the runner's pre-satisfied-skip path\n * when nothing remains to backfill).\n * - postcheck `SELECT NOT EXISTS (<check>) AS ok` asserts the work is\n * complete after the run steps execute.\n *\n * The `check` plan is therefore expected to be a **rowset query whose\n * presence of any row signals \"work remains\"** — typically `select('id')\n * .where(<violation predicate>).limit(1)`. Scalar/aggregate shapes\n * (`count(*)`, `bool_and(...)`) do not work under this contract: they\n * always return exactly one row, so `EXISTS` is always true and\n * `NOT EXISTS` is always false. (This is the same row-presence contract\n * the pre-unification runner relied on; the wrapping is just lifting it\n * into SQL.)\n *\n * Each `run` plan becomes an execute step. Because the `Step.params`\n * field threads through `driver.query(sql, params)`, the user's bound\n * values flow through the driver's parameter binder rather than being\n * inlined into the SQL text.\n *\n * The free factory remains usable standalone (tests, ad-hoc tooling,\n * non-class contexts) by passing the adapter explicitly as the fourth\n * argument.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport { errorDataTransformContractMismatch } from '@prisma-next/errors/migration';\nimport type {\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n} from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport type { SerializedQueryPlan } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresPlanTargetDetails } from '../planner-target-details';\n\ninterface Buildable<R = unknown> {\n build(): SqlQueryPlan<R>;\n}\n\n/**\n * A single-closure producer of a SQL query plan. Shared between\n * `check` and each `run` entry.\n */\nexport type DataTransformClosure = () => SqlQueryPlan | Buildable;\n\nexport interface DataTransformOptions {\n /**\n * Optional opt-in routing identity. Presence opts the transform into\n * invariant-aware routing; absence means it is path-dependent and\n * not referenceable from refs.\n */\n readonly invariantId?: string;\n /**\n * Optional pre-flight query. `undefined` means \"no check\". When\n * supplied, the closure must return a **rowset query** whose\n * presence of any row signals \"violations remain\". Conventional\n * shape: `db.<table>.select('id').where(<violation>).limit(1)`.\n * Scalar/aggregate shapes do not satisfy this contract.\n */\n readonly check?: DataTransformClosure;\n /** One or more mutation queries to execute. */\n readonly run: DataTransformClosure | readonly DataTransformClosure[];\n}\n\nexport function dataTransform<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n name: string,\n options: DataTransformOptions,\n adapter: SqlControlAdapter<'postgres'>,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const runClosures: readonly DataTransformClosure[] = Array.isArray(options.run)\n ? options.run\n : [options.run as DataTransformClosure];\n\n const checkPlan = options.check ? invokeAndLower(options.check, contract, adapter, name) : null;\n const runPlans = runClosures.map((closure) => invokeAndLower(closure, contract, adapter, name));\n\n const precheck: readonly SqlMigrationPlanOperationStep[] = checkPlan\n ? [\n {\n description: `Check ${name} has work to do`,\n sql: `SELECT EXISTS (${checkPlan.sql}) AS ok`,\n params: checkPlan.params,\n },\n ]\n : [];\n\n const execute: readonly SqlMigrationPlanOperationStep[] = runPlans.map((plan) => ({\n description: `Run ${name}`,\n sql: plan.sql,\n params: plan.params,\n }));\n\n const postcheck: readonly SqlMigrationPlanOperationStep[] = checkPlan\n ? [\n {\n description: `Verify ${name} resolved all violations`,\n sql: `SELECT NOT EXISTS (${checkPlan.sql}) AS ok`,\n params: checkPlan.params,\n },\n ]\n : [];\n\n return {\n id: `data_migration.${name}`,\n label: `Data transform: ${name}`,\n operationClass: 'data',\n ...ifDefined('invariantId', options.invariantId),\n target: { id: 'postgres' },\n precheck,\n execute,\n postcheck,\n };\n}\n\nfunction invokeAndLower(\n closure: DataTransformClosure,\n contract: Contract<SqlStorage>,\n adapter: SqlControlAdapter<'postgres'>,\n name: string,\n): SerializedQueryPlan {\n const result = closure();\n const plan = isBuildable(result) ? result.build() : result;\n assertContractMatches(plan, contract, name);\n const lowered = adapter.lower(plan.ast, { contract });\n const params = lowered.params.map((slot) => {\n if (slot.kind === 'literal') return slot.value;\n throw new Error(\n `data-transform: bind-site slot '${slot.name}' is not allowed in migration plans`,\n );\n });\n return { sql: lowered.sql, params };\n}\n\nfunction isBuildable(value: unknown): value is Buildable {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'build' in value &&\n typeof (value as { build: unknown }).build === 'function'\n );\n}\n\nfunction assertContractMatches(\n plan: SqlQueryPlan,\n contract: Contract<SqlStorage>,\n name: string,\n): void {\n if (plan.meta.storageHash !== contract.storage.storageHash) {\n throw errorDataTransformContractMismatch({\n dataTransformName: name,\n expected: contract.storage.storageHash,\n actual: plan.meta.storageHash,\n });\n }\n}\n"],"mappings":";;;AAkGA,SAAgB,cACd,UACA,MACA,SACA,SACsD;CACtD,MAAM,cAA+C,MAAM,QAAQ,QAAQ,GAAG,IAC1E,QAAQ,MACR,CAAC,QAAQ,GAA2B;CAExC,MAAM,YAAY,QAAQ,QAAQ,eAAe,QAAQ,OAAO,UAAU,SAAS,IAAI,IAAI;CAC3F,MAAM,WAAW,YAAY,KAAK,YAAY,eAAe,SAAS,UAAU,SAAS,IAAI,CAAC;CAE9F,MAAM,WAAqD,YACvD,CACE;EACE,aAAa,SAAS,KAAK;EAC3B,KAAK,kBAAkB,UAAU,IAAI;EACrC,QAAQ,UAAU;CACpB,CACF,IACA,CAAC;CAEL,MAAM,UAAoD,SAAS,KAAK,UAAU;EAChF,aAAa,OAAO;EACpB,KAAK,KAAK;EACV,QAAQ,KAAK;CACf,EAAE;CAEF,MAAM,YAAsD,YACxD,CACE;EACE,aAAa,UAAU,KAAK;EAC5B,KAAK,sBAAsB,UAAU,IAAI;EACzC,QAAQ,UAAU;CACpB,CACF,IACA,CAAC;CAEL,OAAO;EACL,IAAI,kBAAkB;EACtB,OAAO,mBAAmB;EAC1B,gBAAgB;EAChB,GAAG,UAAU,eAAe,QAAQ,WAAW;EAC/C,QAAQ,EAAE,IAAI,WAAW;EACzB;EACA;EACA;CACF;AACF;AAEA,SAAS,eACP,SACA,UACA,SACA,MACqB;CACrB,MAAM,SAAS,QAAQ;CACvB,MAAM,OAAO,YAAY,MAAM,IAAI,OAAO,MAAM,IAAI;CACpD,sBAAsB,MAAM,UAAU,IAAI;CAC1C,MAAM,UAAU,QAAQ,MAAM,KAAK,KAAK,EAAE,SAAS,CAAC;CACpD,MAAM,SAAS,QAAQ,OAAO,KAAK,SAAS;EAC1C,IAAI,KAAK,SAAS,WAAW,OAAO,KAAK;EACzC,MAAM,IAAI,MACR,mCAAmC,KAAK,KAAK,oCAC/C;CACF,CAAC;CACD,OAAO;EAAE,KAAK,QAAQ;EAAK;CAAO;AACpC;AAEA,SAAS,YAAY,OAAoC;CACvD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,WAAW,SACX,OAAQ,MAA6B,UAAU;AAEnD;AAEA,SAAS,sBACP,MACA,UACA,MACM;CACN,IAAI,KAAK,KAAK,gBAAgB,SAAS,QAAQ,aAC7C,MAAM,mCAAmC;EACvC,mBAAmB;EACnB,UAAU,SAAS,QAAQ;EAC3B,QAAQ,KAAK,KAAK;CACpB,CAAC;AAEL"}
1
+ {"version":3,"file":"data-transform-D25tLeYU.mjs","names":[],"sources":["../src/core/migrations/operations/data-transform.ts"],"sourcesContent":["/**\n * User-facing `dataTransform` factory for the Postgres migration authoring\n * surface. Invoked directly inside a `migration.ts` file via the\n * `PostgresMigration` instance method (`this.dataTransform(...)`), which\n * supplies the control adapter from the migration's injected stack:\n *\n * ```ts\n * import endContract from './end-contract.json' with { type: 'json' };\n *\n * class M extends Migration {\n * override get operations() {\n * return [\n * this.dataTransform(endContract, 'backfill emails', {\n * check: () => db.users.select('id').where(({ email }) => email.isNull()).limit(1),\n * run: () => db.users.update({ email: '' }).where(({ email }) => email.isNull()),\n * }),\n * ];\n * }\n * }\n * ```\n *\n * The factory accepts lazy closures (`() => SqlQueryPlan | Buildable`),\n * invokes each one, asserts that its `meta.storageHash` matches the\n * `contract` it was handed (→ `PN-MIG-2005` on mismatch), and lowers the\n * plan via the supplied control adapter to a serialized `{sql, params}`\n * payload.\n *\n * The factory then lowers the data transform to the unified migration-op\n * shape `{ precheck, execute, postcheck }`. The user's `check` plan is\n * wrapped twice with opposite truth values:\n *\n * - precheck `SELECT EXISTS (<check>) AS ok` asserts there is work to do\n * (precheck is short-circuited by the runner's pre-satisfied-skip path\n * when nothing remains to backfill).\n * - postcheck `SELECT NOT EXISTS (<check>) AS ok` asserts the work is\n * complete after the run steps execute.\n *\n * The `check` plan is therefore expected to be a **rowset query whose\n * presence of any row signals \"work remains\"** — typically `select('id')\n * .where(<violation predicate>).limit(1)`. Scalar/aggregate shapes\n * (`count(*)`, `bool_and(...)`) do not work under this contract: they\n * always return exactly one row, so `EXISTS` is always true and\n * `NOT EXISTS` is always false. (This is the same row-presence contract\n * the pre-unification runner relied on; the wrapping is just lifting it\n * into SQL.)\n *\n * Each `run` plan becomes an execute step. Because the `Step.params`\n * field threads through `driver.query(sql, params)`, the user's bound\n * values flow through the driver's parameter binder rather than being\n * inlined into the SQL text.\n *\n * The free factory remains usable standalone (tests, ad-hoc tooling,\n * non-class contexts) by passing the adapter explicitly as the fourth\n * argument.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport { errorDataTransformContractMismatch } from '@prisma-next/errors/migration';\nimport type {\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n} from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport type { SerializedQueryPlan } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresPlanTargetDetails } from '../planner-target-details';\n\ninterface Buildable<R = unknown> {\n build(): SqlQueryPlan<R>;\n}\n\n/**\n * A single-closure producer of a SQL query plan. Shared between\n * `check` and each `run` entry.\n */\nexport type DataTransformClosure = () => SqlQueryPlan | Buildable;\n\nexport interface DataTransformOptions {\n /**\n * Optional opt-in routing identity. Presence opts the transform into\n * invariant-aware routing; absence means it is path-dependent and\n * not referenceable from refs.\n */\n readonly invariantId?: string;\n /**\n * Optional pre-flight query. `undefined` means \"no check\". When\n * supplied, the closure must return a **rowset query** whose\n * presence of any row signals \"violations remain\". Conventional\n * shape: `db.<table>.select('id').where(<violation>).limit(1)`.\n * Scalar/aggregate shapes do not satisfy this contract.\n */\n readonly check?: DataTransformClosure;\n /** One or more mutation queries to execute. */\n readonly run: DataTransformClosure | readonly DataTransformClosure[];\n}\n\nexport function dataTransform<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n name: string,\n options: DataTransformOptions,\n adapter: SqlControlAdapter<'postgres'>,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const runClosures: readonly DataTransformClosure[] = Array.isArray(options.run)\n ? options.run\n : [options.run as DataTransformClosure];\n\n const checkPlan = options.check ? invokeAndLower(options.check, contract, adapter, name) : null;\n const runPlans = runClosures.map((closure) => invokeAndLower(closure, contract, adapter, name));\n\n const precheck: readonly SqlMigrationPlanOperationStep[] = checkPlan\n ? [\n {\n description: `Check ${name} has work to do`,\n sql: `SELECT EXISTS (${checkPlan.sql}) AS ok`,\n params: checkPlan.params,\n },\n ]\n : [];\n\n const execute: readonly SqlMigrationPlanOperationStep[] = runPlans.map((plan) => ({\n description: `Run ${name}`,\n sql: plan.sql,\n params: plan.params,\n }));\n\n const postcheck: readonly SqlMigrationPlanOperationStep[] = checkPlan\n ? [\n {\n description: `Verify ${name} resolved all violations`,\n sql: `SELECT NOT EXISTS (${checkPlan.sql}) AS ok`,\n params: checkPlan.params,\n },\n ]\n : [];\n\n return {\n id: `data_migration.${name}`,\n label: `Data transform: ${name}`,\n operationClass: 'data',\n ...ifDefined('invariantId', options.invariantId),\n target: { id: 'postgres' },\n precheck,\n execute,\n postcheck,\n };\n}\n\nfunction invokeAndLower(\n closure: DataTransformClosure,\n contract: Contract<SqlStorage>,\n adapter: SqlControlAdapter<'postgres'>,\n name: string,\n): SerializedQueryPlan {\n const result = closure();\n const plan = isBuildable(result) ? result.build() : result;\n assertContractMatches(plan, contract, name);\n const lowered = adapter.lower(plan.ast, { contract });\n const params = lowered.params.map((slot) => {\n if (slot.kind === 'literal') return slot.value;\n throw new Error(\n `data-transform: bind-site slot '${slot.name}' is not allowed in migration plans`,\n );\n });\n return { sql: lowered.sql, params };\n}\n\nfunction isBuildable(value: unknown): value is Buildable {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'build' in value &&\n typeof (value as { build: unknown }).build === 'function'\n );\n}\n\nfunction assertContractMatches(\n plan: SqlQueryPlan,\n contract: Contract<SqlStorage>,\n name: string,\n): void {\n if (plan.meta.storageHash !== contract.storage.storageHash) {\n throw errorDataTransformContractMismatch({\n dataTransformName: name,\n expected: contract.storage.storageHash,\n actual: plan.meta.storageHash,\n });\n }\n}\n"],"mappings":";;;AAkGA,SAAgB,cACd,UACA,MACA,SACA,SACsD;CACtD,MAAM,cAA+C,MAAM,QAAQ,QAAQ,GAAG,IAC1E,QAAQ,MACR,CAAC,QAAQ,GAA2B;CAExC,MAAM,YAAY,QAAQ,QAAQ,eAAe,QAAQ,OAAO,UAAU,SAAS,IAAI,IAAI;CAC3F,MAAM,WAAW,YAAY,KAAK,YAAY,eAAe,SAAS,UAAU,SAAS,IAAI,CAAC;CAE9F,MAAM,WAAqD,YACvD,CACE;EACE,aAAa,SAAS,KAAK;EAC3B,KAAK,kBAAkB,UAAU,IAAI;EACrC,QAAQ,UAAU;CACpB,CACF,IACA,CAAC;CAEL,MAAM,UAAoD,SAAS,KAAK,UAAU;EAChF,aAAa,OAAO;EACpB,KAAK,KAAK;EACV,QAAQ,KAAK;CACf,EAAE;CAEF,MAAM,YAAsD,YACxD,CACE;EACE,aAAa,UAAU,KAAK;EAC5B,KAAK,sBAAsB,UAAU,IAAI;EACzC,QAAQ,UAAU;CACpB,CACF,IACA,CAAC;CAEL,OAAO;EACL,IAAI,kBAAkB;EACtB,OAAO,mBAAmB;EAC1B,gBAAgB;EAChB,GAAG,UAAU,eAAe,QAAQ,WAAW;EAC/C,QAAQ,EAAE,IAAI,WAAW;EACzB;EACA;EACA;CACF;AACF;AAEA,SAAS,eACP,SACA,UACA,SACA,MACqB;CACrB,MAAM,SAAS,QAAQ;CACvB,MAAM,OAAO,YAAY,MAAM,IAAI,OAAO,MAAM,IAAI;CACpD,sBAAsB,MAAM,UAAU,IAAI;CAC1C,MAAM,UAAU,QAAQ,MAAM,KAAK,KAAK,EAAE,SAAS,CAAC;CACpD,MAAM,SAAS,QAAQ,OAAO,KAAK,SAAS;EAC1C,IAAI,KAAK,SAAS,WAAW,OAAO,KAAK;EACzC,MAAM,IAAI,MACR,mCAAmC,KAAK,KAAK,oCAC/C;CACF,CAAC;CACD,OAAO;EAAE,KAAK,QAAQ;EAAK;CAAO;AACpC;AAEA,SAAS,YAAY,OAAoC;CACvD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,WAAW,SACX,OAAQ,MAA6B,UAAU;AAEnD;AAEA,SAAS,sBACP,MACA,UACA,MACM;CACN,IAAI,KAAK,KAAK,gBAAgB,SAAS,QAAQ,aAC7C,MAAM,mCAAmC;EACvC,mBAAmB;EACnB,UAAU,SAAS,QAAQ;EAC3B,QAAQ,KAAK,KAAK;CACpB,CAAC;AAEL"}
@@ -1,4 +1,4 @@
1
- import { t as PostgresPlanTargetDetails } from "./planner-target-details-CIj61DUj.mjs";
1
+ import { t as PostgresPlanTargetDetails } from "./planner-target-details-CIY6tLeo.mjs";
2
2
  import { SqlMigrationPlanOperation } from "@prisma-next/family-sql/control";
3
3
  import { SqlStorage } from "@prisma-next/sql-contract/types";
4
4
  import { Contract } from "@prisma-next/contract/types";
@@ -35,4 +35,4 @@ interface DataTransformOptions {
35
35
  declare function dataTransform<TContract extends Contract<SqlStorage>>(contract: TContract, name: string, options: DataTransformOptions, adapter: SqlControlAdapter<'postgres'>): SqlMigrationPlanOperation<PostgresPlanTargetDetails>;
36
36
  //#endregion
37
37
  export { DataTransformOptions as n, dataTransform as r, DataTransformClosure as t };
38
- //# sourceMappingURL=data-transform-bmOKkygi.d.mts.map
38
+ //# sourceMappingURL=data-transform-DGOqcLrf.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"data-transform-bmOKkygi.d.mts","names":[],"sources":["../src/core/migrations/operations/data-transform.ts"],"mappings":";;;;;;;;UAqEU,SAAA;EACR,KAAA,IAAS,YAAY,CAAC,CAAA;AAAA;AAiC8B;;;;AAAA,KA1B1C,oBAAA,SAA6B,YAAA,GAAe,SAAS;AAAA,UAEhD,oBAAA;;;;;;WAMN,WAAA;;;;;;;;WAQA,KAAA,GAAQ,oBAAA;;WAER,GAAA,EAAK,oBAAA,YAAgC,oBAAA;AAAA;AAAA,iBAGhC,aAAA,mBAAgC,QAAA,CAAS,UAAA,EAAA,CACvD,QAAA,EAAU,SAAA,EACV,IAAA,UACA,OAAA,EAAS,oBAAA,EACT,OAAA,EAAS,iBAAA,eACR,yBAAA,CAA0B,yBAAA"}
1
+ {"version":3,"file":"data-transform-DGOqcLrf.d.mts","names":[],"sources":["../src/core/migrations/operations/data-transform.ts"],"mappings":";;;;;;;;UAqEU,SAAA;EACR,KAAA,IAAS,YAAY,CAAC,CAAA;AAAA;AAiC8B;;;;AAAA,KA1B1C,oBAAA,SAA6B,YAAA,GAAe,SAAS;AAAA,UAEhD,oBAAA;;;;;;WAMN,WAAA;;;;;;;;WAQA,KAAA,GAAQ,oBAAA;;WAER,GAAA,EAAK,oBAAA,YAAgC,oBAAA;AAAA;AAAA,iBAGhC,aAAA,mBAAgC,QAAA,CAAS,UAAA,GACvD,QAAA,EAAU,SAAA,EACV,IAAA,UACA,OAAA,EAAS,oBAAA,EACT,OAAA,EAAS,iBAAA,eACR,yBAAA,CAA0B,yBAAA"}
@@ -1,2 +1,2 @@
1
- import { r as dataTransform } from "./data-transform-bmOKkygi.mjs";
1
+ import { r as dataTransform } from "./data-transform-DGOqcLrf.mjs";
2
2
  export { dataTransform };
@@ -1,2 +1,2 @@
1
- import { t as dataTransform } from "./data-transform-CdtGUWp2.mjs";
1
+ import { t as dataTransform } from "./data-transform-D25tLeYU.mjs";
2
2
  export { dataTransform };
@@ -0,0 +1,30 @@
1
+ import { n as PostgresCreateTable, t as PostgresCreateSchema } from "./nodes-DZk2JZG3.mjs";
2
+ //#region src/contract-free/ddl.ts
3
+ /**
4
+ * Build a Postgres `CREATE TABLE` query node.
5
+ *
6
+ * Pass `constraints` for table-level composite primary keys, foreign keys, and
7
+ * unique constraints — use the {@link PrimaryKeyConstraint}, {@link ForeignKeyConstraint},
8
+ * and {@link UniqueConstraint} classes from `@prisma-next/sql-relational-core/ast`.
9
+ *
10
+ * Precondition: identifiers (`table`, `schema`, column names/types) are
11
+ * emitted to SQL verbatim — they are not quoted or escaped, so callers must
12
+ * pass pre-trusted values (e.g. fixed control-plane identifiers). String-literal
13
+ * default values, by contrast, are single-quote-escaped (embedded `'` doubled)
14
+ * by the renderer. Identifier quoting for untrusted identifiers is added when
15
+ * the migration planner adopts this lowering path.
16
+ */
17
+ function createTable(options) {
18
+ return new PostgresCreateTable(options);
19
+ }
20
+ /**
21
+ * Build a Postgres `CREATE SCHEMA` query node. See {@link createTable} for the
22
+ * pre-trusted-identifier precondition.
23
+ */
24
+ function createSchema(options) {
25
+ return new PostgresCreateSchema(options);
26
+ }
27
+ //#endregion
28
+ export { createTable as n, createSchema as t };
29
+
30
+ //# sourceMappingURL=ddl-77SyXgFt.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ddl-77SyXgFt.mjs","names":[],"sources":["../src/contract-free/ddl.ts"],"sourcesContent":["import type { DdlColumn, DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';\nimport { PostgresCreateSchema, PostgresCreateTable } from '../core/ddl/nodes';\n\n/**\n * Build a Postgres `CREATE TABLE` query node.\n *\n * Pass `constraints` for table-level composite primary keys, foreign keys, and\n * unique constraints — use the {@link PrimaryKeyConstraint}, {@link ForeignKeyConstraint},\n * and {@link UniqueConstraint} classes from `@prisma-next/sql-relational-core/ast`.\n *\n * Precondition: identifiers (`table`, `schema`, column names/types) are\n * emitted to SQL verbatim — they are not quoted or escaped, so callers must\n * pass pre-trusted values (e.g. fixed control-plane identifiers). String-literal\n * default values, by contrast, are single-quote-escaped (embedded `'` doubled)\n * by the renderer. Identifier quoting for untrusted identifiers is added when\n * the migration planner adopts this lowering path.\n */\nexport function createTable(options: {\n readonly table: string;\n readonly schema?: string;\n readonly ifNotExists?: boolean;\n readonly columns: readonly DdlColumn[];\n readonly constraints?: readonly DdlTableConstraint[];\n}): PostgresCreateTable {\n return new PostgresCreateTable(options);\n}\n\n/**\n * Build a Postgres `CREATE SCHEMA` query node. See {@link createTable} for the\n * pre-trusted-identifier precondition.\n */\nexport function createSchema(options: {\n readonly schema: string;\n readonly ifNotExists?: boolean;\n}): PostgresCreateSchema {\n return new PostgresCreateSchema(options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,SAAgB,YAAY,SAMJ;CACtB,OAAO,IAAI,oBAAoB,OAAO;AACxC;;;;;AAMA,SAAgB,aAAa,SAGJ;CACvB,OAAO,IAAI,qBAAqB,OAAO;AACzC"}
package/dist/ddl.d.mts ADDED
@@ -0,0 +1,2 @@
1
+ import { a as PostgresDdlVisitor, i as PostgresDdlNode, n as PostgresCreateSchema, r as PostgresCreateTable, t as AnyPostgresDdlNode } from "./nodes-779hmCfL.mjs";
2
+ export { type AnyPostgresDdlNode, PostgresCreateSchema, PostgresCreateTable, PostgresDdlNode, type PostgresDdlVisitor };
package/dist/ddl.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import { n as PostgresCreateTable, r as PostgresDdlNode, t as PostgresCreateSchema } from "./nodes-DZk2JZG3.mjs";
2
+ export { PostgresCreateSchema, PostgresCreateTable, PostgresDdlNode };
@@ -128,4 +128,4 @@ function parsePostgresDefault(rawDefault, nativeType) {
128
128
  //#endregion
129
129
  export { parsePostgresDefault as t };
130
130
 
131
- //# sourceMappingURL=default-normalizer-CRscvhS5.mjs.map
131
+ //# sourceMappingURL=default-normalizer-DyyCHQWs.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"default-normalizer-CRscvhS5.mjs","names":[],"sources":["../src/core/default-normalizer.ts"],"sourcesContent":["import type { ColumnDefault } from '@prisma-next/contract/types';\n\n/**\n * Pre-compiled regex patterns for performance.\n * These are compiled once at module load time rather than on each function call.\n */\nconst NEXTVAL_PATTERN = /^nextval\\s*\\(/i;\nconst NOW_FUNCTION_PATTERN = /^(now\\s*\\(\\s*\\)|CURRENT_TIMESTAMP)$/i;\nconst CLOCK_TIMESTAMP_PATTERN = /^clock_timestamp\\s*\\(\\s*\\)$/i;\nconst TIMESTAMP_CAST_SUFFIX = /::timestamp(?:tz|\\s+(?:with|without)\\s+time\\s+zone)?$/i;\nconst TEXT_CAST_SUFFIX = /::text$/i;\nconst NOW_LITERAL_PATTERN = /^'now'$/i;\nconst UUID_PATTERN = /^gen_random_uuid\\s*\\(\\s*\\)$/i;\nconst UUID_OSSP_PATTERN = /^uuid_generate_v4\\s*\\(\\s*\\)$/i;\nconst NULL_PATTERN = /^NULL(?:::.+)?$/i;\nconst TRUE_PATTERN = /^true$/i;\nconst FALSE_PATTERN = /^false$/i;\nconst NUMERIC_PATTERN = /^-?\\d+(\\.\\d+)?$/;\nconst STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:\"[^\"]+\"|[\\w\\s]+)(?:\\(\\d+\\))?)?$/;\n\n/**\n * Returns the canonical expression for a timestamp default function, or undefined\n * if the expression is not a recognized timestamp default.\n *\n * Keeps now()/CURRENT_TIMESTAMP and clock_timestamp() distinct:\n * - now(), CURRENT_TIMESTAMP, ('now'::text)::timestamp... → 'now()'\n * - clock_timestamp(), clock_timestamp()::timestamptz → 'clock_timestamp()'\n *\n * These are semantically different in Postgres: now() returns the transaction\n * start time (constant within a transaction), while clock_timestamp() returns\n * the actual wall-clock time (can differ across rows in a single INSERT).\n */\nfunction canonicalizeTimestampDefault(expr: string): string | undefined {\n if (NOW_FUNCTION_PATTERN.test(expr)) return 'now()';\n if (CLOCK_TIMESTAMP_PATTERN.test(expr)) return 'clock_timestamp()';\n\n if (!TIMESTAMP_CAST_SUFFIX.test(expr)) return undefined;\n\n let inner = expr.replace(TIMESTAMP_CAST_SUFFIX, '').trim();\n\n if (inner.startsWith('(') && inner.endsWith(')')) {\n inner = inner.slice(1, -1).trim();\n }\n\n if (NOW_FUNCTION_PATTERN.test(inner)) return 'now()';\n if (CLOCK_TIMESTAMP_PATTERN.test(inner)) return 'clock_timestamp()';\n\n inner = inner.replace(TEXT_CAST_SUFFIX, '').trim();\n if (NOW_LITERAL_PATTERN.test(inner)) return 'now()';\n\n return undefined;\n}\n\n/**\n * Parses a raw Postgres column default expression into a normalized ColumnDefault.\n * This enables semantic comparison between contract defaults and introspected schema defaults.\n *\n * Used by the migration diff layer to normalize raw database defaults during comparison,\n * keeping the introspection layer focused on faithful data capture.\n *\n * @param rawDefault - Raw default expression from information_schema.columns.column_default\n * @param nativeType - Native column type, used for type-aware parsing (bigint tagging, JSON detection)\n * @returns Normalized ColumnDefault or undefined if the expression cannot be parsed\n */\nexport function parsePostgresDefault(\n rawDefault: string,\n nativeType?: string,\n): ColumnDefault | undefined {\n const trimmed = rawDefault.trim();\n const normalizedType = nativeType?.toLowerCase();\n const isBigInt = normalizedType === 'bigint' || normalizedType === 'int8';\n\n if (NEXTVAL_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'autoincrement()' };\n }\n\n const canonicalTimestamp = canonicalizeTimestampDefault(trimmed);\n if (canonicalTimestamp) {\n return { kind: 'function', expression: canonicalTimestamp };\n }\n\n if (UUID_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'gen_random_uuid()' };\n }\n\n if (UUID_OSSP_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'gen_random_uuid()' };\n }\n\n if (NULL_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: null };\n }\n\n if (TRUE_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: true };\n }\n if (FALSE_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: false };\n }\n\n if (NUMERIC_PATTERN.test(trimmed)) {\n const num = Number(trimmed);\n if (!Number.isFinite(num)) return undefined;\n if (isBigInt && !Number.isSafeInteger(num)) {\n return { kind: 'literal', value: trimmed };\n }\n return { kind: 'literal', value: num };\n }\n\n const stringMatch = trimmed.match(STRING_LITERAL_PATTERN);\n if (stringMatch?.[1] !== undefined) {\n const unescaped = stringMatch[1].replace(/''/g, \"'\");\n if (normalizedType === 'json' || normalizedType === 'jsonb') {\n try {\n return { kind: 'literal', value: JSON.parse(unescaped) };\n } catch {\n // Keep legacy behavior for malformed/non-JSON string content.\n }\n }\n if (isBigInt && NUMERIC_PATTERN.test(unescaped)) {\n const num = Number(unescaped);\n if (Number.isSafeInteger(num)) {\n return { kind: 'literal', value: num };\n }\n return { kind: 'literal', value: unescaped };\n }\n return { kind: 'literal', value: unescaped };\n }\n\n return { kind: 'function', expression: trimmed };\n}\n"],"mappings":";;;;;AAMA,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;AAC7B,MAAM,0BAA0B;AAChC,MAAM,wBAAwB;AAC9B,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAC5B,MAAM,eAAe;AACrB,MAAM,oBAAoB;AAC1B,MAAM,eAAe;AACrB,MAAM,eAAe;AACrB,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;AACxB,MAAM,yBAAyB;;;;;;;;;;;;;AAc/B,SAAS,6BAA6B,MAAkC;CACtE,IAAI,qBAAqB,KAAK,IAAI,GAAG,OAAO;CAC5C,IAAI,wBAAwB,KAAK,IAAI,GAAG,OAAO;CAE/C,IAAI,CAAC,sBAAsB,KAAK,IAAI,GAAG,OAAO,KAAA;CAE9C,IAAI,QAAQ,KAAK,QAAQ,uBAAuB,EAAE,EAAE,KAAK;CAEzD,IAAI,MAAM,WAAW,GAAG,KAAK,MAAM,SAAS,GAAG,GAC7C,QAAQ,MAAM,MAAM,GAAG,EAAE,EAAE,KAAK;CAGlC,IAAI,qBAAqB,KAAK,KAAK,GAAG,OAAO;CAC7C,IAAI,wBAAwB,KAAK,KAAK,GAAG,OAAO;CAEhD,QAAQ,MAAM,QAAQ,kBAAkB,EAAE,EAAE,KAAK;CACjD,IAA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zD,QAAQ,CAER;EAEF,IAAI,YAAY,gBAAgB,KAAK,SAAS,GAAG;GAC/C,MAAM,MAAM,OAAO,SAAS;GAC5B,IAAI,OAAO,cAAc,GAAG,GAC1B,OAAO;IAAE,MAAM;IAAW,OAAO;GAAI;GAEvC,OAAO;IAAE,MAAM;IAAW,OAAO;GAAU;EAC7C;EACA,OAAO;GAAE,MAAM;GAAW,OAAO;EAAU;CAC7C;CAEA,OAAO;EAAE,MAAM;EAAY,YAAY;CAAQ;AACjD"}
1
+ {"version":3,"file":"default-normalizer-DyyCHQWs.mjs","names":[],"sources":["../src/core/default-normalizer.ts"],"sourcesContent":["import type { ColumnDefault } from '@prisma-next/contract/types';\n\n/**\n * Pre-compiled regex patterns for performance.\n * These are compiled once at module load time rather than on each function call.\n */\nconst NEXTVAL_PATTERN = /^nextval\\s*\\(/i;\nconst NOW_FUNCTION_PATTERN = /^(now\\s*\\(\\s*\\)|CURRENT_TIMESTAMP)$/i;\nconst CLOCK_TIMESTAMP_PATTERN = /^clock_timestamp\\s*\\(\\s*\\)$/i;\nconst TIMESTAMP_CAST_SUFFIX = /::timestamp(?:tz|\\s+(?:with|without)\\s+time\\s+zone)?$/i;\nconst TEXT_CAST_SUFFIX = /::text$/i;\nconst NOW_LITERAL_PATTERN = /^'now'$/i;\nconst UUID_PATTERN = /^gen_random_uuid\\s*\\(\\s*\\)$/i;\nconst UUID_OSSP_PATTERN = /^uuid_generate_v4\\s*\\(\\s*\\)$/i;\nconst NULL_PATTERN = /^NULL(?:::.+)?$/i;\nconst TRUE_PATTERN = /^true$/i;\nconst FALSE_PATTERN = /^false$/i;\nconst NUMERIC_PATTERN = /^-?\\d+(\\.\\d+)?$/;\nconst STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:\"[^\"]+\"|[\\w\\s]+)(?:\\(\\d+\\))?)?$/;\n\n/**\n * Returns the canonical expression for a timestamp default function, or undefined\n * if the expression is not a recognized timestamp default.\n *\n * Keeps now()/CURRENT_TIMESTAMP and clock_timestamp() distinct:\n * - now(), CURRENT_TIMESTAMP, ('now'::text)::timestamp... → 'now()'\n * - clock_timestamp(), clock_timestamp()::timestamptz → 'clock_timestamp()'\n *\n * These are semantically different in Postgres: now() returns the transaction\n * start time (constant within a transaction), while clock_timestamp() returns\n * the actual wall-clock time (can differ across rows in a single INSERT).\n */\nfunction canonicalizeTimestampDefault(expr: string): string | undefined {\n if (NOW_FUNCTION_PATTERN.test(expr)) return 'now()';\n if (CLOCK_TIMESTAMP_PATTERN.test(expr)) return 'clock_timestamp()';\n\n if (!TIMESTAMP_CAST_SUFFIX.test(expr)) return undefined;\n\n let inner = expr.replace(TIMESTAMP_CAST_SUFFIX, '').trim();\n\n if (inner.startsWith('(') && inner.endsWith(')')) {\n inner = inner.slice(1, -1).trim();\n }\n\n if (NOW_FUNCTION_PATTERN.test(inner)) return 'now()';\n if (CLOCK_TIMESTAMP_PATTERN.test(inner)) return 'clock_timestamp()';\n\n inner = inner.replace(TEXT_CAST_SUFFIX, '').trim();\n if (NOW_LITERAL_PATTERN.test(inner)) return 'now()';\n\n return undefined;\n}\n\n/**\n * Parses a raw Postgres column default expression into a normalized ColumnDefault.\n * This enables semantic comparison between contract defaults and introspected schema defaults.\n *\n * Used by the migration diff layer to normalize raw database defaults during comparison,\n * keeping the introspection layer focused on faithful data capture.\n *\n * @param rawDefault - Raw default expression from information_schema.columns.column_default\n * @param nativeType - Native column type, used for type-aware parsing (bigint tagging, JSON detection)\n * @returns Normalized ColumnDefault or undefined if the expression cannot be parsed\n */\nexport function parsePostgresDefault(\n rawDefault: string,\n nativeType?: string,\n): ColumnDefault | undefined {\n const trimmed = rawDefault.trim();\n const normalizedType = nativeType?.toLowerCase();\n const isBigInt = normalizedType === 'bigint' || normalizedType === 'int8';\n\n if (NEXTVAL_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'autoincrement()' };\n }\n\n const canonicalTimestamp = canonicalizeTimestampDefault(trimmed);\n if (canonicalTimestamp) {\n return { kind: 'function', expression: canonicalTimestamp };\n }\n\n if (UUID_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'gen_random_uuid()' };\n }\n\n if (UUID_OSSP_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'gen_random_uuid()' };\n }\n\n if (NULL_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: null };\n }\n\n if (TRUE_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: true };\n }\n if (FALSE_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: false };\n }\n\n if (NUMERIC_PATTERN.test(trimmed)) {\n const num = Number(trimmed);\n if (!Number.isFinite(num)) return undefined;\n if (isBigInt && !Number.isSafeInteger(num)) {\n return { kind: 'literal', value: trimmed };\n }\n return { kind: 'literal', value: num };\n }\n\n const stringMatch = trimmed.match(STRING_LITERAL_PATTERN);\n if (stringMatch?.[1] !== undefined) {\n const unescaped = stringMatch[1].replace(/''/g, \"'\");\n if (normalizedType === 'json' || normalizedType === 'jsonb') {\n try {\n return { kind: 'literal', value: JSON.parse(unescaped) };\n } catch {\n // Keep legacy behavior for malformed/non-JSON string content.\n }\n }\n if (isBigInt && NUMERIC_PATTERN.test(unescaped)) {\n const num = Number(unescaped);\n if (Number.isSafeInteger(num)) {\n return { kind: 'literal', value: num };\n }\n return { kind: 'literal', value: unescaped };\n }\n return { kind: 'literal', value: unescaped };\n }\n\n return { kind: 'function', expression: trimmed };\n}\n"],"mappings":";;;;;AAMA,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;AAC7B,MAAM,0BAA0B;AAChC,MAAM,wBAAwB;AAC9B,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAC5B,MAAM,eAAe;AACrB,MAAM,oBAAoB;AAC1B,MAAM,eAAe;AACrB,MAAM,eAAe;AACrB,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;AACxB,MAAM,yBAAyB;;;;;;;;;;;;;AAc/B,SAAS,6BAA6B,MAAkC;CACtE,IAAI,qBAAqB,KAAK,IA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AAG;EACjC,MAAM,MAAM,OAAO,OAAO;EAC1B,IAAI,CAAC,OAAO,SAAS,GAAG,GAAG,OAAO,KAAA;EAClC,IAAI,YAAY,CAAC,OAAO,cAAc,GAAG,GACvC,OAAO;GAAE,MAAM;GAAW,OAAO;EAAQ;EAE3C,OAAO;GAAE,MAAM;GAAW,OAAO;EAAI;CACvC;CAEA,MAAM,cAAc,QAAQ,MAAM,sBAAsB;CACxD,IAAI,cAAc,OAAO,KAAA,GAAW;EAClC,MAAM,YAAY,YAAY,EAAE,CAAC,QAAQ,OAAO,GAAG;EACnD,IAAI,mBAAmB,UAAU,mBAAmB,SAClD,IAAI;GACF,OAAO;IAAE,MAAM;IAAW,OAAO,KAAK,MAAM,SAAS;GAAE;EACzD,QAAQ,CAER;EAEF,IAAI,YAAY,gBAAgB,KAAK,SAAS,GAAG;GAC/C,MAAM,MAAM,OAAO,SAAS;GAC5B,IAAI,OAAO,cAAc,GAAG,GAC1B,OAAO;IAAE,MAAM;IAAW,OAAO;GAAI;GAEvC,OAAO;IAAE,MAAM;IAAW,OAAO;GAAU;EAC7C;EACA,OAAO;GAAE,MAAM;GAAW,OAAO;EAAU;CAC7C;CAEA,OAAO;EAAE,MAAM;EAAY,YAAY;CAAQ;AACjD"}
@@ -1,2 +1,2 @@
1
- import { t as parsePostgresDefault } from "./default-normalizer-CRscvhS5.mjs";
1
+ import { t as parsePostgresDefault } from "./default-normalizer-DyyCHQWs.mjs";
2
2
  export { parsePostgresDefault };
@@ -0,0 +1,14 @@
1
+ import { i as postgresAuthoringTypes, n as postgresAuthoringEntityTypes, r as postgresAuthoringFieldPresets, t as postgresTargetDescriptorMetaRuntime } from "./descriptor-meta-runtime-My8_s4cs.mjs";
2
+ const postgresTargetDescriptorMeta = {
3
+ ...postgresTargetDescriptorMetaRuntime,
4
+ defaultNamespaceId: "public",
5
+ authoring: {
6
+ type: postgresAuthoringTypes,
7
+ field: postgresAuthoringFieldPresets,
8
+ entityTypes: postgresAuthoringEntityTypes
9
+ }
10
+ };
11
+ //#endregion
12
+ export { postgresTargetDescriptorMeta as t };
13
+
14
+ //# sourceMappingURL=descriptor-meta-DKmj-IMN.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"descriptor-meta-DKmj-IMN.mjs","names":[],"sources":["../src/core/descriptor-meta.ts"],"sourcesContent":["import type { CodecTypes } from '../exports/codec-types';\nimport {\n postgresAuthoringEntityTypes,\n postgresAuthoringFieldPresets,\n postgresAuthoringTypes,\n} from './authoring';\nimport { postgresTargetDescriptorMetaRuntime } from './descriptor-meta-runtime';\n\nconst postgresTargetDescriptorMetaBase = {\n ...postgresTargetDescriptorMetaRuntime,\n defaultNamespaceId: 'public',\n authoring: {\n type: postgresAuthoringTypes,\n field: postgresAuthoringFieldPresets,\n entityTypes: postgresAuthoringEntityTypes,\n },\n} as const;\n\nexport const postgresTargetDescriptorMeta: typeof postgresTargetDescriptorMetaBase & {\n readonly __codecTypes?: CodecTypes;\n} = postgresTargetDescriptorMetaBase;\n"],"mappings":";AAkBA,MAAa,+BAET;CAXF,GAAG;CACH,oBAAoB;CACpB,WAAW;EACT,MAAM;EACN,OAAO;EACP,aAAa;CACf;AAKE"}