@prisma-next/target-postgres 0.4.1 → 0.4.3

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 (179) hide show
  1. package/dist/codec-ids-CojIXVf9.mjs +29 -0
  2. package/dist/codec-ids-CojIXVf9.mjs.map +1 -0
  3. package/dist/codec-ids.d.mts +28 -0
  4. package/dist/codec-ids.d.mts.map +1 -0
  5. package/dist/codec-ids.mjs +3 -0
  6. package/dist/codec-types.d.mts +42 -0
  7. package/dist/codec-types.d.mts.map +1 -0
  8. package/dist/codec-types.mjs +3 -0
  9. package/dist/codecs-CE5EUsNM.d.mts +323 -0
  10. package/dist/codecs-CE5EUsNM.d.mts.map +1 -0
  11. package/dist/codecs-dzZ_dMpK.mjs +290 -0
  12. package/dist/codecs-dzZ_dMpK.mjs.map +1 -0
  13. package/dist/codecs.d.mts +2 -0
  14. package/dist/codecs.mjs +3 -0
  15. package/dist/control.d.mts +1 -1
  16. package/dist/control.mjs +24 -1989
  17. package/dist/control.mjs.map +1 -1
  18. package/dist/data-transform-C83dy0vk.mjs +41 -0
  19. package/dist/data-transform-C83dy0vk.mjs.map +1 -0
  20. package/dist/data-transform-D8x5m1YV.d.mts +38 -0
  21. package/dist/data-transform-D8x5m1YV.d.mts.map +1 -0
  22. package/dist/data-transform.d.mts +2 -0
  23. package/dist/data-transform.mjs +3 -0
  24. package/dist/default-normalizer-DNOpRoOF.mjs +131 -0
  25. package/dist/default-normalizer-DNOpRoOF.mjs.map +1 -0
  26. package/dist/default-normalizer.d.mts +19 -0
  27. package/dist/default-normalizer.d.mts.map +1 -0
  28. package/dist/default-normalizer.mjs +3 -0
  29. package/dist/{descriptor-meta-DkvCmY98.mjs → descriptor-meta-BVoVtyp-.mjs} +1 -1
  30. package/dist/{descriptor-meta-DkvCmY98.mjs.map → descriptor-meta-BVoVtyp-.mjs.map} +1 -1
  31. package/dist/errors-AFvEPZ1R.mjs +34 -0
  32. package/dist/errors-AFvEPZ1R.mjs.map +1 -0
  33. package/dist/errors.d.mts +27 -0
  34. package/dist/errors.d.mts.map +1 -0
  35. package/dist/errors.mjs +3 -0
  36. package/dist/issue-planner-CFjB0_oO.mjs +879 -0
  37. package/dist/issue-planner-CFjB0_oO.mjs.map +1 -0
  38. package/dist/issue-planner.d.mts +85 -0
  39. package/dist/issue-planner.d.mts.map +1 -0
  40. package/dist/issue-planner.mjs +3 -0
  41. package/dist/migration.d.mts +5 -79
  42. package/dist/migration.d.mts.map +1 -1
  43. package/dist/migration.mjs +6 -428
  44. package/dist/migration.mjs.map +1 -1
  45. package/dist/native-type-normalizer-CInai_oY.mjs +38 -0
  46. package/dist/native-type-normalizer-CInai_oY.mjs.map +1 -0
  47. package/dist/native-type-normalizer.d.mts +18 -0
  48. package/dist/native-type-normalizer.d.mts.map +1 -0
  49. package/dist/native-type-normalizer.mjs +3 -0
  50. package/dist/op-factory-call-BKlruaiC.mjs +605 -0
  51. package/dist/op-factory-call-BKlruaiC.mjs.map +1 -0
  52. package/dist/op-factory-call-C3bWXKSP.d.mts +304 -0
  53. package/dist/op-factory-call-C3bWXKSP.d.mts.map +1 -0
  54. package/dist/op-factory-call.d.mts +3 -0
  55. package/dist/op-factory-call.mjs +3 -0
  56. package/dist/pack.d.mts +1 -1
  57. package/dist/pack.mjs +1 -1
  58. package/dist/planner-B4ZSLHRI.mjs +98 -0
  59. package/dist/planner-B4ZSLHRI.mjs.map +1 -0
  60. package/dist/planner-ddl-builders-Dxvw1LHw.mjs +132 -0
  61. package/dist/planner-ddl-builders-Dxvw1LHw.mjs.map +1 -0
  62. package/dist/planner-ddl-builders.d.mts +22 -0
  63. package/dist/planner-ddl-builders.d.mts.map +1 -0
  64. package/dist/planner-ddl-builders.mjs +3 -0
  65. package/dist/planner-identity-values-Dju-o5GF.mjs +91 -0
  66. package/dist/planner-identity-values-Dju-o5GF.mjs.map +1 -0
  67. package/dist/planner-identity-values.d.mts +20 -0
  68. package/dist/planner-identity-values.d.mts.map +1 -0
  69. package/dist/planner-identity-values.mjs +3 -0
  70. package/dist/planner-produced-postgres-migration-C0GNhHGw.mjs +32 -0
  71. package/dist/planner-produced-postgres-migration-C0GNhHGw.mjs.map +1 -0
  72. package/dist/planner-produced-postgres-migration-Dw_mPMKt.d.mts +20 -0
  73. package/dist/planner-produced-postgres-migration-Dw_mPMKt.d.mts.map +1 -0
  74. package/dist/planner-produced-postgres-migration.d.mts +5 -0
  75. package/dist/planner-produced-postgres-migration.mjs +3 -0
  76. package/dist/planner-schema-lookup-B7lkypwn.mjs +29 -0
  77. package/dist/planner-schema-lookup-B7lkypwn.mjs.map +1 -0
  78. package/dist/planner-schema-lookup.d.mts +22 -0
  79. package/dist/planner-schema-lookup.d.mts.map +1 -0
  80. package/dist/planner-schema-lookup.mjs +3 -0
  81. package/dist/planner-sql-checks-7jkgm9TX.mjs +241 -0
  82. package/dist/planner-sql-checks-7jkgm9TX.mjs.map +1 -0
  83. package/dist/planner-sql-checks.d.mts +55 -0
  84. package/dist/planner-sql-checks.d.mts.map +1 -0
  85. package/dist/planner-sql-checks.mjs +3 -0
  86. package/dist/{planner-target-details-MXb3oeul.d.mts → planner-target-details-DH-azLu-.d.mts} +1 -1
  87. package/dist/{planner-target-details-MXb3oeul.d.mts.map → planner-target-details-DH-azLu-.d.mts.map} +1 -1
  88. package/dist/planner-target-details.d.mts +2 -0
  89. package/dist/planner-target-details.mjs +1 -0
  90. package/dist/planner.d.mts +74 -0
  91. package/dist/planner.d.mts.map +1 -0
  92. package/dist/planner.mjs +4 -0
  93. package/dist/postgres-migration-DcfWGqhe.d.mts +50 -0
  94. package/dist/postgres-migration-DcfWGqhe.d.mts.map +1 -0
  95. package/dist/postgres-migration-EGSlO4jO.mjs +52 -0
  96. package/dist/postgres-migration-EGSlO4jO.mjs.map +1 -0
  97. package/dist/render-ops-D6_DHdOK.mjs +8 -0
  98. package/dist/render-ops-D6_DHdOK.mjs.map +1 -0
  99. package/dist/render-ops.d.mts +11 -0
  100. package/dist/render-ops.d.mts.map +1 -0
  101. package/dist/render-ops.mjs +3 -0
  102. package/dist/render-typescript-Co3Emwgz.mjs +84 -0
  103. package/dist/render-typescript-Co3Emwgz.mjs.map +1 -0
  104. package/dist/render-typescript.d.mts +14 -0
  105. package/dist/render-typescript.d.mts.map +1 -0
  106. package/dist/render-typescript.mjs +3 -0
  107. package/dist/runtime.d.mts +15 -3
  108. package/dist/runtime.d.mts.map +1 -1
  109. package/dist/runtime.mjs +10 -1
  110. package/dist/runtime.mjs.map +1 -1
  111. package/dist/shared-Bxkt8pNO.d.mts +41 -0
  112. package/dist/shared-Bxkt8pNO.d.mts.map +1 -0
  113. package/dist/sql-utils-r-Lw535w.mjs +76 -0
  114. package/dist/sql-utils-r-Lw535w.mjs.map +1 -0
  115. package/dist/sql-utils.d.mts +59 -0
  116. package/dist/sql-utils.d.mts.map +1 -0
  117. package/dist/sql-utils.mjs +3 -0
  118. package/dist/statement-builders-CHqCtSfe.mjs +121 -0
  119. package/dist/statement-builders-CHqCtSfe.mjs.map +1 -0
  120. package/dist/statement-builders.d.mts +30 -0
  121. package/dist/statement-builders.d.mts.map +1 -0
  122. package/dist/statement-builders.mjs +3 -0
  123. package/dist/tables-BmdW_FWO.mjs +477 -0
  124. package/dist/tables-BmdW_FWO.mjs.map +1 -0
  125. package/dist/types-ClK03Ojd.d.mts +10 -0
  126. package/dist/types-ClK03Ojd.d.mts.map +1 -0
  127. package/dist/types.d.mts +2 -0
  128. package/dist/types.mjs +1 -0
  129. package/package.json +40 -20
  130. package/src/core/codec-ids.ts +30 -0
  131. package/src/core/codecs.ts +622 -0
  132. package/src/core/default-normalizer.ts +131 -0
  133. package/src/core/descriptor-meta.ts +1 -1
  134. package/src/core/errors.ts +33 -0
  135. package/src/core/migrations/op-factory-call.ts +1 -5
  136. package/src/core/migrations/operations/columns.ts +1 -1
  137. package/src/core/migrations/operations/constraints.ts +1 -1
  138. package/src/core/migrations/operations/data-transform.ts +35 -21
  139. package/src/core/migrations/operations/dependencies.ts +1 -1
  140. package/src/core/migrations/operations/enums.ts +1 -1
  141. package/src/core/migrations/operations/indexes.ts +1 -1
  142. package/src/core/migrations/operations/shared.ts +1 -1
  143. package/src/core/migrations/operations/tables.ts +1 -1
  144. package/src/core/migrations/planner-ddl-builders.ts +1 -1
  145. package/src/core/migrations/planner-produced-postgres-migration.ts +0 -1
  146. package/src/core/migrations/planner-recipes.ts +1 -1
  147. package/src/core/migrations/planner-sql-checks.ts +1 -1
  148. package/src/core/migrations/planner.ts +19 -15
  149. package/src/core/migrations/postgres-migration.ts +54 -1
  150. package/src/core/migrations/render-typescript.ts +23 -17
  151. package/src/core/migrations/runner.ts +47 -13
  152. package/src/core/migrations/statement-builders.ts +22 -6
  153. package/src/core/native-type-normalizer.ts +49 -0
  154. package/src/core/sql-utils.ts +104 -0
  155. package/src/exports/codec-ids.ts +1 -0
  156. package/src/exports/codec-types.ts +51 -0
  157. package/src/exports/codecs.ts +2 -0
  158. package/src/exports/data-transform.ts +1 -0
  159. package/src/exports/default-normalizer.ts +1 -0
  160. package/src/exports/errors.ts +1 -0
  161. package/src/exports/issue-planner.ts +1 -0
  162. package/src/exports/migration.ts +6 -0
  163. package/src/exports/native-type-normalizer.ts +1 -0
  164. package/src/exports/op-factory-call.ts +25 -0
  165. package/src/exports/planner-ddl-builders.ts +8 -0
  166. package/src/exports/planner-identity-values.ts +1 -0
  167. package/src/exports/planner-produced-postgres-migration.ts +1 -0
  168. package/src/exports/planner-schema-lookup.ts +6 -0
  169. package/src/exports/planner-sql-checks.ts +11 -0
  170. package/src/exports/planner-target-details.ts +1 -0
  171. package/src/exports/planner.ts +1 -0
  172. package/src/exports/render-ops.ts +1 -0
  173. package/src/exports/render-typescript.ts +1 -0
  174. package/src/exports/runtime.ts +19 -4
  175. package/src/exports/sql-utils.ts +7 -0
  176. package/src/exports/statement-builders.ts +7 -0
  177. package/src/exports/types.ts +1 -0
  178. package/dist/postgres-migration-BsHJHV9O.mjs +0 -2793
  179. package/dist/postgres-migration-BsHJHV9O.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"control.mjs","names":["notNullBackfillCallStrategy: CallMigrationStrategy","matched: SchemaIssue[]","calls: PostgresOpFactoryCall[]","typeChangeCallStrategy: CallMigrationStrategy","nullableTighteningCallStrategy: CallMigrationStrategy","columnRefs: { table: string; column: string }[]","enumChangeCallStrategy: CallMigrationStrategy","storageTypePlanCallStrategy: CallMigrationStrategy","dependencyInstallCallStrategy: CallMigrationStrategy","notNullAddColumnCallStrategy: CallMigrationStrategy","postgresPlannerStrategies: readonly CallMigrationStrategy[]","ISSUE_KIND_ORDER: Record<string, number>","columns: ColumnSpec[]","calls: PostgresOpFactoryCall[]","fkSpec: ForeignKeySpec","DEFAULT_POLICY: MigrationOperationPolicy","location: {\n table?: string;\n column?: string;\n index?: string;\n constraint?: string;\n type?: string;\n }","context: StrategyContext","recipeCalls: PostgresOpFactoryCall[]","bucketablePatternCalls: PostgresOpFactoryCall[]","defaultCalls: PostgresOpFactoryCall[]","conflicts: SqlPlannerConflict[]","gatedDefaultBucket: PostgresOpFactoryCall[]","gatedRecipeBucket: PostgresOpFactoryCall[]","gatedBucketableBucket: PostgresOpFactoryCall[]","BASE_IMPORT: ImportRequirement","requirements: ImportRequirement[]","lines: string[]","#calls","#meta","DEFAULT_PLANNER_CONFIG: PlannerConfig","config: PlannerConfig","ensurePrismaContractSchemaStatement: SqlStatement","ensureMarkerTableStatement: SqlStatement","ensureLedgerTableStatement: SqlStatement","params: readonly unknown[]","DEFAULT_CONFIG: RunnerConfig","cloned: Record<string, unknown>","family: SqlControlFamilyInstance","config: RunnerConfig","applyValue: ApplyPlanSuccessValue","executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>","error: unknown","postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails>"],"sources":["../src/core/migrations/op-factory-call.ts","../src/core/migrations/planner-ddl-builders.ts","../src/core/migrations/planner-identity-values.ts","../src/core/migrations/planner-target-details.ts","../src/core/migrations/planner-recipes.ts","../src/core/migrations/planner-schema-lookup.ts","../src/core/migrations/planner-strategies.ts","../src/core/migrations/issue-planner.ts","../src/core/migrations/render-ops.ts","../src/core/migrations/render-typescript.ts","../src/core/migrations/planner-produced-postgres-migration.ts","../src/core/migrations/planner.ts","../src/core/migrations/statement-builders.ts","../src/core/migrations/runner.ts","../src/exports/control.ts"],"sourcesContent":["/**\n * Postgres migration IR: one concrete `*Call` class per pure factory under\n * `operations/`, plus a shared `PostgresOpFactoryCallNode` abstract base.\n *\n * Every call class carries the literal arguments its backing factory would\n * receive, computes a human-readable `label` in its constructor, and\n * implements two polymorphic hooks:\n *\n * - `toOp()` — converts the IR node to a runtime\n * `SqlMigrationPlanOperation` by delegating to the matching pure factory\n * under `operations/`. `DataTransformCall.toOp()` always throws\n * `PN-MIG-2001` because a planner-generated data transform is an\n * unfilled authoring stub by construction.\n * - `renderTypeScript()` / `importRequirements()` — inherited from\n * `TsExpression`. Used by `renderCallsToTypeScript` to emit the call as\n * a TypeScript expression inside the scaffolded `migration.ts`.\n *\n * The abstract base and all concrete classes are package-private. External\n * consumers see only the framework-level `OpFactoryCall` interface and the\n * `PostgresOpFactoryCall` union.\n */\n\nimport { errorUnfilledPlaceholder } from '@prisma-next/errors/migration';\nimport type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type {\n OpFactoryCall as FrameworkOpFactoryCall,\n MigrationOperationClass,\n} from '@prisma-next/framework-components/control';\nimport { type ImportRequirement, jsonToTsSource, TsExpression } from '@prisma-next/ts-render';\nimport {\n addColumn,\n alterColumnType,\n dropColumn,\n dropDefault,\n dropNotNull,\n setDefault,\n setNotNull,\n} from './operations/columns';\nimport { addForeignKey, addPrimaryKey, addUnique, dropConstraint } from './operations/constraints';\nimport { createExtension, createSchema } from './operations/dependencies';\nimport { addEnumValues, createEnumType, dropEnumType, renameType } from './operations/enums';\nimport { createIndex, dropIndex } from './operations/indexes';\nimport type { ColumnSpec, ForeignKeySpec } from './operations/shared';\nimport { createTable, dropTable } from './operations/tables';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\n\ntype Op = SqlMigrationPlanOperation<PostgresPlanTargetDetails>;\n\nconst TARGET_MIGRATION_MODULE = '@prisma-next/target-postgres/migration';\n\nabstract class PostgresOpFactoryCallNode extends TsExpression implements FrameworkOpFactoryCall {\n abstract readonly factoryName: string;\n abstract readonly operationClass: MigrationOperationClass;\n abstract readonly label: string;\n abstract toOp(): Op;\n\n importRequirements(): readonly ImportRequirement[] {\n return [{ moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: this.factoryName }];\n }\n\n protected freeze(): void {\n Object.freeze(this);\n }\n}\n\n// ============================================================================\n// Table\n// ============================================================================\n\nexport interface CreateTablePrimaryKey {\n readonly columns: readonly string[];\n}\n\nexport class CreateTableCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'createTable' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly columns: readonly ColumnSpec[];\n readonly primaryKey: CreateTablePrimaryKey | undefined;\n readonly label: string;\n\n constructor(\n schemaName: string,\n tableName: string,\n columns: readonly ColumnSpec[],\n primaryKey?: CreateTablePrimaryKey,\n ) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.columns = columns;\n this.primaryKey = primaryKey;\n this.label = `Create table \"${tableName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return createTable(this.schemaName, this.tableName, this.columns, this.primaryKey);\n }\n\n renderTypeScript(): string {\n const args = [\n jsonToTsSource(this.schemaName),\n jsonToTsSource(this.tableName),\n jsonToTsSource(this.columns),\n ];\n if (this.primaryKey) args.push(jsonToTsSource(this.primaryKey));\n return `createTable(${args.join(', ')})`;\n }\n}\n\nexport class DropTableCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dropTable' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.label = `Drop table \"${tableName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropTable(this.schemaName, this.tableName);\n }\n\n renderTypeScript(): string {\n return `dropTable(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.tableName)})`;\n }\n}\n\n// ============================================================================\n// Column\n// ============================================================================\n\nexport class AddColumnCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'addColumn' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly column: ColumnSpec;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, column: ColumnSpec) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.column = column;\n this.label = `Add column \"${column.name}\" to \"${tableName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return addColumn(this.schemaName, this.tableName, this.column);\n }\n\n renderTypeScript(): string {\n return `addColumn(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.column)})`;\n }\n}\n\nexport class DropColumnCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dropColumn' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, columnName: string) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.columnName = columnName;\n this.label = `Drop column \"${columnName}\" from \"${tableName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropColumn(this.schemaName, this.tableName, this.columnName);\n }\n\n renderTypeScript(): string {\n return `dropColumn(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.columnName)})`;\n }\n}\n\nexport interface AlterColumnTypeOptions {\n readonly qualifiedTargetType: string;\n readonly formatTypeExpected: string;\n readonly rawTargetTypeForLabel: string;\n readonly using?: string;\n}\n\nexport class AlterColumnTypeCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'alterColumnType' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly options: AlterColumnTypeOptions;\n readonly label: string;\n\n constructor(\n schemaName: string,\n tableName: string,\n columnName: string,\n options: AlterColumnTypeOptions,\n ) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.columnName = columnName;\n this.options = options;\n this.label = `Alter type of \"${tableName}\".\"${columnName}\" to ${options.rawTargetTypeForLabel}`;\n this.freeze();\n }\n\n toOp(): Op {\n return alterColumnType(this.schemaName, this.tableName, this.columnName, this.options);\n }\n\n renderTypeScript(): string {\n return `alterColumnType(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.columnName)}, ${jsonToTsSource(this.options)})`;\n }\n}\n\nexport class SetNotNullCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'setNotNull' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, columnName: string) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.columnName = columnName;\n this.label = `Set NOT NULL on \"${tableName}\".\"${columnName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return setNotNull(this.schemaName, this.tableName, this.columnName);\n }\n\n renderTypeScript(): string {\n return `setNotNull(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.columnName)})`;\n }\n}\n\nexport class DropNotNullCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dropNotNull' as const;\n readonly operationClass = 'widening' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, columnName: string) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.columnName = columnName;\n this.label = `Drop NOT NULL on \"${tableName}\".\"${columnName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropNotNull(this.schemaName, this.tableName, this.columnName);\n }\n\n renderTypeScript(): string {\n return `dropNotNull(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.columnName)})`;\n }\n}\n\nexport class SetDefaultCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'setDefault' as const;\n readonly operationClass: 'additive' | 'widening';\n readonly schemaName: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly defaultSql: string;\n readonly label: string;\n\n constructor(\n schemaName: string,\n tableName: string,\n columnName: string,\n defaultSql: string,\n operationClass: 'additive' | 'widening' = 'additive',\n ) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.columnName = columnName;\n this.defaultSql = defaultSql;\n this.operationClass = operationClass;\n this.label = `Set default on \"${tableName}\".\"${columnName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return setDefault(\n this.schemaName,\n this.tableName,\n this.columnName,\n this.defaultSql,\n this.operationClass,\n );\n }\n\n renderTypeScript(): string {\n const args = [\n jsonToTsSource(this.schemaName),\n jsonToTsSource(this.tableName),\n jsonToTsSource(this.columnName),\n jsonToTsSource(this.defaultSql),\n ];\n if (this.operationClass !== 'additive') {\n args.push(jsonToTsSource(this.operationClass));\n }\n return `setDefault(${args.join(', ')})`;\n }\n}\n\nexport class DropDefaultCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dropDefault' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, columnName: string) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.columnName = columnName;\n this.label = `Drop default on \"${tableName}\".\"${columnName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropDefault(this.schemaName, this.tableName, this.columnName);\n }\n\n renderTypeScript(): string {\n return `dropDefault(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.columnName)})`;\n }\n}\n\n// ============================================================================\n// Constraints\n// ============================================================================\n\nexport class AddPrimaryKeyCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'addPrimaryKey' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly constraintName: string;\n readonly columns: readonly string[];\n readonly label: string;\n\n constructor(\n schemaName: string,\n tableName: string,\n constraintName: string,\n columns: readonly string[],\n ) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.constraintName = constraintName;\n this.columns = columns;\n this.label = `Add primary key on \"${tableName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return addPrimaryKey(this.schemaName, this.tableName, this.constraintName, this.columns);\n }\n\n renderTypeScript(): string {\n return `addPrimaryKey(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.constraintName)}, ${jsonToTsSource(this.columns)})`;\n }\n}\n\nexport class AddUniqueCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'addUnique' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly constraintName: string;\n readonly columns: readonly string[];\n readonly label: string;\n\n constructor(\n schemaName: string,\n tableName: string,\n constraintName: string,\n columns: readonly string[],\n ) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.constraintName = constraintName;\n this.columns = columns;\n this.label = `Add unique constraint on \"${tableName}\" (${columns.join(', ')})`;\n this.freeze();\n }\n\n toOp(): Op {\n return addUnique(this.schemaName, this.tableName, this.constraintName, this.columns);\n }\n\n renderTypeScript(): string {\n return `addUnique(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.constraintName)}, ${jsonToTsSource(this.columns)})`;\n }\n}\n\nexport class AddForeignKeyCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'addForeignKey' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly fk: ForeignKeySpec;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, fk: ForeignKeySpec) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.fk = fk;\n this.label = `Add foreign key \"${fk.name}\" on \"${tableName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return addForeignKey(this.schemaName, this.tableName, this.fk);\n }\n\n renderTypeScript(): string {\n return `addForeignKey(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.fk)})`;\n }\n}\n\nexport class DropConstraintCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dropConstraint' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly constraintName: string;\n readonly kind: 'foreignKey' | 'unique' | 'primaryKey';\n readonly label: string;\n\n constructor(\n schemaName: string,\n tableName: string,\n constraintName: string,\n kind: 'foreignKey' | 'unique' | 'primaryKey' = 'unique',\n ) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.constraintName = constraintName;\n this.kind = kind;\n this.label = `Drop constraint \"${constraintName}\" on \"${tableName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropConstraint(this.schemaName, this.tableName, this.constraintName, this.kind);\n }\n\n renderTypeScript(): string {\n const args = [\n jsonToTsSource(this.schemaName),\n jsonToTsSource(this.tableName),\n jsonToTsSource(this.constraintName),\n ];\n if (this.kind !== 'unique') {\n args.push(jsonToTsSource(this.kind));\n }\n return `dropConstraint(${args.join(', ')})`;\n }\n}\n\n// ============================================================================\n// Indexes\n// ============================================================================\n\nexport class CreateIndexCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'createIndex' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly indexName: string;\n readonly columns: readonly string[];\n readonly label: string;\n\n constructor(\n schemaName: string,\n tableName: string,\n indexName: string,\n columns: readonly string[],\n ) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.indexName = indexName;\n this.columns = columns;\n this.label = `Create index \"${indexName}\" on \"${tableName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return createIndex(this.schemaName, this.tableName, this.indexName, this.columns);\n }\n\n renderTypeScript(): string {\n return `createIndex(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.indexName)}, ${jsonToTsSource(this.columns)})`;\n }\n}\n\nexport class DropIndexCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dropIndex' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly indexName: string;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, indexName: string) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.indexName = indexName;\n this.label = `Drop index \"${indexName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropIndex(this.schemaName, this.tableName, this.indexName);\n }\n\n renderTypeScript(): string {\n return `dropIndex(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.indexName)})`;\n }\n}\n\n// ============================================================================\n// Enum types\n// ============================================================================\n\nexport class CreateEnumTypeCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'createEnumType' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly typeName: string;\n readonly values: readonly string[];\n readonly label: string;\n\n constructor(schemaName: string, typeName: string, values: readonly string[]) {\n super();\n this.schemaName = schemaName;\n this.typeName = typeName;\n this.values = values;\n this.label = `Create enum type \"${typeName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return createEnumType(this.schemaName, this.typeName, this.values);\n }\n\n renderTypeScript(): string {\n return `createEnumType(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.typeName)}, ${jsonToTsSource(this.values)})`;\n }\n}\n\nexport class AddEnumValuesCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'addEnumValues' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly typeName: string;\n readonly nativeType: string;\n readonly values: readonly string[];\n readonly label: string;\n\n constructor(schemaName: string, typeName: string, nativeType: string, values: readonly string[]) {\n super();\n this.schemaName = schemaName;\n this.typeName = typeName;\n this.nativeType = nativeType;\n this.values = values;\n this.label = `Add values to enum type \"${typeName}\": ${values.join(', ')}`;\n this.freeze();\n }\n\n toOp(): Op {\n return addEnumValues(this.schemaName, this.typeName, this.nativeType, this.values);\n }\n\n renderTypeScript(): string {\n return `addEnumValues(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.typeName)}, ${jsonToTsSource(this.nativeType)}, ${jsonToTsSource(this.values)})`;\n }\n}\n\nexport class DropEnumTypeCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dropEnumType' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly typeName: string;\n readonly label: string;\n\n constructor(schemaName: string, typeName: string) {\n super();\n this.schemaName = schemaName;\n this.typeName = typeName;\n this.label = `Drop enum type \"${typeName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropEnumType(this.schemaName, this.typeName);\n }\n\n renderTypeScript(): string {\n return `dropEnumType(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.typeName)})`;\n }\n}\n\nexport class RenameTypeCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'renameType' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly fromName: string;\n readonly toName: string;\n readonly label: string;\n\n constructor(schemaName: string, fromName: string, toName: string) {\n super();\n this.schemaName = schemaName;\n this.fromName = fromName;\n this.toName = toName;\n this.label = `Rename type \"${fromName}\" to \"${toName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return renameType(this.schemaName, this.fromName, this.toName);\n }\n\n renderTypeScript(): string {\n return `renameType(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.fromName)}, ${jsonToTsSource(this.toName)})`;\n }\n}\n\n// ============================================================================\n// Raw SQL\n// ============================================================================\n\n/**\n * Laundered pre-built operation.\n *\n * Wraps an already-materialized `SqlMigrationPlanOperation` — typically one\n * produced by a SQL-family method, a codec control hook, or a component\n * `databaseDependencies.init` declaration — so the planner can carry it\n * alongside IR nodes without reverse-engineering it into a\n * structured call class. Doubles as the user-facing escape hatch for raw\n * migrations: authors can pass a full op shape to `rawSql({...})`.\n *\n * `toOp()` returns the stored op unchanged. `renderTypeScript()` emits\n * `rawSql({...})` with the op serialized as a JSON literal — round-tripping\n * requires every field on the op to be JSON-serializable (no closures).\n */\nexport class RawSqlCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'rawSql' as const;\n readonly operationClass: MigrationOperationClass;\n readonly label: string;\n readonly op: Op;\n\n constructor(op: Op) {\n super();\n this.op = op;\n this.label = op.label;\n this.operationClass = op.operationClass;\n this.freeze();\n }\n\n toOp(): Op {\n return this.op;\n }\n\n renderTypeScript(): string {\n return `rawSql(${jsonToTsSource(this.op)})`;\n }\n}\n\n// ============================================================================\n// Database dependencies (structured DDL)\n// ============================================================================\n\nexport class CreateExtensionCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'createExtension' as const;\n readonly operationClass = 'additive' as const;\n readonly extensionName: string;\n readonly label: string;\n\n constructor(extensionName: string) {\n super();\n this.extensionName = extensionName;\n this.label = `Create extension \"${extensionName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return createExtension(this.extensionName);\n }\n\n renderTypeScript(): string {\n return `createExtension(${jsonToTsSource(this.extensionName)})`;\n }\n}\n\nexport class CreateSchemaCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'createSchema' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly label: string;\n\n constructor(schemaName: string) {\n super();\n this.schemaName = schemaName;\n this.label = `Create schema \"${schemaName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return createSchema(this.schemaName);\n }\n\n renderTypeScript(): string {\n return `createSchema(${jsonToTsSource(this.schemaName)})`;\n }\n}\n\n// ============================================================================\n// Data transform\n// ============================================================================\n\n/**\n * A planner-generated data-transform stub. `checkSlot` and `runSlot` name\n * the unfilled authoring slots that the rendered `migration.ts` will expose\n * to the user via `placeholder(\"…\")` calls. `toOp()` always throws\n * `PN-MIG-2001`: the planner cannot lower a stubbed transform to a runtime\n * op — the user must fill the rendered `migration.ts` and re-emit.\n */\nexport class DataTransformCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dataTransform' as const;\n readonly operationClass: MigrationOperationClass;\n readonly label: string;\n readonly checkSlot: string;\n readonly runSlot: string;\n\n constructor(\n label: string,\n checkSlot: string,\n runSlot: string,\n operationClass: MigrationOperationClass = 'data',\n ) {\n super();\n this.label = label;\n this.checkSlot = checkSlot;\n this.runSlot = runSlot;\n this.operationClass = operationClass;\n this.freeze();\n }\n\n toOp(): Op {\n throw errorUnfilledPlaceholder(this.label);\n }\n\n renderTypeScript(): string {\n return [\n `dataTransform(endContract, ${jsonToTsSource(this.label)}, {`,\n ` check: () => placeholder(${jsonToTsSource(this.checkSlot)}),`,\n ` run: () => placeholder(${jsonToTsSource(this.runSlot)}),`,\n '})',\n ].join('\\n');\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [\n { moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: this.factoryName },\n // `placeholder` is re-exported from `@prisma-next/target-postgres/migration`\n // so the user's migration.ts only depends on a single migration-authoring\n // entrypoint.\n { moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: 'placeholder' },\n {\n moduleSpecifier: './end-contract.json',\n symbol: 'endContract',\n kind: 'default',\n attributes: { type: 'json' },\n },\n ];\n }\n}\n\nexport type PostgresOpFactoryCall =\n | CreateTableCall\n | DropTableCall\n | AddColumnCall\n | DropColumnCall\n | AlterColumnTypeCall\n | SetNotNullCall\n | DropNotNullCall\n | SetDefaultCall\n | DropDefaultCall\n | AddPrimaryKeyCall\n | AddForeignKeyCall\n | AddUniqueCall\n | CreateIndexCall\n | DropIndexCall\n | DropConstraintCall\n | CreateEnumTypeCall\n | AddEnumValuesCall\n | DropEnumTypeCall\n | RenameTypeCall\n | RawSqlCall\n | CreateExtensionCall\n | CreateSchemaCall\n | DataTransformCall;\n\n/**\n * Stable identity key for reconciliation-level dedup.\n *\n * Two calls whose runtime ops would share the same `id` return the same\n * key, so a `Set<string>` can collapse them before they're emitted. The\n * current implementation delegates to `toOp().id`, which is the\n * authoritative identity; isolating dedup behind this helper lets a future\n * pass replace it with an allocation-free computation directly from the\n * call's fields without touching call sites.\n *\n * `DataTransformCall` intentionally has no sensible identity today — it\n * throws `PN-MIG-2001` on `toOp()`. Reconciliation never produces one; the\n * helper is unspecified for that variant and only meant for\n * reconciliation-emitted calls.\n */\nexport function identityKeyFor(call: PostgresOpFactoryCall): string {\n return call.toOp().id;\n}\n","import { escapeLiteral, quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type {\n ForeignKey,\n ReferentialAction,\n StorageColumn,\n StorageTable,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport type { PostgresColumnDefault } from '../types';\nimport { qualifyTableName } from './planner-sql-checks';\nimport { resolveColumnTypeMetadata } from './planner-type-resolution';\n\nexport function buildCreateTableSql(\n qualifiedTableName: string,\n table: StorageTable,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance> = {},\n): string {\n const columnDefinitions = Object.entries(table.columns).map(\n ([columnName, column]: [string, StorageColumn]) => {\n const parts = [\n quoteIdentifier(columnName),\n buildColumnTypeSql(column, codecHooks, storageTypes),\n buildColumnDefaultSql(column.default, column),\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n },\n );\n\n const constraintDefinitions: string[] = [];\n if (table.primaryKey) {\n constraintDefinitions.push(\n `PRIMARY KEY (${table.primaryKey.columns.map(quoteIdentifier).join(', ')})`,\n );\n }\n\n const allDefinitions = [...columnDefinitions, ...constraintDefinitions];\n return `CREATE TABLE ${qualifiedTableName} (\\n ${allDefinitions.join(',\\n ')}\\n)`;\n}\n\n/**\n * Pattern for safe PostgreSQL type names.\n * Allows letters, digits, underscores, spaces (for \"double precision\", \"character varying\"),\n * and trailing [] for array types.\n */\nconst SAFE_NATIVE_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9_ ]*(\\[\\])?$/;\n\nfunction assertSafeNativeType(nativeType: string): void {\n if (!SAFE_NATIVE_TYPE_PATTERN.test(nativeType)) {\n throw new Error(\n `Unsafe native type name in contract: \"${nativeType}\". ` +\n 'Native type names must match /^[a-zA-Z][a-zA-Z0-9_ ]*(\\\\[\\\\])?$/',\n );\n }\n}\n\n/**\n * Sanity check against accidental SQL injection from malformed contract files.\n * Rejects semicolons, SQL comment tokens, and dollar-quoting.\n * Not a comprehensive security boundary — the contract is developer-authored.\n */\nfunction assertSafeDefaultExpression(expression: string): void {\n if (expression.includes(';') || /--|\\/\\*|\\$\\$|\\bSELECT\\b/i.test(expression)) {\n throw new Error(\n `Unsafe default expression in contract: \"${expression}\". ` +\n 'Default expressions must not contain semicolons, SQL comment tokens, dollar-quoting, or subqueries.',\n );\n }\n}\n\n/**\n * Renders the SQL type for a column in DDL context.\n *\n * @param allowPseudoTypes - When true (default), autoincrement integer columns\n * produce SERIAL/BIGSERIAL/SMALLSERIAL pseudo-types. Set to false for contexts\n * like ALTER COLUMN TYPE where pseudo-types are invalid.\n */\nexport function buildColumnTypeSql(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance> = {},\n allowPseudoTypes = true,\n): string {\n const resolved = resolveColumnTypeMetadata(column, storageTypes);\n\n if (allowPseudoTypes) {\n const columnDefault = column.default;\n if (columnDefault?.kind === 'function' && columnDefault.expression === 'autoincrement()') {\n if (resolved.nativeType === 'int4' || resolved.nativeType === 'integer') {\n return 'SERIAL';\n }\n if (resolved.nativeType === 'int8' || resolved.nativeType === 'bigint') {\n return 'BIGSERIAL';\n }\n if (resolved.nativeType === 'int2' || resolved.nativeType === 'smallint') {\n return 'SMALLSERIAL';\n }\n }\n }\n\n const expanded = expandParameterizedTypeSql(resolved, codecHooks);\n if (expanded !== null) {\n return expanded;\n }\n\n if (column.typeRef) {\n return quoteIdentifier(resolved.nativeType);\n }\n\n assertSafeNativeType(resolved.nativeType);\n return resolved.nativeType;\n}\n\nfunction expandParameterizedTypeSql(\n column: Pick<StorageColumn, 'nativeType' | 'codecId' | 'typeParams'>,\n codecHooks: Map<string, CodecControlHooks>,\n): string | null {\n if (!column.typeParams) {\n return null;\n }\n\n if (!column.codecId) {\n throw new Error(\n `Column declares typeParams for nativeType \"${column.nativeType}\" but has no codecId. ` +\n 'Ensure the column is associated with a codec.',\n );\n }\n\n const hooks = codecHooks.get(column.codecId);\n if (!hooks?.expandNativeType) {\n if (hooks?.planTypeOperations) {\n return null;\n }\n throw new Error(\n `Column declares typeParams for nativeType \"${column.nativeType}\" ` +\n `but no expandNativeType hook is registered for codecId \"${column.codecId}\". ` +\n 'Ensure the extension providing this codec is included in extensionPacks.',\n );\n }\n\n const expanded = hooks.expandNativeType({\n nativeType: column.nativeType,\n codecId: column.codecId,\n typeParams: column.typeParams,\n });\n\n return expanded !== column.nativeType ? expanded : null;\n}\n\n/** Autoincrement columns use SERIAL types, so this returns empty for them. */\nexport function buildColumnDefaultSql(\n columnDefault: PostgresColumnDefault | undefined,\n column?: StorageColumn,\n): string {\n if (!columnDefault) {\n return '';\n }\n\n switch (columnDefault.kind) {\n case 'literal':\n return `DEFAULT ${renderDefaultLiteral(columnDefault.value, column)}`;\n case 'function': {\n if (columnDefault.expression === 'autoincrement()') {\n return '';\n }\n assertSafeDefaultExpression(columnDefault.expression);\n return `DEFAULT (${columnDefault.expression})`;\n }\n case 'sequence':\n return `DEFAULT nextval('${escapeLiteral(quoteIdentifier(columnDefault.name))}'::regclass)`;\n }\n}\n\nexport function renderDefaultLiteral(value: unknown, column?: StorageColumn): string {\n const isJsonColumn = column?.nativeType === 'json' || column?.nativeType === 'jsonb';\n\n if (value instanceof Date) {\n return `'${escapeLiteral(value.toISOString())}'`;\n }\n if (typeof value === 'string') {\n return `'${escapeLiteral(value)}'`;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (value === null) {\n return 'NULL';\n }\n const json = JSON.stringify(value);\n if (isJsonColumn) {\n return `'${escapeLiteral(json)}'::${column.nativeType}`;\n }\n return `'${escapeLiteral(json)}'`;\n}\n\nexport function buildAddColumnSql(\n qualifiedTableName: string,\n columnName: string,\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n temporaryDefault?: string | null,\n storageTypes: Record<string, StorageTypeInstance> = {},\n): string {\n const typeSql = buildColumnTypeSql(column, codecHooks, storageTypes);\n const defaultSql =\n buildColumnDefaultSql(column.default, column) ||\n (temporaryDefault ? `DEFAULT ${temporaryDefault}` : '');\n const parts = [\n `ALTER TABLE ${qualifiedTableName}`,\n `ADD COLUMN ${quoteIdentifier(columnName)} ${typeSql}`,\n defaultSql,\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n}\n\nconst REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string> = {\n noAction: 'NO ACTION',\n restrict: 'RESTRICT',\n cascade: 'CASCADE',\n setNull: 'SET NULL',\n setDefault: 'SET DEFAULT',\n};\n\nexport function buildForeignKeySql(\n schemaName: string,\n tableName: string,\n fkName: string,\n foreignKey: ForeignKey,\n): string {\n let sql = `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(fkName)}\nFOREIGN KEY (${foreignKey.columns.map(quoteIdentifier).join(', ')})\nREFERENCES ${qualifyTableName(schemaName, foreignKey.references.table)} (${foreignKey.references.columns\n .map(quoteIdentifier)\n .join(', ')})`;\n\n if (foreignKey.onDelete !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[foreignKey.onDelete];\n if (!action) {\n throw new Error(`Unknown referential action for onDelete: ${String(foreignKey.onDelete)}`);\n }\n sql += `\\nON DELETE ${action}`;\n }\n if (foreignKey.onUpdate !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[foreignKey.onUpdate];\n if (!action) {\n throw new Error(`Unknown referential action for onUpdate: ${String(foreignKey.onUpdate)}`);\n }\n sql += `\\nON UPDATE ${action}`;\n }\n\n return sql;\n}\n","import type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { StorageColumn, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\n\n/**\n * Resolves the identity value (monoid neutral element) as a SQL literal for a column's type.\n * Checks codec hooks first (extensions can provide type-specific identity values),\n * then falls back to the built-in map.\n */\nexport function resolveIdentityValue(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance> = {},\n): string | null {\n const referencedType = column.typeRef ? storageTypes[column.typeRef] : undefined;\n const codecId = referencedType?.codecId ?? column.codecId;\n const nativeType = referencedType?.nativeType ?? column.nativeType;\n const typeParams = referencedType?.typeParams ?? column.typeParams;\n\n if (codecId) {\n const hookDefault = codecHooks.get(codecId)?.resolveIdentityValue?.({\n nativeType,\n codecId,\n ...ifDefined('typeParams', typeParams),\n });\n if (hookDefault !== undefined) {\n return hookDefault;\n }\n }\n\n return buildBuiltinIdentityValue(nativeType, typeParams);\n}\n\n/**\n * Returns the built-in identity value (monoid neutral element) as a SQL literal for the given\n * PostgreSQL native type — e.g. 0 for integers, '' for text, false for booleans.\n *\n * This is the planner's fallback when no codec hook provides a type-specific identity value.\n *\n * Returns null for unrecognized types (for example enums and extension-owned types without a\n * hook), which causes the planner to fall back to the empty-table precheck.\n *\n * @internal Exported for testing only.\n */\nexport function buildBuiltinIdentityValue(\n nativeType: string,\n typeParams?: Record<string, unknown>,\n): string | null {\n const normalizedNativeType = normalizeIdentityValueNativeType(nativeType);\n\n if (normalizedNativeType.endsWith('[]')) {\n return \"'{}'\";\n }\n\n switch (normalizedNativeType) {\n case 'text':\n case 'character':\n case 'bpchar':\n case 'character varying':\n case 'varchar':\n return \"''\";\n\n case 'int2':\n case 'int4':\n case 'int8':\n case 'integer':\n case 'bigint':\n case 'smallint':\n case 'float4':\n case 'float8':\n case 'real':\n case 'double precision':\n case 'numeric':\n case 'decimal':\n return '0';\n\n case 'bool':\n case 'boolean':\n return 'false';\n\n case 'uuid':\n return \"'00000000-0000-0000-0000-000000000000'\";\n\n case 'json':\n return \"'{}'::json\";\n case 'jsonb':\n return \"'{}'::jsonb\";\n\n case 'date':\n case 'timestamp':\n case 'timestamptz':\n case 'timestamp with time zone':\n case 'timestamp without time zone':\n return \"'epoch'\";\n\n case 'time':\n case 'time without time zone':\n return \"'00:00:00'\";\n case 'timetz':\n case 'time with time zone':\n return \"'00:00:00+00'\";\n\n case 'interval':\n return \"'0'\";\n\n case 'bytea':\n return \"''::bytea\";\n case 'tsvector':\n return \"''::tsvector\";\n\n case 'bit':\n return buildBitIdentityValue(typeParams);\n case 'bit varying':\n case 'varbit':\n return \"B''\";\n\n default:\n return null;\n }\n}\n\nfunction normalizeIdentityValueNativeType(nativeType: string): string {\n return nativeType.trim().toLowerCase().replace(/\\s+/g, ' ');\n}\n\nfunction buildBitIdentityValue(typeParams?: Record<string, unknown>): string | null {\n const length = typeParams?.['length'];\n if (length === undefined) {\n return \"B'0'\";\n }\n if (typeof length !== 'number' || !Number.isInteger(length) || length <= 0) {\n return null;\n }\n return `B'${'0'.repeat(length)}'`;\n}\n","import { ifDefined } from '@prisma-next/utils/defined';\n\nexport type OperationClass =\n | 'dependency'\n | 'type'\n | 'table'\n | 'column'\n | 'primaryKey'\n | 'unique'\n | 'index'\n | 'foreignKey';\n\nexport interface PostgresPlanTargetDetails {\n readonly schema: string;\n readonly objectType: OperationClass;\n readonly name: string;\n readonly table?: string;\n}\n\nexport function buildTargetDetails(\n objectType: OperationClass,\n name: string,\n schema: string,\n table?: string,\n): PostgresPlanTargetDetails {\n return {\n schema,\n objectType,\n name,\n ...ifDefined('table', table),\n };\n}\n","import { quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { CodecControlHooks, SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { StorageColumn, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport { buildAddColumnSql } from './planner-ddl-builders';\nimport {\n columnExistsCheck,\n columnHasNoDefaultCheck,\n columnNullabilityCheck,\n qualifyTableName,\n} from './planner-sql-checks';\nimport { buildTargetDetails, type PostgresPlanTargetDetails } from './planner-target-details';\n\nexport function buildAddColumnOperationIdentity(\n schema: string,\n tableName: string,\n columnName: string,\n): Pick<\n SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n 'id' | 'label' | 'summary' | 'target'\n> {\n return {\n id: `column.${tableName}.${columnName}`,\n label: `Add column ${columnName} to ${tableName}`,\n summary: `Adds column ${columnName} to table ${tableName}`,\n target: {\n id: 'postgres',\n details: buildTargetDetails('table', tableName, schema),\n },\n };\n}\n\nexport function buildAddNotNullColumnWithTemporaryDefaultOperation(options: {\n readonly schema: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly column: StorageColumn;\n readonly codecHooks: Map<string, CodecControlHooks>;\n readonly storageTypes: Record<string, StorageTypeInstance>;\n readonly temporaryDefault: string;\n}): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const { schema, tableName, columnName, column, codecHooks, storageTypes, temporaryDefault } =\n options;\n const qualified = qualifyTableName(schema, tableName);\n\n return {\n ...buildAddColumnOperationIdentity(schema, tableName, columnName),\n operationClass: 'additive',\n precheck: [\n {\n description: `ensure column \"${columnName}\" is missing`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName, exists: false }),\n },\n ],\n execute: [\n {\n description: `add column \"${columnName}\"`,\n sql: buildAddColumnSql(\n qualified,\n columnName,\n column,\n codecHooks,\n temporaryDefault,\n storageTypes,\n ),\n },\n {\n description: `drop temporary default from column \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified} ALTER COLUMN ${quoteIdentifier(columnName)} DROP DEFAULT`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName }),\n },\n {\n description: `verify column \"${columnName}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n {\n description: `verify column \"${columnName}\" has no default after temporary default removal`,\n sql: columnHasNoDefaultCheck({ schema, table: tableName, column: columnName }),\n },\n ],\n };\n}\n","import type { ForeignKey } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\n\n/**\n * Pre-computed lookup sets for a schema table's constraints.\n * Converts O(n*m) linear scans to O(1) Set lookups per constraint check.\n */\nexport interface SchemaTableLookup {\n readonly uniqueKeys: Set<string>;\n readonly indexKeys: Set<string>;\n readonly uniqueIndexKeys: Set<string>;\n readonly fkKeys: Set<string>;\n}\n\nexport function buildSchemaLookupMap(schema: SqlSchemaIR): ReadonlyMap<string, SchemaTableLookup> {\n const map = new Map<string, SchemaTableLookup>();\n for (const [tableName, table] of Object.entries(schema.tables)) {\n map.set(tableName, buildSchemaTableLookup(table));\n }\n return map;\n}\n\nfunction buildSchemaTableLookup(table: SqlSchemaIR['tables'][string]): SchemaTableLookup {\n const uniqueKeys = new Set(table.uniques.map((u) => u.columns.join(',')));\n const indexKeys = new Set(table.indexes.map((i) => i.columns.join(',')));\n const uniqueIndexKeys = new Set(\n table.indexes.filter((i) => i.unique).map((i) => i.columns.join(',')),\n );\n const fkKeys = new Set(\n table.foreignKeys.map(\n (fk) => `${fk.columns.join(',')}|${fk.referencedTable}|${fk.referencedColumns.join(',')}`,\n ),\n );\n return { uniqueKeys, indexKeys, uniqueIndexKeys, fkKeys };\n}\n\nexport function hasUniqueConstraint(\n lookup: SchemaTableLookup,\n columns: readonly string[],\n): boolean {\n const key = columns.join(',');\n return lookup.uniqueKeys.has(key) || lookup.uniqueIndexKeys.has(key);\n}\n\nexport function hasIndex(lookup: SchemaTableLookup, columns: readonly string[]): boolean {\n const key = columns.join(',');\n return lookup.indexKeys.has(key) || lookup.uniqueKeys.has(key);\n}\n\nexport function hasForeignKey(lookup: SchemaTableLookup, fk: ForeignKey): boolean {\n return lookup.fkKeys.has(\n `${fk.columns.join(',')}|${fk.references.table}|${fk.references.columns.join(',')}`,\n );\n}\n","/**\n * Migration strategies.\n *\n * Each strategy examines the issue list, consumes issues it handles, and\n * returns the `PostgresOpFactoryCall[]` to address them. The issue planner\n * runs each strategy in order and routes whatever's left through\n * `mapIssueToCall`.\n *\n * The full ordered list is exported as `postgresPlannerStrategies` and is\n * used unchanged by both `migration plan` and `db update` / `db init`. The\n * two journeys differ only in `policy.allowedOperationClasses`:\n *\n * - When `'data'` is in the policy, data-safe strategies (NOT NULL backfill,\n * nullability tightening, unsafe type changes, enum shrink/rebuild) emit\n * `DataTransformCall` placeholders that the user fills in.\n * - When `'data'` is excluded, those strategies short-circuit so the\n * downstream walk-schema strategies (codec-hook type ops, dependency\n * installs, temp-default backfill) and `mapIssueToCall` defaults emit\n * direct DDL instead.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n ComponentDatabaseDependency,\n MigrationOperationPolicy,\n SqlMigrationPlanOperation,\n} from '@prisma-next/family-sql/control';\nimport { collectInitDependencies } from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport {\n AddColumnCall,\n AddEnumValuesCall,\n AlterColumnTypeCall,\n CreateEnumTypeCall,\n DataTransformCall,\n DropEnumTypeCall,\n type PostgresOpFactoryCall,\n RawSqlCall,\n RenameTypeCall,\n SetNotNullCall,\n} from './op-factory-call';\nimport {\n buildAddColumnSql,\n buildColumnDefaultSql,\n buildColumnTypeSql,\n} from './planner-ddl-builders';\nimport { resolveIdentityValue } from './planner-identity-values';\nimport {\n buildAddColumnOperationIdentity,\n buildAddNotNullColumnWithTemporaryDefaultOperation,\n} from './planner-recipes';\nimport { buildSchemaLookupMap, hasForeignKey, hasUniqueConstraint } from './planner-schema-lookup';\nimport {\n buildExpectedFormatType,\n columnExistsCheck,\n columnNullabilityCheck,\n qualifyTableName,\n tableIsEmptyCheck,\n} from './planner-sql-checks';\nimport { buildTargetDetails, type PostgresPlanTargetDetails } from './planner-target-details';\n\nconst REBUILD_SUFFIX = '__prisma_next_new';\n\n// ============================================================================\n// Strategy types\n// ============================================================================\n\n/**\n * Context passed to each migration strategy.\n *\n * Strategies read the source (`fromContract`), target (`toContract`), current\n * database state (`schema`), operation policy (`policy`), and component list\n * (`frameworkComponents`) to make planning decisions. `fromContract` is null\n * when no prior contract is available (e.g. `db update`, where the current\n * DB state is approximated via `schema`).\n */\nexport interface StrategyContext {\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\n readonly schemaName: string;\n readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;\n readonly storageTypes: Readonly<Record<string, StorageTypeInstance>>;\n readonly schema: SqlSchemaIR;\n readonly policy: MigrationOperationPolicy;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}\n\n// ============================================================================\n// Call strategies (for issue planner)\n// ============================================================================\n\nexport type CallMigrationStrategy = (\n issues: readonly SchemaIssue[],\n context: StrategyContext,\n) =>\n | {\n kind: 'match';\n issues: readonly SchemaIssue[];\n calls: readonly PostgresOpFactoryCall[];\n /**\n * `true` for strategies that emit cohesive sequential recipes whose\n * calls must stay contiguous and in the returned order — e.g.\n * `enumChangeCallStrategy` (dataTransform → createEnumType →\n * dropEnumType), `notNullBackfillCallStrategy` (addColumn →\n * dataTransform → setNotNull). Defaults to `false`, which lets\n * `planIssues` hoist individual calls into their DDL sequencing bucket.\n */\n recipe?: boolean;\n }\n | { kind: 'no_match' };\n\nfunction buildColumnSpec(\n table: string,\n column: string,\n ctx: StrategyContext,\n overrides?: { nullable?: boolean },\n) {\n const col = ctx.toContract.storage.tables[table]?.columns[column];\n if (!col) throw new Error(`Column \"${table}\".\"${column}\" not found in destination contract`);\n const mutableHooks = ctx.codecHooks as Map<string, CodecControlHooks>;\n const mutableTypes = ctx.storageTypes as Record<string, StorageTypeInstance>;\n return {\n name: column,\n typeSql: buildColumnTypeSql(col, mutableHooks, mutableTypes),\n defaultSql: buildColumnDefaultSql(col.default, col),\n nullable: overrides?.nullable ?? col.nullable,\n };\n}\n\nfunction buildAlterTypeOptions(\n table: string,\n column: string,\n ctx: StrategyContext,\n using?: string,\n) {\n const col = ctx.toContract.storage.tables[table]?.columns[column];\n if (!col) throw new Error(`Column \"${table}\".\"${column}\" not found in destination contract`);\n const mutableHooks = ctx.codecHooks as Map<string, CodecControlHooks>;\n const mutableTypes = ctx.storageTypes as Record<string, StorageTypeInstance>;\n const qualifiedTargetType = buildColumnTypeSql(col, mutableHooks, mutableTypes, false);\n const formatTypeExpected = buildExpectedFormatType(col, mutableHooks, mutableTypes);\n return {\n qualifiedTargetType,\n formatTypeExpected,\n rawTargetTypeForLabel: qualifiedTargetType,\n ...(using !== undefined ? { using } : {}),\n };\n}\n\nexport const notNullBackfillCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n // `DataTransformCall` is operation class `'data'`. When the policy excludes\n // it (`db update` / `db init`), skip so `notNullAddColumnCallStrategy`\n // (temp-default backfill) or `mapIssueToCall` can take the issue.\n if (!ctx.policy.allowedOperationClasses.includes('data')) return { kind: 'no_match' };\n\n const matched: SchemaIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const issue of issues) {\n if (issue.kind !== 'missing_column' || !issue.table || !issue.column) continue;\n\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column) continue;\n if (column.nullable === true || column.default !== undefined) continue;\n\n matched.push(issue);\n const spec = buildColumnSpec(issue.table, issue.column, ctx, { nullable: true });\n calls.push(\n new AddColumnCall(ctx.schemaName, issue.table, spec),\n new DataTransformCall(\n `backfill-${issue.table}-${issue.column}`,\n `backfill-${issue.table}-${issue.column}:check`,\n `backfill-${issue.table}-${issue.column}:run`,\n ),\n new SetNotNullCall(ctx.schemaName, issue.table, issue.column),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n recipe: true,\n };\n};\n\nconst SAFE_WIDENINGS = new Set(['int2→int4', 'int2→int8', 'int4→int8', 'float4→float8']);\n\nexport const typeChangeCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n // For unsafe widenings this strategy emits a `DataTransformCall` placeholder\n // (operation class `'data'`); when the policy excludes `'data'`\n // (`db update` / `db init`), skip those issues so `mapIssueToCall` can\n // emit a direct `ALTER COLUMN TYPE`. Safe widenings still flow through\n // here because the resulting `AlterColumnTypeCall` is `widening`-class.\n const dataAllowed = ctx.policy.allowedOperationClasses.includes('data');\n\n const matched: SchemaIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const issue of issues) {\n if (issue.kind !== 'type_mismatch') continue;\n if (!issue.table || !issue.column) continue;\n const fromColumn = ctx.fromContract?.storage.tables[issue.table]?.columns[issue.column];\n const toColumn = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!fromColumn || !toColumn) continue;\n const fromType = fromColumn.nativeType;\n const toType = toColumn.nativeType;\n if (fromType === toType) continue;\n const isSafeWidening = SAFE_WIDENINGS.has(`${fromType}→${toType}`);\n if (!isSafeWidening && !dataAllowed) continue;\n matched.push(issue);\n const alterOpts = buildAlterTypeOptions(issue.table, issue.column, ctx);\n if (isSafeWidening) {\n calls.push(new AlterColumnTypeCall(ctx.schemaName, issue.table, issue.column, alterOpts));\n } else {\n calls.push(\n new DataTransformCall(\n `typechange-${issue.table}-${issue.column}`,\n `typechange-${issue.table}-${issue.column}:check`,\n `typechange-${issue.table}-${issue.column}:run`,\n ),\n new AlterColumnTypeCall(ctx.schemaName, issue.table, issue.column, alterOpts),\n );\n }\n }\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n recipe: true,\n };\n};\n\nexport const nullableTighteningCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n // `DataTransformCall` is operation class `'data'`. When the policy excludes\n // it (`db update` / `db init`), skip so `mapIssueToCall` emits a direct\n // `SET NOT NULL` instead.\n if (!ctx.policy.allowedOperationClasses.includes('data')) return { kind: 'no_match' };\n\n const matched: SchemaIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const issue of issues) {\n if (issue.kind !== 'nullability_mismatch' || !issue.table || !issue.column) continue;\n\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column) continue;\n if (column.nullable === true) continue;\n\n matched.push(issue);\n calls.push(\n new DataTransformCall(\n `handle-nulls-${issue.table}-${issue.column}`,\n `handle-nulls-${issue.table}-${issue.column}:check`,\n `handle-nulls-${issue.table}-${issue.column}:run`,\n ),\n new SetNotNullCall(ctx.schemaName, issue.table, issue.column),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n recipe: true,\n };\n};\n\nfunction enumRebuildCallRecipe(\n typeName: string,\n ctx: StrategyContext,\n): readonly PostgresOpFactoryCall[] {\n const toType = ctx.toContract.storage.types?.[typeName];\n if (!toType) return [];\n const nativeType = toType.nativeType;\n const desiredValues = (toType.typeParams['values'] ?? []) as readonly string[];\n const tempName = `${nativeType}${REBUILD_SUFFIX}`;\n\n const columnRefs: { table: string; column: string }[] = [];\n for (const [tableName, table] of Object.entries(ctx.toContract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (column.typeRef === typeName) {\n columnRefs.push({ table: tableName, column: columnName });\n }\n }\n }\n\n return [\n new CreateEnumTypeCall(ctx.schemaName, tempName, desiredValues),\n ...columnRefs.map((ref) => {\n const using = `${ref.column}::text::${tempName}`;\n return new AlterColumnTypeCall(ctx.schemaName, ref.table, ref.column, {\n qualifiedTargetType: tempName,\n formatTypeExpected: tempName,\n rawTargetTypeForLabel: tempName,\n using,\n });\n }),\n new DropEnumTypeCall(ctx.schemaName, nativeType),\n new RenameTypeCall(ctx.schemaName, tempName, nativeType),\n ];\n}\n\nexport const enumChangeCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n // The shrink/rebuild branches emit a `DataTransformCall` placeholder or a\n // destructive rebuild that should be authored explicitly. When the policy\n // excludes `'data'` (`db update` / `db init`), skip the entire strategy so\n // `storageTypePlanCallStrategy` (codec-hook driven) takes over with the\n // dev-push enum behavior.\n if (!ctx.policy.allowedOperationClasses.includes('data')) return { kind: 'no_match' };\n\n const matched: SchemaIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const issue of issues) {\n if (issue.kind !== 'enum_values_changed') continue;\n matched.push(issue);\n\n if (issue.removedValues.length > 0) {\n calls.push(\n new DataTransformCall(\n `migrate-${issue.typeName}-values`,\n `migrate-${issue.typeName}-values:check`,\n `migrate-${issue.typeName}-values:run`,\n ),\n ...enumRebuildCallRecipe(issue.typeName, ctx),\n );\n } else if (issue.addedValues.length === 0) {\n calls.push(...enumRebuildCallRecipe(issue.typeName, ctx));\n } else {\n const toType = ctx.toContract.storage.types?.[issue.typeName];\n if (toType) {\n calls.push(\n new AddEnumValuesCall(\n ctx.schemaName,\n issue.typeName,\n toType.nativeType,\n issue.addedValues,\n ),\n );\n }\n }\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n recipe: true,\n };\n};\n\n// ============================================================================\n// Walk-schema strategies (absorbed from the legacy planner)\n// ============================================================================\n\n/**\n * Dispatches storage types through their codec's `planTypeOperations` hook.\n * Replaces the walk-schema `buildStorageTypeOperations` path: the hook is\n * the authoritative source for codec-driven DDL (enum create/rebuild/add-\n * value, custom type creation, etc.).\n *\n * Runs after `enumChangeCallStrategy` so the structured enum path (value\n * add, rebuild recipe) gets first pick at `enum_values_changed` issues;\n * this strategy then handles remaining `type_missing` / `enum_values_changed`\n * issues for types whose hook produced at least one op.\n */\nexport const storageTypePlanCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n const storageTypes = ctx.toContract.storage.types ?? {};\n if (Object.keys(storageTypes).length === 0) return { kind: 'no_match' };\n\n const calls: PostgresOpFactoryCall[] = [];\n const handledTypeNames = new Set<string>();\n\n for (const [typeName, typeInstance] of Object.entries(storageTypes).sort(([a], [b]) =>\n a.localeCompare(b),\n )) {\n const hook = ctx.codecHooks.get(typeInstance.codecId);\n if (!hook?.planTypeOperations) continue;\n const planResult = hook.planTypeOperations({\n typeName,\n typeInstance,\n contract: ctx.toContract,\n schema: ctx.schema,\n schemaName: ctx.schemaName,\n policy: ctx.policy,\n });\n if (!planResult) continue;\n if (planResult.operations.length === 0) {\n handledTypeNames.add(typeName);\n continue;\n }\n handledTypeNames.add(typeName);\n for (const op of planResult.operations) {\n calls.push(\n new RawSqlCall({\n ...op,\n target: {\n id: op.target.id,\n details: buildTargetDetails('type', typeName, ctx.schemaName),\n },\n } as SqlMigrationPlanOperation<PostgresPlanTargetDetails>),\n );\n }\n }\n\n const remaining = issues.filter(\n (issue) =>\n !(\n (issue.kind === 'type_missing' || issue.kind === 'enum_values_changed') &&\n issue.typeName &&\n handledTypeNames.has(issue.typeName)\n ),\n );\n\n if (calls.length === 0 && remaining.length === issues.length) {\n return { kind: 'no_match' };\n }\n\n return { kind: 'match', issues: remaining, calls };\n};\n\n/**\n * Dispatches component-declared database dependencies. Replaces the\n * walk-schema `buildDatabaseDependencyOperations` path. Rather than consuming\n * `dependency_missing` issues (which only carry the id), this strategy\n * re-invokes `collectInitDependencies(frameworkComponents)` at plan time so\n * the handler has access to the structured `install` ops each component\n * declared — including arbitrary SQL launders — and dedupes by dependency id\n * plus per-op id.\n */\nexport const dependencyInstallCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n const installedIds = new Set(ctx.schema.dependencies.map((d) => d.id));\n const dependencies = sortDependencies(\n collectInitDependencies(ctx.frameworkComponents).filter(isPostgresPlannerDependency),\n );\n\n const calls: PostgresOpFactoryCall[] = [];\n const handledDependencyIds = new Set<string>();\n const seenOperationIds = new Set<string>();\n\n for (const dep of dependencies) {\n handledDependencyIds.add(dep.id);\n if (installedIds.has(dep.id)) continue;\n for (const installOp of dep.install) {\n if (seenOperationIds.has(installOp.id)) continue;\n seenOperationIds.add(installOp.id);\n calls.push(liftInstallOpToCall(installOp));\n }\n }\n\n // Consume ALL `dependency_missing` issues — even non-postgres ones. The\n // walk-schema predecessor silently skipped non-postgres deps; leaving those\n // issues in the stream would let `mapIssueToCall` reject them as\n // \"Unknown dependency type\".\n const remaining = issues.filter((issue) => issue.kind !== 'dependency_missing');\n\n if (calls.length === 0 && remaining.length === issues.length) {\n return { kind: 'no_match' };\n }\n return { kind: 'match', issues: remaining, calls };\n};\n\n/**\n * Handles `missing_column` issues for NOT NULL columns without a contract\n * default. Replaces the walk-schema `buildAddColumnItem` non-default branches.\n *\n * Two shapes:\n * - Shared-temp-default safe: emit a single atomic composite op (add\n * nullable → backfill identity value → `SET NOT NULL` → `DROP DEFAULT`).\n * - Empty-table guarded: emit a hand-built op with a `tableIsEmptyCheck`\n * precheck so the failure message is \"table is not empty\" rather than the\n * raw PG NOT NULL violation.\n *\n * \"Normal\" missing_column cases (nullable or has a contract default) are left\n * for `mapIssueToCall`'s default `AddColumnCall` emission.\n */\nexport const notNullAddColumnCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n const matched: SchemaIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n const schemaLookups = buildSchemaLookupMap(ctx.schema);\n\n const mutableCodecHooks = ctx.codecHooks as Map<string, CodecControlHooks>;\n const mutableStorageTypes = ctx.storageTypes as Record<string, StorageTypeInstance>;\n\n for (const issue of issues) {\n if (issue.kind !== 'missing_column' || !issue.table || !issue.column) continue;\n const contractTable = ctx.toContract.storage.tables[issue.table];\n const column = contractTable?.columns[issue.column];\n if (!column) continue;\n\n const notNull = column.nullable !== true;\n const hasDefault = column.default !== undefined;\n if (!notNull || hasDefault) continue;\n\n const schemaTable = ctx.schema.tables[issue.table];\n if (!schemaTable) continue;\n\n const temporaryDefault = resolveIdentityValue(column, mutableCodecHooks, mutableStorageTypes);\n const schemaLookup = schemaLookups.get(issue.table);\n const canUseSharedTempDefault =\n temporaryDefault !== null &&\n canUseSharedTemporaryDefaultStrategy({\n table: contractTable,\n schemaTable,\n schemaLookup,\n columnName: issue.column,\n });\n\n matched.push(issue);\n\n if (canUseSharedTempDefault && temporaryDefault !== null) {\n calls.push(\n new RawSqlCall(\n buildAddNotNullColumnWithTemporaryDefaultOperation({\n schema: ctx.schemaName,\n tableName: issue.table,\n columnName: issue.column,\n column,\n codecHooks: mutableCodecHooks,\n storageTypes: mutableStorageTypes,\n temporaryDefault,\n }),\n ),\n );\n continue;\n }\n\n const qualified = qualifyTableName(ctx.schemaName, issue.table);\n calls.push(\n new RawSqlCall({\n ...buildAddColumnOperationIdentity(ctx.schemaName, issue.table, issue.column),\n operationClass: 'additive',\n precheck: [\n {\n description: `ensure column \"${issue.column}\" is missing`,\n sql: columnExistsCheck({\n schema: ctx.schemaName,\n table: issue.table,\n column: issue.column,\n exists: false,\n }),\n },\n {\n description: `ensure table \"${issue.table}\" is empty before adding NOT NULL column without default`,\n sql: tableIsEmptyCheck(qualified),\n },\n ],\n execute: [\n {\n description: `add column \"${issue.column}\"`,\n sql: buildAddColumnSql(\n qualified,\n issue.column,\n column,\n mutableCodecHooks,\n undefined,\n mutableStorageTypes,\n ),\n },\n ],\n postcheck: [\n {\n description: `verify column \"${issue.column}\" exists`,\n sql: columnExistsCheck({\n schema: ctx.schemaName,\n table: issue.table,\n column: issue.column,\n }),\n },\n {\n description: `verify column \"${issue.column}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema: ctx.schemaName,\n table: issue.table,\n column: issue.column,\n nullable: false,\n }),\n },\n ],\n }),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n };\n};\n\n// ============================================================================\n// Strategy helpers\n// ============================================================================\n\nfunction canUseSharedTemporaryDefaultStrategy(options: {\n readonly table: NonNullable<Contract<SqlStorage>['storage']['tables'][string]>;\n readonly schemaTable: SqlSchemaIR['tables'][string];\n readonly schemaLookup: ReturnType<typeof buildSchemaLookupMap> extends ReadonlyMap<\n string,\n infer V\n >\n ? V | undefined\n : never;\n readonly columnName: string;\n}): boolean {\n const { table, schemaTable, schemaLookup, columnName } = options;\n\n if (table.primaryKey?.columns.includes(columnName) && !schemaTable.primaryKey) {\n return false;\n }\n\n for (const unique of table.uniques) {\n if (!unique.columns.includes(columnName)) continue;\n if (!schemaLookup || !hasUniqueConstraint(schemaLookup, unique.columns)) return false;\n }\n\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.constraint === false || !foreignKey.columns.includes(columnName)) continue;\n if (!schemaLookup || !hasForeignKey(schemaLookup, foreignKey)) return false;\n }\n\n return true;\n}\n\ntype PlannerDatabaseDependency = ComponentDatabaseDependency<unknown> & {\n readonly install: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n};\n\nfunction isPostgresPlannerDependency(\n dependency: ComponentDatabaseDependency<unknown>,\n): dependency is PlannerDatabaseDependency {\n return dependency.install.every((operation) => operation.target.id === 'postgres');\n}\n\nfunction sortDependencies(\n dependencies: ReadonlyArray<PlannerDatabaseDependency>,\n): ReadonlyArray<PlannerDatabaseDependency> {\n return [...dependencies].sort((a, b) => a.id.localeCompare(b.id));\n}\n\n/**\n * Lift a component install op into migration IR. Structured shapes — extension\n * and schema installs with predictable SQL — collapse to typed `*Call`\n * subclasses so the scaffolded migration authoring surface stays readable.\n * Everything else (arbitrary SQL) falls through to `RawSqlCall` as an escape\n * hatch.\n */\n/**\n * Component-declared install ops are wrapped as `RawSqlCall` so the\n * component's original `label`, `precheck`, `execute`, `postcheck`, and op\n * id are preserved verbatim. Structured conversion (to e.g.\n * `CreateExtensionCall`) would drop the precheck/postcheck pair and\n * change the DDL label, breaking walk-schema output parity. Classification\n * as `'dep'` happens in `classifyCall` via the underlying op's id prefix.\n */\nfunction liftInstallOpToCall(\n op: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n): PostgresOpFactoryCall {\n return new RawSqlCall(op);\n}\n\n/**\n * Ordered list of Postgres planner strategies, shared by `migration plan`\n * and `db update` / `db init`. The issue planner runs each strategy in\n * order, letting it consume any issues it handles, and routes whatever's\n * left through `mapIssueToCall`. Behavior diverges purely on\n * `policy.allowedOperationClasses`:\n *\n * - When `'data'` is allowed (`migration plan`), the data-safe strategies\n * (`enumChangeCallStrategy`, `notNullBackfillCallStrategy`,\n * `typeChangeCallStrategy`, `nullableTighteningCallStrategy`) consume their\n * matching issues and emit `DataTransformCall` placeholders or recipe ops.\n *\n * - When `'data'` is not allowed (`db update` / `db init`), each data-safe\n * strategy short-circuits to `no_match`, leaving the issue for the\n * downstream walk-schema strategies (`storageTypePlanCallStrategy`,\n * `dependencyInstallCallStrategy`, `notNullAddColumnCallStrategy`) or the\n * `mapIssueToCall` default to handle with direct DDL.\n *\n * Order matters: data-safe strategies must run before the walk-schema\n * strategies on overlapping issue kinds (e.g. `enum_values_changed`,\n * `missing_column` for NOT NULL) so they take priority when active.\n */\nexport const postgresPlannerStrategies: readonly CallMigrationStrategy[] = [\n enumChangeCallStrategy,\n notNullBackfillCallStrategy,\n typeChangeCallStrategy,\n nullableTighteningCallStrategy,\n storageTypePlanCallStrategy,\n dependencyInstallCallStrategy,\n notNullAddColumnCallStrategy,\n];\n","/**\n * Postgres migration planner.\n *\n * Takes schema issues (from verifySqlSchema) and emits migration IR\n * (`PostgresOpFactoryCall[]`). Strategies consume issues they recognize and\n * produce specialized call sequences (e.g. NOT NULL backfill →\n * addColumn(nullable) + dataTransform + setNotNull); remaining issues flow\n * through `mapIssueToCall` for the default case.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlPlannerConflict,\n SqlPlannerConflictLocation,\n} from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type {\n SqlStorage,\n StorageColumn,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport {\n AddColumnCall,\n AddForeignKeyCall,\n AddPrimaryKeyCall,\n AddUniqueCall,\n AlterColumnTypeCall,\n CreateEnumTypeCall,\n CreateExtensionCall,\n CreateIndexCall,\n CreateSchemaCall,\n CreateTableCall,\n DropColumnCall,\n DropConstraintCall,\n DropDefaultCall,\n DropIndexCall,\n DropNotNullCall,\n DropTableCall,\n type PostgresOpFactoryCall,\n SetDefaultCall,\n SetNotNullCall,\n} from './op-factory-call';\nimport type { ColumnSpec, ForeignKeySpec } from './operations/shared';\nimport { buildColumnDefaultSql, buildColumnTypeSql } from './planner-ddl-builders';\nimport { buildExpectedFormatType } from './planner-sql-checks';\nimport {\n type CallMigrationStrategy,\n postgresPlannerStrategies,\n type StrategyContext,\n} from './planner-strategies';\n\nexport type { CallMigrationStrategy, StrategyContext };\n\n// ============================================================================\n// Issue kind ordering (dependency order)\n// ============================================================================\n\nconst ISSUE_KIND_ORDER: Record<string, number> = {\n // Dependencies and types first\n dependency_missing: 1,\n type_missing: 2,\n type_values_mismatch: 3,\n enum_values_changed: 3,\n\n // Drops (reconciliation — clear the way for creates)\n // FKs dropped first (they depend on other constraints)\n extra_foreign_key: 10,\n extra_unique_constraint: 11,\n extra_primary_key: 12,\n extra_index: 13,\n extra_default: 14,\n extra_column: 15,\n extra_table: 16,\n\n // Tables before columns\n missing_table: 20,\n\n // Columns before constraints\n missing_column: 30,\n\n // Reconciliation alters (on existing objects)\n type_mismatch: 40,\n nullability_mismatch: 41,\n default_missing: 42,\n default_mismatch: 43,\n\n // Constraints after columns exist\n primary_key_mismatch: 50,\n unique_constraint_mismatch: 51,\n index_mismatch: 52,\n foreign_key_mismatch: 60,\n};\n\nfunction issueOrder(issue: SchemaIssue): number {\n return ISSUE_KIND_ORDER[issue.kind] ?? 99;\n}\n\n// ============================================================================\n// Conflict helpers\n// ============================================================================\n\nfunction issueConflict(\n kind: SqlPlannerConflict['kind'],\n summary: string,\n location?: SqlPlannerConflict['location'],\n): SqlPlannerConflict {\n return {\n kind,\n summary,\n why: 'Use `migration new` to author a custom migration for this change.',\n ...(location ? { location } : {}),\n };\n}\n\nfunction isMissing(issue: SchemaIssue): boolean {\n if (issue.kind === 'enum_values_changed') return false;\n return issue.actual === undefined;\n}\n\n// ============================================================================\n// Issue planner\n// ============================================================================\n\nexport interface IssuePlannerOptions {\n readonly issues: readonly SchemaIssue[];\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\n readonly schemaName: string;\n readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;\n readonly storageTypes: Readonly<Record<string, StorageTypeInstance>>;\n /**\n * Current database schema IR. Strategies read this to detect whether a\n * structure already exists (e.g. `buildSchemaLookupMap` for shared-temp-\n * default safety, extension dependency checks). Defaults to an empty schema\n * when omitted so the planner can still run over \"fresh DB\" contract\n * snapshots.\n */\n readonly schema?: SqlSchemaIR;\n /**\n * Operation-class policy. `planIssues` filters calls whose `operationClass`\n * is not in `policy.allowedOperationClasses` and surfaces them as conflicts\n * instead of emitting disallowed DDL. Defaults to additive-only.\n */\n readonly policy?: MigrationOperationPolicy;\n /**\n * Framework components participating in this composition. Used by the\n * dependency-install strategy to dispatch `databaseDependencies.init` at\n * plan time.\n */\n readonly frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n readonly strategies?: readonly CallMigrationStrategy[];\n}\n\nexport interface IssuePlannerValue {\n readonly calls: readonly PostgresOpFactoryCall[];\n}\n\nfunction toColumnSpec(\n name: string,\n column: StorageColumn,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n storageTypes: Readonly<Record<string, StorageTypeInstance>>,\n): ColumnSpec {\n return {\n name,\n typeSql: buildColumnTypeSql(\n column,\n codecHooks as Map<string, CodecControlHooks>,\n storageTypes as Record<string, StorageTypeInstance>,\n ),\n defaultSql: buildColumnDefaultSql(column.default, column),\n nullable: column.nullable,\n };\n}\n\nfunction mapIssueToCall(\n issue: SchemaIssue,\n ctx: StrategyContext,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n const { schemaName, codecHooks, storageTypes } = ctx;\n\n switch (issue.kind) {\n case 'missing_table': {\n if (!issue.table)\n return notOk(\n issueConflict('unsupportedOperation', 'Missing table issue has no table name'),\n );\n const contractTable = ctx.toContract.storage.tables[issue.table];\n if (!contractTable) {\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Table \"${issue.table}\" reported missing but not found in destination contract`,\n ),\n );\n }\n const columns: ColumnSpec[] = Object.entries(contractTable.columns).map(([name, column]) =>\n toColumnSpec(name, column, codecHooks, storageTypes),\n );\n const primaryKey = contractTable.primaryKey\n ? { columns: contractTable.primaryKey.columns }\n : undefined;\n const calls: PostgresOpFactoryCall[] = [\n new CreateTableCall(schemaName, issue.table, columns, primaryKey),\n ];\n for (const index of contractTable.indexes) {\n const indexName = index.name ?? `${issue.table}_${index.columns.join('_')}_idx`;\n calls.push(new CreateIndexCall(schemaName, issue.table, indexName, [...index.columns]));\n }\n const explicitIndexColumnSets = new Set(\n contractTable.indexes.map((idx) => idx.columns.join(',')),\n );\n for (const fk of contractTable.foreignKeys) {\n if (fk.constraint) {\n const fkName = fk.name ?? `${issue.table}_${fk.columns.join('_')}_fkey`;\n const fkSpec: ForeignKeySpec = {\n name: fkName,\n columns: fk.columns,\n references: { table: fk.references.table, columns: fk.references.columns },\n ...(fk.onDelete !== undefined && { onDelete: fk.onDelete }),\n ...(fk.onUpdate !== undefined && { onUpdate: fk.onUpdate }),\n };\n calls.push(new AddForeignKeyCall(schemaName, issue.table, fkSpec));\n }\n if (fk.index && !explicitIndexColumnSets.has(fk.columns.join(','))) {\n const indexName = `${issue.table}_${fk.columns.join('_')}_idx`;\n calls.push(new CreateIndexCall(schemaName, issue.table, indexName, [...fk.columns]));\n }\n }\n for (const unique of contractTable.uniques) {\n const constraintName = unique.name ?? `${issue.table}_${unique.columns.join('_')}_key`;\n calls.push(new AddUniqueCall(schemaName, issue.table, constraintName, [...unique.columns]));\n }\n return ok(calls);\n }\n\n case 'missing_column':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Missing column issue has no table/column name'),\n );\n {\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column)\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Column \"${issue.table}\".\"${issue.column}\" not in destination contract`,\n ),\n );\n return ok([\n new AddColumnCall(\n schemaName,\n issue.table,\n toColumnSpec(issue.column, column, codecHooks, storageTypes),\n ),\n ]);\n }\n\n case 'default_missing':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Default missing issue has no table/column name'),\n );\n {\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column?.default) {\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Column \"${issue.table}\".\"${issue.column}\" has no default in contract`,\n ),\n );\n }\n const defaultSql = buildColumnDefaultSql(column.default, column);\n if (!defaultSql) return ok([]);\n return ok([new SetDefaultCall(schemaName, issue.table, issue.column, defaultSql)]);\n }\n\n case 'extra_table':\n if (!issue.table)\n return notOk(issueConflict('unsupportedOperation', 'Extra table issue has no table name'));\n return ok([new DropTableCall(schemaName, issue.table)]);\n\n case 'extra_column':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Extra column issue has no table/column name'),\n );\n return ok([new DropColumnCall(schemaName, issue.table, issue.column)]);\n\n case 'extra_index':\n if (!issue.table || !issue.indexOrConstraint)\n return notOk(\n issueConflict('unsupportedOperation', 'Extra index issue has no table/index name'),\n );\n return ok([new DropIndexCall(schemaName, issue.table, issue.indexOrConstraint)]);\n\n case 'extra_unique_constraint':\n case 'extra_foreign_key':\n case 'extra_primary_key': {\n if (!issue.table)\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n 'Extra constraint issue has no table/constraint name',\n ),\n );\n // `extra_primary_key` issues don't carry a constraint name — the\n // verifier only has the table. Fall back to `<table>_pkey`, matching\n // Postgres' default PK constraint naming and the old reconciliation\n // planner's behavior.\n const constraintName =\n issue.indexOrConstraint ??\n (issue.kind === 'extra_primary_key' ? `${issue.table}_pkey` : undefined);\n if (!constraintName)\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n 'Extra constraint issue has no table/constraint name',\n ),\n );\n const kindMap = {\n extra_unique_constraint: 'unique' as const,\n extra_foreign_key: 'foreignKey' as const,\n extra_primary_key: 'primaryKey' as const,\n };\n return ok([\n new DropConstraintCall(schemaName, issue.table, constraintName, kindMap[issue.kind]),\n ]);\n }\n\n case 'extra_default':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Extra default issue has no table/column name'),\n );\n return ok([new DropDefaultCall(schemaName, issue.table, issue.column)]);\n\n case 'nullability_mismatch': {\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('nullabilityConflict', 'Nullability mismatch has no table/column name'),\n );\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column)\n return notOk(\n issueConflict(\n 'nullabilityConflict',\n `Column \"${issue.table}\".\"${issue.column}\" not found in destination contract`,\n ),\n );\n return ok(\n column.nullable\n ? [new DropNotNullCall(schemaName, issue.table, issue.column)]\n : [new SetNotNullCall(schemaName, issue.table, issue.column)],\n );\n }\n\n case 'type_mismatch':\n if (!issue.table || !issue.column)\n return notOk(issueConflict('typeMismatch', 'Type mismatch has no table/column name'));\n {\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column)\n return notOk(\n issueConflict(\n 'typeMismatch',\n `Column \"${issue.table}\".\"${issue.column}\" not in destination contract`,\n ),\n );\n const hooksMap = codecHooks as Map<string, CodecControlHooks>;\n const typesMap = storageTypes as Record<string, StorageTypeInstance>;\n const qualifiedTargetType = buildColumnTypeSql(column, hooksMap, typesMap, false);\n const formatTypeExpected = buildExpectedFormatType(column, hooksMap, typesMap);\n return ok([\n new AlterColumnTypeCall(schemaName, issue.table, issue.column, {\n qualifiedTargetType,\n formatTypeExpected,\n rawTargetTypeForLabel: qualifiedTargetType,\n }),\n ]);\n }\n\n case 'default_mismatch':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Default mismatch has no table/column name'),\n );\n {\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column?.default) return ok([]);\n const defaultSql = buildColumnDefaultSql(column.default, column);\n if (!defaultSql) return ok([]);\n return ok([\n new SetDefaultCall(schemaName, issue.table, issue.column, defaultSql, 'widening'),\n ]);\n }\n\n case 'primary_key_mismatch':\n if (!issue.table)\n return notOk(issueConflict('indexIncompatible', 'Primary key issue has no table name'));\n if (isMissing(issue)) {\n const pk = ctx.toContract.storage.tables[issue.table]?.primaryKey;\n if (!pk)\n return notOk(\n issueConflict('indexIncompatible', `No primary key in contract for \"${issue.table}\"`),\n );\n const constraintName = pk.name ?? `${issue.table}_pkey`;\n return ok([new AddPrimaryKeyCall(schemaName, issue.table, constraintName, pk.columns)]);\n }\n return notOk(\n issueConflict(\n 'indexIncompatible',\n `Primary key on \"${issue.table}\" has different columns (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n case 'unique_constraint_mismatch':\n if (!issue.table)\n return notOk(\n issueConflict('indexIncompatible', 'Unique constraint issue has no table name'),\n );\n if (isMissing(issue) && issue.expected) {\n const columns = issue.expected.split(', ');\n const constraintName = `${issue.table}_${columns.join('_')}_key`;\n return ok([new AddUniqueCall(schemaName, issue.table, constraintName, columns)]);\n }\n return notOk(\n issueConflict(\n 'indexIncompatible',\n `Unique constraint on \"${issue.table}\" differs (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n case 'index_mismatch':\n if (!issue.table)\n return notOk(issueConflict('indexIncompatible', 'Index issue has no table name'));\n if (isMissing(issue) && issue.expected) {\n const columns = issue.expected.split(', ');\n const indexName = `${issue.table}_${columns.join('_')}_idx`;\n return ok([new CreateIndexCall(schemaName, issue.table, indexName, columns)]);\n }\n return notOk(\n issueConflict(\n 'indexIncompatible',\n `Index on \"${issue.table}\" differs (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n case 'foreign_key_mismatch':\n if (!issue.table)\n return notOk(issueConflict('foreignKeyConflict', 'Foreign key issue has no table name'));\n if (isMissing(issue) && issue.expected) {\n const arrowIdx = issue.expected.indexOf(' -> ');\n if (arrowIdx >= 0) {\n const columns = issue.expected.slice(0, arrowIdx).split(', ');\n const fkName = `${issue.table}_${columns.join('_')}_fkey`;\n const fk = ctx.toContract.storage.tables[issue.table]?.foreignKeys.find(\n (k) => k.columns.join(', ') === columns.join(', '),\n );\n if (fk) {\n const fkSpec: ForeignKeySpec = {\n name: fkName,\n columns: fk.columns,\n references: { table: fk.references.table, columns: fk.references.columns },\n ...(fk.onDelete !== undefined && { onDelete: fk.onDelete }),\n ...(fk.onUpdate !== undefined && { onUpdate: fk.onUpdate }),\n };\n return ok([new AddForeignKeyCall(schemaName, issue.table, fkSpec)]);\n }\n return notOk(\n issueConflict(\n 'foreignKeyConflict',\n `Foreign key on \"${issue.table}\" (${columns.join(', ')}) not found in destination contract`,\n { table: issue.table },\n ),\n );\n }\n }\n return notOk(\n issueConflict(\n 'foreignKeyConflict',\n `Foreign key on \"${issue.table}\" differs (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n case 'type_missing': {\n if (!issue.typeName)\n return notOk(issueConflict('unsupportedOperation', 'Type missing issue has no typeName'));\n const typeInstance = ctx.toContract.storage.types?.[issue.typeName];\n if (!typeInstance) {\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Type \"${issue.typeName}\" reported missing but not found in destination contract`,\n ),\n );\n }\n if (typeInstance.codecId.startsWith('pg/enum')) {\n const values = (typeInstance.typeParams['values'] ?? []) as readonly string[];\n return ok([new CreateEnumTypeCall(schemaName, typeInstance.nativeType, values)]);\n }\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Type \"${issue.typeName}\" uses codec \"${typeInstance.codecId}\" — only enum types are supported`,\n ),\n );\n }\n\n case 'type_values_mismatch':\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Type \"${issue.typeName ?? 'unknown'}\" values differ — type alteration not yet supported`,\n ),\n );\n\n case 'dependency_missing':\n if (!issue.dependencyId)\n return notOk(\n issueConflict('unsupportedOperation', 'Dependency missing issue has no dependencyId'),\n );\n if (issue.dependencyId.startsWith('ext:')) {\n return ok([new CreateExtensionCall(issue.dependencyId.slice(4))]);\n }\n if (issue.dependencyId.startsWith('schema:')) {\n return ok([new CreateSchemaCall(issue.dependencyId.slice(7))]);\n }\n return notOk(\n issueConflict('unsupportedOperation', `Unknown dependency type: ${issue.dependencyId}`),\n );\n\n default:\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Unhandled issue kind: ${(issue as SchemaIssue).kind}`,\n ),\n );\n }\n}\n\n/**\n * Classifies calls into dependency order categories for correct DDL sequencing.\n */\ntype CallCategory =\n | 'dep'\n | 'drop'\n | 'table'\n | 'column'\n | 'alter'\n | 'primaryKey'\n | 'unique'\n | 'index'\n | 'foreignKey';\n\n/**\n * Classifies calls into DDL sequencing buckets. The order matches the\n * legacy walk-schema planner's emission order so `db init` and `db update`\n * produce byte-identical plans for the shared shape (deps → drops → tables\n * → columns → alters → PKs → uniques → indexes → FKs).\n */\nfunction classifyCall(call: PostgresOpFactoryCall): CallCategory {\n switch (call.factoryName) {\n case 'createExtension':\n case 'createSchema':\n case 'createEnumType':\n case 'addEnumValues':\n case 'dropEnumType':\n case 'renameType':\n return 'dep';\n case 'dropTable':\n case 'dropColumn':\n case 'dropConstraint':\n case 'dropIndex':\n case 'dropDefault':\n return 'drop';\n case 'createTable':\n return 'table';\n case 'addColumn':\n return 'column';\n case 'alterColumnType':\n case 'setNotNull':\n case 'dropNotNull':\n case 'setDefault':\n return 'alter';\n case 'addPrimaryKey':\n return 'primaryKey';\n case 'addUnique':\n return 'unique';\n case 'createIndex':\n return 'index';\n case 'addForeignKey':\n return 'foreignKey';\n case 'rawSql': {\n // Install ops (`dependencyInstallCallStrategy`) and type ops\n // (`storageTypePlanCallStrategy`) both lift raw `SqlMigrationPlanOperation`s\n // through `RawSqlCall` to preserve the component-declared label and\n // precheck/postcheck. Classification falls back to inspecting the\n // underlying op's target details (`objectType: 'type'`) and id prefix\n // (`extension.*` / `schema.*`).\n const op = (\n call as {\n op?: {\n id?: string;\n target?: { details?: { objectType?: string } };\n };\n }\n ).op;\n const objectType = op?.target?.details?.objectType;\n if (objectType === 'type') return 'dep';\n const id = typeof op?.id === 'string' ? op.id : '';\n if (id.startsWith('extension.') || id.startsWith('schema.')) return 'dep';\n return 'alter';\n }\n default:\n return 'alter';\n }\n}\n\n/** Stable lexical key used to order issues within the same kind bucket. */\nfunction issueKey(issue: SchemaIssue): string {\n const table = 'table' in issue && typeof issue.table === 'string' ? issue.table : '';\n const column = 'column' in issue && typeof issue.column === 'string' ? issue.column : '';\n const name =\n 'indexOrConstraint' in issue && typeof issue.indexOrConstraint === 'string'\n ? issue.indexOrConstraint\n : '';\n return `${table}\\u0000${column}\\u0000${name}`;\n}\n\n// When no policy is explicitly supplied (test-only path; production callers\n// always pass one), allow every class so strategies that gate on\n// `'data'` (data-safe placeholders) still fire — the test is treated as\n// trusted. Filtering of actual emitted calls only runs when a policy was\n// explicitly provided (see `policyProvided` below).\nconst DEFAULT_POLICY: MigrationOperationPolicy = {\n allowedOperationClasses: ['additive', 'widening', 'destructive', 'data'],\n};\n\nfunction emptySchemaIR(): SqlSchemaIR {\n return { tables: {}, dependencies: [] };\n}\n\nfunction conflictKindForCall(call: PostgresOpFactoryCall): SqlPlannerConflict['kind'] {\n switch (call.factoryName) {\n case 'alterColumnType':\n return 'typeMismatch';\n case 'setNotNull':\n case 'dropNotNull':\n return 'nullabilityConflict';\n case 'addForeignKey':\n case 'dropConstraint':\n return 'foreignKeyConflict';\n case 'createIndex':\n case 'dropIndex':\n return 'indexIncompatible';\n default:\n return 'missingButNonAdditive';\n }\n}\n\nfunction locationForCall(call: PostgresOpFactoryCall): SqlPlannerConflict['location'] | undefined {\n // Most Postgres call classes expose `tableName`/`columnName`/`indexName`/\n // `constraintName` as readonly fields. We avoid `toOp()` here because a\n // `DataTransformCall` intentionally throws from `toOp`.\n const anyCall = call as unknown as {\n tableName?: string;\n columnName?: string;\n indexName?: string;\n constraintName?: string;\n typeName?: string;\n };\n const location: {\n table?: string;\n column?: string;\n index?: string;\n constraint?: string;\n type?: string;\n } = {};\n if (anyCall.tableName) location.table = anyCall.tableName;\n if (anyCall.columnName) location.column = anyCall.columnName;\n if (anyCall.indexName) location.index = anyCall.indexName;\n if (anyCall.constraintName) location.constraint = anyCall.constraintName;\n if (anyCall.typeName) location.type = anyCall.typeName;\n return Object.keys(location).length > 0 ? (location as SqlPlannerConflictLocation) : undefined;\n}\n\nfunction conflictForDisallowedCall(\n call: PostgresOpFactoryCall,\n allowed: readonly string[],\n): SqlPlannerConflict {\n const summary = `Operation \"${call.label}\" requires class \"${call.operationClass}\", but policy allows only: ${allowed.join(', ')}`;\n const location = locationForCall(call);\n return {\n kind: conflictKindForCall(call),\n summary,\n why: 'Use `migration new` to author a custom migration for this change.',\n ...(location ? { location } : {}),\n };\n}\n\nexport function planIssues(\n options: IssuePlannerOptions,\n): Result<IssuePlannerValue, readonly SqlPlannerConflict[]> {\n // When no policy is supplied, `planIssues` treats the call as trusted (the\n // caller — typically a test — has already vetted the issues). Only explicit\n // policies gate operation classes into conflicts.\n // `PostgresMigrationPlanner` always passes an explicit policy.\n const policyProvided = options.policy !== undefined;\n const policy = options.policy ?? DEFAULT_POLICY;\n const schema = options.schema ?? emptySchemaIR();\n const frameworkComponents = options.frameworkComponents ?? [];\n\n const context: StrategyContext = {\n toContract: options.toContract,\n fromContract: options.fromContract,\n schemaName: options.schemaName,\n codecHooks: options.codecHooks,\n storageTypes: options.storageTypes,\n schema,\n policy,\n frameworkComponents,\n };\n\n const strategies = options.strategies ?? postgresPlannerStrategies;\n\n let remaining = options.issues;\n const recipeCalls: PostgresOpFactoryCall[] = [];\n const bucketablePatternCalls: PostgresOpFactoryCall[] = [];\n\n for (const strategy of strategies) {\n const result = strategy(remaining, context);\n if (result.kind === 'match') {\n remaining = result.issues;\n if (result.recipe) {\n recipeCalls.push(...result.calls);\n } else {\n bucketablePatternCalls.push(...result.calls);\n }\n }\n }\n\n const sorted = [...remaining].sort((a, b) => {\n const kindDelta = issueOrder(a) - issueOrder(b);\n if (kindDelta !== 0) return kindDelta;\n const keyA = issueKey(a);\n const keyB = issueKey(b);\n return keyA < keyB ? -1 : keyA > keyB ? 1 : 0;\n });\n\n const defaultCalls: PostgresOpFactoryCall[] = [];\n const conflicts: SqlPlannerConflict[] = [];\n\n for (const issue of sorted) {\n const result = mapIssueToCall(issue, context);\n if (result.ok) {\n defaultCalls.push(...result.value);\n } else {\n conflicts.push(result.failure);\n }\n }\n\n // Policy gating: drop calls whose operation class is not allowed and\n // surface a conflict describing the disallowed op. Applies to both strategy\n // output and default-mapped output. Only active when the caller explicitly\n // supplied a policy — direct unit-test invocations (which pass no policy)\n // stay as pass-through and keep destructive recipe steps intact.\n const allowed = policy.allowedOperationClasses;\n let gatedDefault = defaultCalls;\n let gatedRecipe = recipeCalls;\n let gatedBucketable = bucketablePatternCalls;\n if (policyProvided) {\n const keepIfAllowed = (bucket: PostgresOpFactoryCall[]) => (call: PostgresOpFactoryCall) => {\n if (allowed.includes(call.operationClass)) {\n bucket.push(call);\n return;\n }\n conflicts.push(conflictForDisallowedCall(call, allowed));\n };\n const gatedDefaultBucket: PostgresOpFactoryCall[] = [];\n const gatedRecipeBucket: PostgresOpFactoryCall[] = [];\n const gatedBucketableBucket: PostgresOpFactoryCall[] = [];\n defaultCalls.forEach(keepIfAllowed(gatedDefaultBucket));\n recipeCalls.forEach(keepIfAllowed(gatedRecipeBucket));\n bucketablePatternCalls.forEach(keepIfAllowed(gatedBucketableBucket));\n gatedDefault = gatedDefaultBucket;\n gatedRecipe = gatedRecipeBucket;\n gatedBucketable = gatedBucketableBucket;\n }\n\n if (conflicts.length > 0) {\n return notOk(conflicts);\n }\n\n // Recipe strategies (`enumChangeCallStrategy`, `notNullBackfillCallStrategy`,\n // etc.) emit a cohesive sequence that must stay contiguous. They are\n // inserted at a single pattern slot. Non-recipe pattern strategies\n // (`dependencyInstallCallStrategy`, `storageTypePlanCallStrategy`,\n // `notNullAddColumnCallStrategy`) produce individually classifiable calls\n // that slot into DDL buckets alongside default-mapped calls.\n const combinedBucketable = [...gatedDefault, ...gatedBucketable];\n const byCategory = (cat: CallCategory) =>\n combinedBucketable.filter((c) => classifyCall(c) === cat);\n\n const calls: PostgresOpFactoryCall[] = [\n ...byCategory('dep'),\n ...byCategory('drop'),\n ...byCategory('table'),\n ...byCategory('column'),\n ...gatedRecipe,\n ...byCategory('alter'),\n ...byCategory('primaryKey'),\n ...byCategory('unique'),\n ...byCategory('index'),\n ...byCategory('foreignKey'),\n ];\n\n return ok({ calls });\n}\n","import type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { PostgresOpFactoryCall } from './op-factory-call';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\n\ntype Op = SqlMigrationPlanOperation<PostgresPlanTargetDetails>;\n\nexport function renderOps(calls: readonly PostgresOpFactoryCall[]): Op[] {\n return calls.map((c) => c.toOp());\n}\n","/**\n * Polymorphic TypeScript emitter for the Postgres migration IR.\n *\n * Each `PostgresOpFactoryCall` renders itself via `renderTypeScript()` and\n * declares its own `importRequirements()`; this file just composes the module\n * source around those contributions. The design mirrors the Mongo target's\n * `render-typescript.ts` deliberately — byte-for-byte alignment isn't required\n * (different factory module specifiers, different base-class name) but the\n * shape is, so future consolidation to a framework-level helper is mechanical.\n */\n\nimport { detectScaffoldRuntime, shebangLineFor } from '@prisma-next/migration-tools/migration-ts';\nimport { type ImportRequirement, jsonToTsSource, renderImports } from '@prisma-next/ts-render';\nimport type { PostgresOpFactoryCall } from './op-factory-call';\n\nexport interface RenderMigrationMeta {\n readonly from: string;\n readonly to: string;\n readonly kind?: string;\n readonly labels?: readonly string[];\n}\n\n/**\n * Always-present base import — the rendered scaffold always extends the\n * target-owned `Migration` (i.e. `PostgresMigration`) re-exported from\n * `@prisma-next/target-postgres/migration`. That re-export fixes the\n * `SqlMigration` generic to `PostgresPlanTargetDetails` and the abstract\n * `targetId` to `'postgres'`, so user-authored migrations don't need to\n * thread target-details or redeclare `targetId`.\n */\nconst BASE_IMPORT: ImportRequirement = {\n moduleSpecifier: '@prisma-next/target-postgres/migration',\n symbol: 'Migration',\n};\n\nexport function renderCallsToTypeScript(\n calls: ReadonlyArray<PostgresOpFactoryCall>,\n meta: RenderMigrationMeta,\n): string {\n const imports = buildImports(calls);\n const operationsBody = calls.map((c) => c.renderTypeScript()).join(',\\n');\n\n return [\n shebangLineFor(detectScaffoldRuntime()),\n imports,\n '',\n 'export default class M extends Migration {',\n buildDescribeMethod(meta),\n ' override get operations() {',\n ' return [',\n indent(operationsBody, 6),\n ' ];',\n ' }',\n '}',\n '',\n 'Migration.run(import.meta.url, M);',\n '',\n ].join('\\n');\n}\n\nfunction buildImports(calls: ReadonlyArray<PostgresOpFactoryCall>): string {\n const requirements: ImportRequirement[] = [BASE_IMPORT];\n for (const call of calls) {\n for (const req of call.importRequirements()) {\n requirements.push(req);\n }\n }\n return renderImports(requirements);\n}\n\nfunction buildDescribeMethod(meta: RenderMigrationMeta): string {\n const lines: string[] = [];\n lines.push(' override describe() {');\n lines.push(' return {');\n lines.push(` from: ${JSON.stringify(meta.from)},`);\n lines.push(` to: ${JSON.stringify(meta.to)},`);\n if (meta.kind) {\n lines.push(` kind: ${JSON.stringify(meta.kind)},`);\n }\n if (meta.labels && meta.labels.length > 0) {\n lines.push(` labels: ${jsonToTsSource(meta.labels)},`);\n }\n lines.push(' };');\n lines.push(' }');\n lines.push('');\n return lines.join('\\n');\n}\n\nfunction indent(text: string, spaces: number): string {\n const pad = ' '.repeat(spaces);\n return text\n .split('\\n')\n .map((line) => (line.trim() ? `${pad}${line}` : line))\n .join('\\n');\n}\n","/**\n * Planner-produced Postgres migration.\n *\n * Returned by `PostgresMigrationPlanner.plan(...)` and `emptyMigration(...)`.\n * Holds the migration IR (`PostgresOpFactoryCall[]`) alongside\n * `MigrationMeta` and exposes both the runtime-ops view (`get operations`)\n * and the TypeScript authoring view (`renderTypeScript()`). Satisfies\n * `MigrationPlanWithAuthoringSurface` so the CLI can uniformly serialize any\n * planner result back to `migration.ts`.\n *\n * Extends the family-level `SqlMigration` alias rather than the target-local\n * migration base directly — mirrors Mongo's `PlannerProducedMongoMigration`\n * shape and keeps CLI wiring one step removed from target internals.\n *\n * Placeholder-bearing plans: `renderTypeScript()` always succeeds and embeds\n * `() => placeholder(\"slot\")` at each stub. `operations`, in contrast, is\n * _not safe to enumerate_ on a stub-bearing plan — `DataTransformCall.toOp()`\n * throws `PN-MIG-2001` because a planner-stubbed closure cannot be lowered\n * to a runtime op. Callers that know a plan may carry stubs must render to\n * `migration.ts`, let the user fill the slots, and re-load the edited\n * migration before enumerating ops. The walk-schema planner does not emit\n * `DataTransformCall`s today, so this asymmetry is invisible until the\n * issue-planner integration lands in Phase 2.\n */\n\nimport type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { MigrationPlanWithAuthoringSurface } from '@prisma-next/framework-components/control';\nimport type { MigrationMeta } from '@prisma-next/migration-tools/migration';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresOpFactoryCall } from './op-factory-call';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\nimport { PostgresMigration } from './postgres-migration';\nimport { renderOps } from './render-ops';\nimport { renderCallsToTypeScript } from './render-typescript';\n\ntype Op = SqlMigrationPlanOperation<PostgresPlanTargetDetails>;\n\nexport class TypeScriptRenderablePostgresMigration\n extends PostgresMigration\n implements MigrationPlanWithAuthoringSurface\n{\n readonly #calls: readonly PostgresOpFactoryCall[];\n readonly #meta: MigrationMeta;\n\n constructor(calls: readonly PostgresOpFactoryCall[], meta: MigrationMeta) {\n super();\n this.#calls = calls;\n this.#meta = meta;\n }\n\n override get operations(): readonly Op[] {\n return renderOps(this.#calls);\n }\n\n override describe(): MigrationMeta {\n return this.#meta;\n }\n\n renderTypeScript(): string {\n return renderCallsToTypeScript(this.#calls, {\n from: this.#meta.from,\n to: this.#meta.to,\n ...ifDefined('kind', this.#meta.kind),\n ...ifDefined('labels', this.#meta.labels),\n });\n }\n}\n","import {\n normalizeSchemaNativeType,\n parsePostgresDefault,\n} from '@prisma-next/adapter-postgres/control';\nimport type {\n MigrationOperationPolicy,\n SqlMigrationPlannerPlanOptions,\n SqlPlannerFailureResult,\n} from '@prisma-next/family-sql/control';\nimport { extractCodecControlHooks, plannerFailure } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationPlanner,\n MigrationPlanWithAuthoringSurface,\n MigrationScaffoldContext,\n SchemaIssue,\n} from '@prisma-next/framework-components/control';\nimport { planIssues } from './issue-planner';\nimport { TypeScriptRenderablePostgresMigration } from './planner-produced-postgres-migration';\nimport { postgresPlannerStrategies } from './planner-strategies';\n\ntype PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {\n readonly frameworkComponents: infer T;\n}\n ? T\n : ReadonlyArray<unknown>;\n\ntype PlannerOptionsWithComponents = SqlMigrationPlannerPlanOptions & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype VerifySqlSchemaOptionsWithComponents = Parameters<typeof verifySqlSchema>[0] & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ninterface PlannerConfig {\n readonly defaultSchema: string;\n}\n\nconst DEFAULT_PLANNER_CONFIG: PlannerConfig = {\n defaultSchema: 'public',\n};\n\nexport function createPostgresMigrationPlanner(\n config: Partial<PlannerConfig> = {},\n): PostgresMigrationPlanner {\n return new PostgresMigrationPlanner({\n ...DEFAULT_PLANNER_CONFIG,\n ...config,\n });\n}\n\n/**\n * Result of `PostgresMigrationPlanner.plan()`. A discriminated union whose\n * success variant carries a `TypeScriptRenderablePostgresMigration` — a\n * migration object that both the CLI (via `renderTypeScript()`) and the\n * SQL-typed callers (via `operations`, `describe()`, etc.) consume\n * uniformly.\n */\nexport type PostgresPlanResult =\n | { readonly kind: 'success'; readonly plan: TypeScriptRenderablePostgresMigration }\n | SqlPlannerFailureResult;\n\n/**\n * Postgres migration planner — a thin wrapper over `planIssues`.\n *\n * `plan()` verifies the live schema against the target contract (producing\n * `SchemaIssue[]`) and delegates to `planIssues` with the unified\n * `postgresPlannerStrategies` list: enum-change, NOT-NULL backfill,\n * type-change, nullable-tightening, codec-hook storage types,\n * component-declared dependency installs, and shared-temp-default /\n * empty-table-guarded NOT-NULL add-column. The same strategy list runs for\n * `migration plan`, `db update`, and `db init`; behavior diverges purely on\n * `policy.allowedOperationClasses` (the data-safe strategies short-circuit\n * when `'data'` is excluded). The issue planner applies operation-class\n * policy gates and emits a single `PostgresOpFactoryCall[]` that drives both\n * the runtime-ops view (via `renderOps`) and the `renderTypeScript()`\n * authoring surface.\n */\nexport class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgres'> {\n constructor(private readonly config: PlannerConfig) {}\n\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n readonly fromHash?: string;\n /**\n * The \"from\" contract (state the planner assumes the database starts\n * at). Only `migration plan` supplies this; `db update` / `db init`\n * reconcile against the live schema with no old contract. When present\n * alongside the `'data'` operation class, strategies that need from/to\n * column shape comparisons (unsafe type change, nullability tightening)\n * activate.\n */\n readonly fromContract?: unknown;\n readonly schemaName?: string;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n }): PostgresPlanResult {\n return this.planSql(options as SqlMigrationPlannerPlanOptions, options.fromHash ?? '');\n }\n\n emptyMigration(context: MigrationScaffoldContext): MigrationPlanWithAuthoringSurface {\n return new TypeScriptRenderablePostgresMigration([], {\n from: context.fromHash,\n to: context.toHash,\n });\n }\n\n private planSql(options: SqlMigrationPlannerPlanOptions, fromHash: string): PostgresPlanResult {\n const schemaName = options.schemaName ?? this.config.defaultSchema;\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) {\n return policyResult;\n }\n\n const schemaIssues = this.collectSchemaIssues(options);\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n const storageTypes = options.contract.storage.types ?? {};\n\n const result = planIssues({\n issues: schemaIssues,\n toContract: options.contract,\n // `fromContract` is only supplied by `migration plan`. It is `null` for\n // `db update` / `db init`, which means data-safety strategies needing\n // from/to comparisons (unsafe type change, nullable tightening) are\n // inapplicable there — reconciliation falls through to\n // `mapIssueToCall`'s direct destructive handlers.\n fromContract: options.fromContract ?? null,\n schemaName,\n codecHooks,\n storageTypes,\n schema: options.schema,\n policy: options.policy,\n frameworkComponents: options.frameworkComponents,\n strategies: postgresPlannerStrategies,\n });\n\n if (!result.ok) {\n return plannerFailure(result.failure);\n }\n\n return Object.freeze({\n kind: 'success' as const,\n plan: new TypeScriptRenderablePostgresMigration(result.value.calls, {\n from: fromHash,\n to: options.contract.storage.storageHash,\n }),\n });\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n private collectSchemaIssues(options: PlannerOptionsWithComponents): readonly SchemaIssue[] {\n // `db init` uses additive-only policy and intentionally ignores extra\n // schema objects. Any reconciliation-capable policy (widening or\n // destructive) must inspect extras to reconcile strict equality.\n const allowed = options.policy.allowedOperationClasses;\n const strict = allowed.includes('widening') || allowed.includes('destructive');\n const verifyOptions: VerifySqlSchemaOptionsWithComponents = {\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n };\n const verifyResult = verifySqlSchema(verifyOptions);\n return verifyResult.schema.issues;\n }\n}\n","export interface SqlStatement {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\nexport const ensurePrismaContractSchemaStatement: SqlStatement = {\n sql: 'create schema if not exists prisma_contract',\n params: [],\n};\n\nexport const ensureMarkerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n id smallint primary key default 1,\n core_hash text not null,\n profile_hash text not null,\n contract_json jsonb,\n canonical_version int,\n updated_at timestamptz not null default now(),\n app_tag text,\n meta jsonb not null default '{}'\n )`,\n params: [],\n};\n\nexport const ensureLedgerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.ledger (\n id bigserial primary key,\n created_at timestamptz not null default now(),\n origin_core_hash text,\n origin_profile_hash text,\n destination_core_hash text not null,\n destination_profile_hash text,\n contract_json_before jsonb,\n contract_json_after jsonb,\n operations jsonb not null\n )`,\n params: [],\n};\n\nexport interface WriteMarkerInput {\n readonly storageHash: string;\n readonly profileHash: string;\n readonly contractJson?: unknown;\n readonly canonicalVersion?: number | null;\n readonly appTag?: string | null;\n readonly meta?: Record<string, unknown>;\n}\n\nexport function buildWriteMarkerStatements(input: WriteMarkerInput): {\n readonly insert: SqlStatement;\n readonly update: SqlStatement;\n} {\n const params: readonly unknown[] = [\n 1,\n input.storageHash,\n input.profileHash,\n jsonParam(input.contractJson),\n input.canonicalVersion ?? null,\n input.appTag ?? null,\n jsonParam(input.meta ?? {}),\n ];\n\n return {\n insert: {\n sql: `insert into prisma_contract.marker (\n id,\n core_hash,\n profile_hash,\n contract_json,\n canonical_version,\n updated_at,\n app_tag,\n meta\n ) values (\n $1,\n $2,\n $3,\n $4::jsonb,\n $5,\n now(),\n $6,\n $7::jsonb\n )`,\n params,\n },\n update: {\n sql: `update prisma_contract.marker set\n core_hash = $2,\n profile_hash = $3,\n contract_json = $4::jsonb,\n canonical_version = $5,\n updated_at = now(),\n app_tag = $6,\n meta = $7::jsonb\n where id = $1`,\n params,\n },\n };\n}\n\nexport interface LedgerInsertInput {\n readonly originStorageHash?: string | null;\n readonly originProfileHash?: string | null;\n readonly destinationStorageHash: string;\n readonly destinationProfileHash?: string | null;\n readonly contractJsonBefore?: unknown;\n readonly contractJsonAfter?: unknown;\n readonly operations: unknown;\n}\n\nexport function buildLedgerInsertStatement(input: LedgerInsertInput): SqlStatement {\n return {\n sql: `insert into prisma_contract.ledger (\n origin_core_hash,\n origin_profile_hash,\n destination_core_hash,\n destination_profile_hash,\n contract_json_before,\n contract_json_after,\n operations\n ) values (\n $1,\n $2,\n $3,\n $4,\n $5::jsonb,\n $6::jsonb,\n $7::jsonb\n )`,\n params: [\n input.originStorageHash ?? null,\n input.originProfileHash ?? null,\n input.destinationStorageHash,\n input.destinationProfileHash ?? null,\n jsonParam(input.contractJsonBefore),\n jsonParam(input.contractJsonAfter),\n jsonParam(input.operations),\n ],\n };\n}\n\nfunction jsonParam(value: unknown): string {\n return JSON.stringify(value ?? null);\n}\n","import {\n normalizeSchemaNativeType,\n parsePostgresDefault,\n} from '@prisma-next/adapter-postgres/control';\nimport type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport { readMarker } from '@prisma-next/family-sql/verify';\nimport type { DataTransformOperation } from '@prisma-next/framework-components/control';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { ok, okVoid } from '@prisma-next/utils/result';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\nimport {\n buildLedgerInsertStatement,\n buildWriteMarkerStatements,\n ensureLedgerTableStatement,\n ensureMarkerTableStatement,\n ensurePrismaContractSchemaStatement,\n type SqlStatement,\n} from './statement-builders';\n\ninterface RunnerConfig {\n readonly defaultSchema: string;\n}\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n}\n\nconst DEFAULT_CONFIG: RunnerConfig = {\n defaultSchema: 'public',\n};\n\nconst LOCK_DOMAIN = 'prisma_next.contract.marker';\n\nfunction isDataTransformOperation(op: unknown): op is DataTransformOperation {\n return (\n typeof op === 'object' &&\n op !== null &&\n 'operationClass' in op &&\n (op as { operationClass: string }).operationClass === 'data' &&\n 'name' in op &&\n 'check' in op &&\n 'run' in op\n );\n}\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n // Clone array (shallow clone of array elements)\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n // Recursively clone nested objects\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n // Primitives are copied as-is\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n config: Partial<RunnerConfig> = {},\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(\n private readonly family: SqlControlFamilyInstance,\n private readonly config: RunnerConfig,\n ) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema = options.schemaName ?? this.config.defaultSchema;\n const driver = options.driver;\n const lockKey = `${LOCK_DOMAIN}:${schema}`;\n\n // Static checks - fail fast before transaction\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) {\n return destinationCheck;\n }\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) {\n return policyCheck;\n }\n\n // Begin transaction for DB operations\n await this.beginTransaction(driver);\n let committed = false;\n try {\n await this.acquireLock(driver, lockKey);\n await this.ensureControlTables(driver);\n const existingMarker = await readMarker(driver);\n\n // Validate plan origin matches existing marker (needs marker from DB)\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) {\n return markerCheck;\n }\n\n // db update (origin: null) always applies; migration-apply (origin set) skips if marker matches.\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const skipOperations = markerAtDestination && options.plan.origin != null;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) {\n return applyResult;\n }\n applyValue = applyResult.value;\n }\n\n // Verify resulting schema matches contract\n // Step 1: Introspect live schema (DB I/O, family-owned)\n const schemaIR = await this.family.introspect({\n driver,\n contract: options.destinationContract,\n });\n\n // Step 2: Pure verification (no DB I/O)\n const schemaVerifyResult = verifySqlSchema({\n contract: options.destinationContract,\n schema: schemaIR,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n typeMetadataRegistry: this.family.typeMetadataRegistry,\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n if (!schemaVerifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: {\n issues: schemaVerifyResult.schema.issues,\n },\n });\n }\n\n // Record marker and ledger entries\n await this.upsertMarker(driver, options, existingMarker);\n await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);\n\n await this.commitTransaction(driver);\n committed = true;\n return runnerSuccess({\n operationsPlanned: options.plan.operations.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: 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 // Data transform operations have a different execution lifecycle\n if (operation.operationClass === 'data' && isDataTransformOperation(operation)) {\n const dtResult = await this.executeDataTransform(driver, operation, {\n runIdempotency,\n });\n if (!dtResult.ok) {\n return dtResult;\n }\n executedOperations.push(operation);\n operationsExecuted += 1;\n continue;\n }\n\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 /**\n * Executes a data transform operation with the check → (skip or run) → check lifecycle.\n *\n * 1. If check is a query AST: render to SQL, execute. Empty result = already applied (skip).\n * 2. If check is `true`: always skip. If `false`: always run.\n * 3. Execute run ASTs (rendered to SQL) sequentially.\n * 4. Re-execute check as post-run validation. If violations remain, fail.\n */\n private async executeDataTransform(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n op: DataTransformOperation,\n options: { runIdempotency: boolean },\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n // Step 1: Check (skip guard)\n if (op.check === true) {\n // Always skip, regardless of idempotency setting\n return okVoid();\n }\n if (options.runIdempotency && op.check !== null && op.check !== false) {\n const checkResult = await driver.query(op.check.sql, op.check.params);\n if (checkResult.rows.length === 0) {\n // No violations — already applied, skip\n return okVoid();\n }\n }\n\n // Step 2: Execute run steps\n if (op.run) {\n for (const plan of op.run) {\n try {\n await driver.query(plan.sql, plan.params);\n } catch (error: unknown) {\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Data transform \"${op.name}\" failed: ${error.message}`,\n {\n why: error.message,\n meta: {\n operationId: op.id,\n dataTransformName: op.name,\n sql: plan.sql,\n sqlState: error.sqlState,\n },\n },\n );\n }\n throw error;\n }\n }\n }\n\n // Step 3: Post-run validation (check again)\n if (op.check !== null && op.check !== false) {\n const checkResult = await driver.query(op.check.sql, op.check.params);\n if (checkResult.rows.length > 0) {\n return runnerFailure(\n 'POSTCHECK_FAILED',\n `Data transform \"${op.name}\" did not resolve all violations (${checkResult.rows.length} remaining)`,\n {\n why: `After executing the data transform, the check query still returns ${checkResult.rows.length} violation(s).`,\n meta: {\n operationId: op.id,\n dataTransformName: op.name,\n remainingViolations: checkResult.rows.length,\n },\n },\n );\n }\n }\n\n return okVoid();\n }\n\n private async ensureControlTables(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await this.executeStatement(driver, ensurePrismaContractSchemaStatement);\n await this.executeStatement(driver, ensureMarkerTableStatement);\n await this.executeStatement(driver, ensureLedgerTableStatement);\n }\n\n private async runExpectationSteps(\n driver: 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);\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);\n } catch (error: unknown) {\n // Catch SqlQueryError and include normalized metadata\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n // Let SqlConnectionError and other errors propagate (fail-fast)\n throw error;\n }\n }\n return okVoid();\n }\n\n private stepResultIsTrue(rows: readonly Record<string, unknown>[]): boolean {\n if (!rows || rows.length === 0) {\n return false;\n }\n const firstRow = rows[0];\n const firstValue = firstRow ? Object.values(firstRow)[0] : undefined;\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n // PostgreSQL boolean representations: 't'/'f', 'true'/'false', '1'/'0'\n if (lower === 't' || lower === 'true' || lower === '1') {\n return true;\n }\n if (lower === 'f' || lower === 'false' || lower === '0') {\n return false;\n }\n // For other strings, non-empty is truthy (though this case shouldn't occur for boolean checks)\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n ): Promise<boolean> {\n if (steps.length === 0) {\n return false;\n }\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n // Clone and freeze existing meta if present\n const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : undefined;\n\n // Create frozen runner metadata\n const runnerMeta = Object.freeze({\n skipped: true,\n reason: 'postcheck_pre_satisfied',\n });\n\n // Merge and freeze the combined meta\n const mergedMeta = Object.freeze({\n ...(clonedMeta ?? {}),\n runner: runnerMeta,\n });\n\n // Clone and freeze arrays to prevent mutation\n const frozenPostcheck = Object.freeze([...operation.postcheck]);\n\n return Object.freeze({\n id: operation.id,\n label: operation.label,\n ...ifDefined('summary', operation.summary),\n operationClass: operation.operationClass,\n target: operation.target, // Already frozen from plan creation\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: frozenPostcheck,\n ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\n return false;\n }\n if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {\n return false;\n }\n return true;\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${policy.allowedOperationClasses.join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n allowedClasses: policy.allowedOperationClasses,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n // No origin assertion on the plan — the caller does not want origin validation.\n // This is the case for `db update`, which introspects the live schema and does not\n // rely on marker continuity. `db init` handles its own marker checks before the runner.\n return okVoid();\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n {\n meta: {\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (origin.profileHash && marker.profileHash !== origin.profileHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`,\n {\n meta: {\n markerProfileHash: marker.profileHash,\n expectedOriginProfileHash: origin.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private ensurePlanMatchesDestinationContract(\n destination: SqlMigrationPlanContractInfo,\n contract: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['destinationContract'],\n ): Result<void, SqlMigrationRunnerFailure> {\n if (destination.storageHash !== contract.storage.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storage.storageHash,\n },\n },\n );\n }\n if (\n destination.profileHash &&\n contract.profileHash &&\n destination.profileHash !== contract.profileHash\n ) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`,\n {\n meta: {\n planProfileHash: destination.profileHash,\n contractProfileHash: contract.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async upsertMarker(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n ): Promise<void> {\n const writeStatements = buildWriteMarkerStatements({\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 });\n const statement = existingMarker ? writeStatements.update : writeStatements.insert;\n await this.executeStatement(driver, statement);\n }\n\n private async recordLedgerEntry(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Promise<void> {\n const ledgerStatement = buildLedgerInsertStatement({\n originStorageHash: existingMarker?.storageHash ?? null,\n originProfileHash: existingMarker?.profileHash ?? null,\n destinationStorageHash: options.plan.destination.storageHash,\n destinationProfileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJsonBefore: existingMarker?.contractJson ?? null,\n contractJsonAfter: options.destinationContract,\n operations: executedOperations,\n });\n await this.executeStatement(driver, ledgerStatement);\n }\n\n private async acquireLock(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n key: string,\n ): Promise<void> {\n await driver.query('select pg_advisory_xact_lock(hashtext($1))', [key]);\n }\n\n private async beginTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n statement: SqlStatement,\n ): Promise<void> {\n if (statement.params.length > 0) {\n await driver.query(statement.sql, statement.params);\n return;\n }\n await driver.query(statement.sql);\n }\n}\n","import type { ColumnDefault, Contract } from '@prisma-next/contract/types';\nimport type {\n SqlControlFamilyInstance,\n SqlControlTargetDescriptor,\n} from '@prisma-next/family-sql/control';\nimport { contractToSchemaIR, extractCodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlTargetInstance,\n MigrationRunner,\n} from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nfunction buildNativeTypeExpander(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n if (!frameworkComponents) {\n return undefined;\n }\n const codecHooks = extractCodecControlHooks(frameworkComponents);\n return (input: {\n readonly nativeType: string;\n readonly codecId?: string;\n readonly typeParams?: Record<string, unknown>;\n }) => {\n if (!input.typeParams) return input.nativeType;\n // Mirror `renderExpectedNativeType` in verify-sql-schema: when a codec\n // has no `expandNativeType` hook (e.g. `pg/enum@1`, whose typeParams\n // describe the value set rather than a DDL suffix), fall back to the\n // bare native type rather than throwing. Throwing here would reject\n // every plan involving an enum-/values-typed column as soon as its\n // `typeRef` resolved to a `StorageTypeInstance` carrying typeParams.\n if (!input.codecId) return input.nativeType;\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) return input.nativeType;\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n migrations: {\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n return contractToSchemaIR(contract as Contract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n frameworkComponents: frameworkComponents ?? [],\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA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MAAM,QAAS,QAAO,MAAM;EACjC,MAAM,QAAQ,WAAW,IAAI,MAAM,QAAQ;AAC3C,MAAI,CAAC,OAAO,iBAAkB,QAAO,MAAM;AAC3C,SAAO,MAAM,iBAAiB,MAAM;;;AAIxC,SAAgB,sBAAsB,KAAoB,QAA+B;AACvF,KAAI,IAAI,SAAS,WACf,QAAO,IAAI;AAEb,QAAO,qBAAqB,IAAI,OAAO,OAAO;;AAGhD,MAAMC,2BACJ;CACE,GAAG;CACH,YAAY;EACV,cAAc,SAAmC;AAC/C,UAAO,gCAAgC;;EAEzC,aAAa,QAAQ;AACnB,UAAO,8BAA8B,OAAO;;EAE9C,iBAAiB,UAAU,qBAAqB;AAE9C,UAAO,mBAAmB,UAAyC;IACjE,qBAAqB;IACrB,GAAG,UAAU,oBAHE,wBAAwB,oBAAoB,CAGjB;IAC1C,eAAe;IACf,qBAAqB,uBAAuB,EAAE;IAC/C,CAAC;;EAEL;CACD,SAAmD;AACjD,SAAO;GACL,UAAU;GACV,UAAU;GACX;;CAMH,cAAc,SAAmC;AAC/C,SAAO,gCAAgC;;CAMzC,aAAa,QAAQ;AACnB,SAAO,8BAA8B,OAAO;;CAE/C;AAEH,sBAAe"}
1
+ {"version":3,"file":"control.mjs","names":["DEFAULT_CONFIG: RunnerConfig","cloned: Record<string, unknown>","family: SqlControlFamilyInstance","config: RunnerConfig","applyValue: ApplyPlanSuccessValue","executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>","error: unknown","postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails>"],"sources":["../src/core/migrations/runner.ts","../src/exports/control.ts"],"sourcesContent":["import type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { DataTransformOperation } from '@prisma-next/framework-components/control';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { ok, okVoid } from '@prisma-next/utils/result';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\nimport {\n buildLedgerInsertStatement,\n buildMergeMarkerStatements,\n ensureLedgerTableStatement,\n ensureMarkerTableStatement,\n ensurePrismaContractSchemaStatement,\n type SqlStatement,\n} from './statement-builders';\n\ninterface RunnerConfig {\n readonly defaultSchema: string;\n}\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n}\n\nconst DEFAULT_CONFIG: RunnerConfig = {\n defaultSchema: 'public',\n};\n\nconst LOCK_DOMAIN = 'prisma_next.contract.marker';\n\nfunction isDataTransformOperation(op: unknown): op is DataTransformOperation {\n return (\n typeof op === 'object' &&\n op !== null &&\n 'operationClass' in op &&\n (op as { operationClass: string }).operationClass === 'data' &&\n 'name' in op &&\n 'check' in op &&\n 'run' in op\n );\n}\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n // Clone array (shallow clone of array elements)\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n // Recursively clone nested objects\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n // Primitives are copied as-is\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n config: Partial<RunnerConfig> = {},\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(\n private readonly family: SqlControlFamilyInstance,\n private readonly config: RunnerConfig,\n ) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema = options.schemaName ?? this.config.defaultSchema;\n const driver = options.driver;\n const lockKey = `${LOCK_DOMAIN}:${schema}`;\n\n // Static checks - fail fast before transaction\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) {\n return destinationCheck;\n }\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) {\n return policyCheck;\n }\n\n // Begin transaction for DB operations\n await this.beginTransaction(driver);\n let committed = false;\n try {\n await this.acquireLock(driver, lockKey);\n await this.ensureControlTables(driver);\n const existingMarker = await this.family.readMarker({ driver });\n\n // Validate plan origin matches existing marker (needs marker from DB)\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) {\n return markerCheck;\n }\n\n // db update (origin: null) always applies; migration-apply (origin set,\n // origin !== destination) skips if marker already matches destination.\n // Self-edges (origin === destination) intentionally bypass the skip:\n // the migration is data-only, and the data transform's own check\n // decides whether `run` fires.\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;\n const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) {\n return applyResult;\n }\n applyValue = applyResult.value;\n }\n\n // Verify resulting schema matches contract\n // Step 1: Introspect live schema (DB I/O, family-owned)\n const schemaIR = await this.family.introspect({\n driver,\n contract: options.destinationContract,\n });\n\n // Step 2: Pure verification (no DB I/O)\n const schemaVerifyResult = verifySqlSchema({\n contract: options.destinationContract,\n schema: schemaIR,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n typeMetadataRegistry: this.family.typeMetadataRegistry,\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n if (!schemaVerifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: {\n issues: schemaVerifyResult.schema.issues,\n },\n });\n }\n\n // Self-edge no-op detection: a self-edge migration with zero ops in\n // the plan that brings no new invariants produced no observable\n // change. Skip the marker + ledger writes so an idempotent re-apply\n // of a self-edge data transform doesn't churn updatedAt or pile up\n // empty ledger entries. db update no-ops still write a ledger entry\n // as audit trail.\n //\n // TODO(invariant-routing follow-up): `executeDataTransform` always\n // counts every op it visits (including self-skips via `check === true`\n // or empty idempotency probe), so `operationsExecuted === 0` here\n // means \"the plan had zero ops\" rather than \"every op self-skipped\".\n // The CLI is unaffected today because `migration-apply.ts` marker-\n // subtraction empties `effectiveRequired` first and short-circuits\n // before we run; the non-CLI re-apply path needs a per-op `executed`\n // flag threaded through `executeDataTransform` to recover the\n // intended check. See review thread A13 / future M5 ADR draft.\n const incomingInvariants = options.plan.providedInvariants;\n const existingInvariants = new Set(existingMarker?.invariants ?? []);\n const incomingIsSubsetOfExisting = incomingInvariants.every((id) =>\n existingInvariants.has(id),\n );\n const isSelfEdgeNoOp =\n isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting;\n\n if (!isSelfEdgeNoOp) {\n await this.upsertMarker(driver, options, existingMarker);\n await this.recordLedgerEntry(\n driver,\n options,\n existingMarker,\n applyValue.executedOperations,\n );\n }\n\n await this.commitTransaction(driver);\n committed = true;\n return runnerSuccess({\n operationsPlanned: options.plan.operations.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<Result<ApplyPlanSuccessValue, SqlMigrationRunnerFailure>> {\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false; // Default true\n const runPostchecks = checks?.postchecks !== false; // Default true\n const runIdempotency = checks?.idempotencyChecks !== false; // Default true\n\n let operationsExecuted = 0;\n const executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> = [];\n for (const operation of options.plan.operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n // Data transform operations have a different execution lifecycle\n if (operation.operationClass === 'data' && isDataTransformOperation(operation)) {\n const dtResult = await this.executeDataTransform(driver, operation, {\n runIdempotency,\n });\n if (!dtResult.ok) {\n return dtResult;\n }\n executedOperations.push(operation);\n operationsExecuted += 1;\n continue;\n }\n\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 /**\n * Executes a data transform operation with the check → (skip or run) → check lifecycle.\n *\n * 1. If check is a query AST: render to SQL, execute. Empty result = already applied (skip).\n * 2. If check is `true`: always skip. If `false`: always run.\n * 3. Execute run ASTs (rendered to SQL) sequentially.\n * 4. Re-execute check as post-run validation. If violations remain, fail.\n */\n private async executeDataTransform(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n op: DataTransformOperation,\n options: { runIdempotency: boolean },\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n // Step 1: Check (skip guard)\n if (op.check === true) {\n // Always skip, regardless of idempotency setting\n return okVoid();\n }\n if (options.runIdempotency && op.check !== null && op.check !== false) {\n const checkResult = await driver.query(op.check.sql, op.check.params);\n if (checkResult.rows.length === 0) {\n // No violations — already applied, skip\n return okVoid();\n }\n }\n\n // Step 2: Execute run steps\n if (op.run) {\n for (const plan of op.run) {\n try {\n await driver.query(plan.sql, plan.params);\n } catch (error: unknown) {\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Data transform \"${op.name}\" failed: ${error.message}`,\n {\n why: error.message,\n meta: {\n operationId: op.id,\n dataTransformName: op.name,\n sql: plan.sql,\n sqlState: error.sqlState,\n },\n },\n );\n }\n throw error;\n }\n }\n }\n\n // Step 3: Post-run validation (check again)\n if (op.check !== null && op.check !== false) {\n const checkResult = await driver.query(op.check.sql, op.check.params);\n if (checkResult.rows.length > 0) {\n return runnerFailure(\n 'POSTCHECK_FAILED',\n `Data transform \"${op.name}\" did not resolve all violations (${checkResult.rows.length} remaining)`,\n {\n why: `After executing the data transform, the check query still returns ${checkResult.rows.length} violation(s).`,\n meta: {\n operationId: op.id,\n dataTransformName: op.name,\n remainingViolations: checkResult.rows.length,\n },\n },\n );\n }\n }\n\n return okVoid();\n }\n\n private async ensureControlTables(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await this.executeStatement(driver, ensurePrismaContractSchemaStatement);\n await this.executeStatement(driver, ensureMarkerTableStatement);\n await this.executeStatement(driver, ensureLedgerTableStatement);\n }\n\n private async runExpectationSteps(\n driver: 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);\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);\n } catch (error: unknown) {\n // Catch SqlQueryError and include normalized metadata\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n // Let SqlConnectionError and other errors propagate (fail-fast)\n throw error;\n }\n }\n return okVoid();\n }\n\n private stepResultIsTrue(rows: readonly Record<string, unknown>[]): boolean {\n if (!rows || rows.length === 0) {\n return false;\n }\n const firstRow = rows[0];\n const firstValue = firstRow ? Object.values(firstRow)[0] : undefined;\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n // PostgreSQL boolean representations: 't'/'f', 'true'/'false', '1'/'0'\n if (lower === 't' || lower === 'true' || lower === '1') {\n return true;\n }\n if (lower === 'f' || lower === 'false' || lower === '0') {\n return false;\n }\n // For other strings, non-empty is truthy (though this case shouldn't occur for boolean checks)\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n ): Promise<boolean> {\n if (steps.length === 0) {\n return false;\n }\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n // Clone and freeze existing meta if present\n const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : undefined;\n\n // Create frozen runner metadata\n const runnerMeta = Object.freeze({\n skipped: true,\n reason: 'postcheck_pre_satisfied',\n });\n\n // Merge and freeze the combined meta\n const mergedMeta = Object.freeze({\n ...(clonedMeta ?? {}),\n runner: runnerMeta,\n });\n\n // Clone and freeze arrays to prevent mutation\n const frozenPostcheck = Object.freeze([...operation.postcheck]);\n\n return Object.freeze({\n id: operation.id,\n label: operation.label,\n ...ifDefined('summary', operation.summary),\n operationClass: operation.operationClass,\n target: operation.target, // Already frozen from plan creation\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: frozenPostcheck,\n ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\n return false;\n }\n if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {\n return false;\n }\n return true;\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${policy.allowedOperationClasses.join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n allowedClasses: policy.allowedOperationClasses,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n // No origin assertion on the plan — the caller does not want origin validation.\n // This is the case for `db update`, which introspects the live schema and does not\n // rely on marker continuity. `db init` handles its own marker checks before the runner.\n return okVoid();\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n {\n meta: {\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (origin.profileHash && marker.profileHash !== origin.profileHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`,\n {\n meta: {\n markerProfileHash: marker.profileHash,\n expectedOriginProfileHash: origin.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private ensurePlanMatchesDestinationContract(\n destination: SqlMigrationPlanContractInfo,\n contract: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['destinationContract'],\n ): Result<void, SqlMigrationRunnerFailure> {\n if (destination.storageHash !== contract.storage.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storage.storageHash,\n },\n },\n );\n }\n if (\n destination.profileHash &&\n contract.profileHash &&\n destination.profileHash !== contract.profileHash\n ) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`,\n {\n meta: {\n planProfileHash: destination.profileHash,\n contractProfileHash: contract.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async upsertMarker(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n ): Promise<void> {\n const incomingInvariants = options.plan.providedInvariants;\n const writeStatements = buildMergeMarkerStatements({\n storageHash: options.plan.destination.storageHash,\n profileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJson: options.destinationContract,\n canonicalVersion: null,\n meta: {},\n invariants: incomingInvariants,\n });\n const statement = existingMarker ? writeStatements.update : writeStatements.insert;\n await this.executeStatement(driver, statement);\n }\n\n private async recordLedgerEntry(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Promise<void> {\n const ledgerStatement = buildLedgerInsertStatement({\n originStorageHash: existingMarker?.storageHash ?? null,\n originProfileHash: existingMarker?.profileHash ?? null,\n destinationStorageHash: options.plan.destination.storageHash,\n destinationProfileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJsonBefore: existingMarker?.contractJson ?? null,\n contractJsonAfter: options.destinationContract,\n operations: executedOperations,\n });\n await this.executeStatement(driver, ledgerStatement);\n }\n\n private async acquireLock(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n key: string,\n ): Promise<void> {\n await driver.query('select pg_advisory_xact_lock(hashtext($1))', [key]);\n }\n\n private async beginTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n statement: SqlStatement,\n ): Promise<void> {\n if (statement.params.length > 0) {\n await driver.query(statement.sql, statement.params);\n return;\n }\n await driver.query(statement.sql);\n }\n}\n","import type { ColumnDefault, Contract } from '@prisma-next/contract/types';\nimport type {\n SqlControlFamilyInstance,\n SqlControlTargetDescriptor,\n} from '@prisma-next/family-sql/control';\nimport { contractToSchemaIR, extractCodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlTargetInstance,\n MigrationRunner,\n} from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nfunction buildNativeTypeExpander(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n if (!frameworkComponents) {\n return undefined;\n }\n const codecHooks = extractCodecControlHooks(frameworkComponents);\n return (input: {\n readonly nativeType: string;\n readonly codecId?: string;\n readonly typeParams?: Record<string, unknown>;\n }) => {\n if (!input.typeParams) return input.nativeType;\n // Mirror `renderExpectedNativeType` in verify-sql-schema: when a codec\n // has no `expandNativeType` hook (e.g. `pg/enum@1`, whose typeParams\n // describe the value set rather than a DDL suffix), fall back to the\n // bare native type rather than throwing. Throwing here would reject\n // every plan involving an enum-/values-typed column as soon as its\n // `typeRef` resolved to a `StorageTypeInstance` carrying typeParams.\n if (!input.codecId) return input.nativeType;\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) return input.nativeType;\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n migrations: {\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n return contractToSchemaIR(contract as Contract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n frameworkComponents: frameworkComponents ?? [],\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;;AAwCA,MAAMA,iBAA+B,EACnC,eAAe,UAChB;AAED,MAAM,cAAc;AAEpB,SAAS,yBAAyB,IAA2C;AAC3E,QACE,OAAO,OAAO,YACd,OAAO,QACP,oBAAoB,MACnB,GAAkC,mBAAmB,UACtD,UAAU,MACV,WAAW,MACX,SAAS;;;;;;AAQb,SAAS,qBAAwD,OAAa;CAC5E,MAAMC,SAAkC,EAAE;AAC1C,MAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,MAAM,CAC5C,KAAI,QAAQ,QAAQ,QAAQ,OAC1B,QAAO,OAAO;UACL,MAAM,QAAQ,IAAI,CAE3B,QAAO,OAAO,OAAO,OAAO,CAAC,GAAG,IAAI,CAAC;UAC5B,OAAO,QAAQ,SAExB,QAAO,OAAO,qBAAqB,IAA+B;KAGlE,QAAO,OAAO;AAGlB,QAAO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