@prisma-next/target-postgres 0.14.0-dev.4 → 0.14.0-dev.41

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 (191) hide show
  1. package/dist/authoring-BX1WHIdN.mjs +220 -0
  2. package/dist/authoring-BX1WHIdN.mjs.map +1 -0
  3. package/dist/canonicalize-Bn3BM1Cn.mjs +46 -0
  4. package/dist/canonicalize-Bn3BM1Cn.mjs.map +1 -0
  5. package/dist/canonicalize-CAbXtVtB.d.mts +37 -0
  6. package/dist/canonicalize-CAbXtVtB.d.mts.map +1 -0
  7. package/dist/{codec-types-DHCkwPKE.d.mts → codec-types-CueCoGD0.d.mts} +2 -2
  8. package/dist/{codec-types-DHCkwPKE.d.mts.map → codec-types-CueCoGD0.d.mts.map} +1 -1
  9. package/dist/codec-types.d.mts +1 -1
  10. package/dist/{codecs--0A5_4Bq.d.mts → codecs-Ca8upop6.d.mts} +12 -1
  11. package/dist/codecs-Ca8upop6.d.mts.map +1 -0
  12. package/dist/codecs.d.mts +1 -1
  13. package/dist/codecs.mjs +34 -1
  14. package/dist/codecs.mjs.map +1 -1
  15. package/dist/contract-free.d.mts +8 -3
  16. package/dist/contract-free.d.mts.map +1 -1
  17. package/dist/contract-free.mjs +3 -3
  18. package/dist/control.d.mts +1 -1
  19. package/dist/control.d.mts.map +1 -1
  20. package/dist/control.mjs +639 -21
  21. package/dist/control.mjs.map +1 -1
  22. package/dist/data-transform-BOWpliq8.mjs.map +1 -1
  23. package/dist/{data-transform-DDgWdB5o.d.mts → data-transform-qKy1U5V9.d.mts} +2 -2
  24. package/dist/{data-transform-DDgWdB5o.d.mts.map → data-transform-qKy1U5V9.d.mts.map} +1 -1
  25. package/dist/data-transform.d.mts +1 -1
  26. package/dist/{ddl-QDyOSeLc.mjs → ddl-BmLIe1z_.mjs} +62 -5
  27. package/dist/ddl-BmLIe1z_.mjs.map +1 -0
  28. package/dist/ddl.d.mts +3 -2
  29. package/dist/ddl.mjs +2 -2
  30. package/dist/{default-normalizer-DyyCHQWs.mjs → default-normalizer-Dug8Fez9.mjs} +119 -2
  31. package/dist/default-normalizer-Dug8Fez9.mjs.map +1 -0
  32. package/dist/default-normalizer.d.mts +1 -1
  33. package/dist/default-normalizer.d.mts.map +1 -1
  34. package/dist/default-normalizer.mjs +1 -1
  35. package/dist/descriptor-meta-runtime-UwYdV8fD.mjs +12 -0
  36. package/dist/descriptor-meta-runtime-UwYdV8fD.mjs.map +1 -0
  37. package/dist/descriptor-meta-tjatyhtZ.mjs +18 -0
  38. package/dist/descriptor-meta-tjatyhtZ.mjs.map +1 -0
  39. package/dist/{issue-planner-DL6g3CmE.mjs → issue-planner-DbFvaAgu.mjs} +35 -10
  40. package/dist/issue-planner-DbFvaAgu.mjs.map +1 -0
  41. package/dist/issue-planner.d.mts +3 -3
  42. package/dist/issue-planner.d.mts.map +1 -1
  43. package/dist/issue-planner.mjs +1 -1
  44. package/dist/migration.d.mts +5 -5
  45. package/dist/migration.mjs +4 -4
  46. package/dist/nodes-CSkPX3rI.d.mts +120 -0
  47. package/dist/nodes-CSkPX3rI.d.mts.map +1 -0
  48. package/dist/{nodes-Bbhs2rwj.mjs → nodes-Dh__NS58.mjs} +56 -2
  49. package/dist/nodes-Dh__NS58.mjs.map +1 -0
  50. package/dist/{op-factory-call-DmQEc3XV.d.mts → op-factory-call-CJWUxyUW.d.mts} +44 -13
  51. package/dist/op-factory-call-CJWUxyUW.d.mts.map +1 -0
  52. package/dist/{op-factory-call-D_p5vxwt.mjs → op-factory-call-t65c4jyY.mjs} +201 -28
  53. package/dist/op-factory-call-t65c4jyY.mjs.map +1 -0
  54. package/dist/op-factory-call.d.mts +1 -1
  55. package/dist/op-factory-call.mjs +1 -1
  56. package/dist/pack.d.mts +74 -2
  57. package/dist/pack.d.mts.map +1 -1
  58. package/dist/pack.mjs +1 -1
  59. package/dist/planner-CG2pLHk-.mjs +640 -0
  60. package/dist/planner-CG2pLHk-.mjs.map +1 -0
  61. package/dist/{planner-ddl-builders-B2wOwLqI.mjs → planner-ddl-builders-B8Nn6nHN.mjs} +12 -27
  62. package/dist/planner-ddl-builders-B8Nn6nHN.mjs.map +1 -0
  63. package/dist/planner-ddl-builders.d.mts +2 -4
  64. package/dist/planner-ddl-builders.d.mts.map +1 -1
  65. package/dist/planner-ddl-builders.mjs +2 -2
  66. package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs → planner-produced-postgres-migration-BolD0Mvc.mjs} +3 -3
  67. package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs.map → planner-produced-postgres-migration-BolD0Mvc.mjs.map} +1 -1
  68. package/dist/{planner-produced-postgres-migration-QqHa2C2l.d.mts → planner-produced-postgres-migration-Cz9--XOT.d.mts} +4 -4
  69. package/dist/{planner-produced-postgres-migration-QqHa2C2l.d.mts.map → planner-produced-postgres-migration-Cz9--XOT.d.mts.map} +1 -1
  70. package/dist/planner-produced-postgres-migration.d.mts +1 -1
  71. package/dist/planner-produced-postgres-migration.mjs +1 -1
  72. package/dist/{planner-sql-checks-jqUUGyQR.mjs → planner-sql-checks-DE9c4519.mjs} +2 -2
  73. package/dist/{planner-sql-checks-jqUUGyQR.mjs.map → planner-sql-checks-DE9c4519.mjs.map} +1 -1
  74. package/dist/planner-sql-checks.mjs +1 -1
  75. package/dist/{planner-target-details-CIY6tLeo.d.mts → planner-target-details-HkP4RrRO.d.mts} +2 -2
  76. package/dist/planner-target-details-HkP4RrRO.d.mts.map +1 -0
  77. package/dist/planner-target-details.d.mts +1 -1
  78. package/dist/planner.d.mts +82 -4
  79. package/dist/planner.d.mts.map +1 -1
  80. package/dist/planner.mjs +2 -2
  81. package/dist/{postgres-contract-serializer-k3TAcPMY.mjs → postgres-contract-view-BegduLr6.mjs} +50 -23
  82. package/dist/postgres-contract-view-BegduLr6.mjs.map +1 -0
  83. package/dist/postgres-contract-view-C9j5cqP0.d.mts +34 -0
  84. package/dist/postgres-contract-view-C9j5cqP0.d.mts.map +1 -0
  85. package/dist/postgres-database-schema-node-os8ogEap.d.mts +183 -0
  86. package/dist/postgres-database-schema-node-os8ogEap.d.mts.map +1 -0
  87. package/dist/{postgres-migration-B5jKrXv3.mjs → postgres-migration-BfMmK6tv.mjs} +21 -2
  88. package/dist/postgres-migration-BfMmK6tv.mjs.map +1 -0
  89. package/dist/{postgres-migration-Y4YBJqkS.d.mts → postgres-migration-D7kNVWVG.d.mts} +19 -6
  90. package/dist/postgres-migration-D7kNVWVG.d.mts.map +1 -0
  91. package/dist/postgres-rls-policy--CSddvMR.d.mts +52 -0
  92. package/dist/postgres-rls-policy--CSddvMR.d.mts.map +1 -0
  93. package/dist/{postgres-schema-COGZ1ark.mjs → postgres-schema-BLIHBEfX.mjs} +108 -5
  94. package/dist/postgres-schema-BLIHBEfX.mjs.map +1 -0
  95. package/dist/postgres-schema-BywoeKlt.d.mts +189 -0
  96. package/dist/postgres-schema-BywoeKlt.d.mts.map +1 -0
  97. package/dist/postgres-table-schema-node-1nNc8XDT.mjs +248 -0
  98. package/dist/postgres-table-schema-node-1nNc8XDT.mjs.map +1 -0
  99. package/dist/render-ops.d.mts +1 -1
  100. package/dist/{render-typescript-KMgosran.mjs → render-typescript-7yqILcwr.mjs} +45 -16
  101. package/dist/render-typescript-7yqILcwr.mjs.map +1 -0
  102. package/dist/render-typescript.mjs +1 -1
  103. package/dist/resolve-ddl-schema-CL1RR1mx.mjs +20 -0
  104. package/dist/resolve-ddl-schema-CL1RR1mx.mjs.map +1 -0
  105. package/dist/rls-canonicalize.d.mts +2 -0
  106. package/dist/rls-canonicalize.mjs +2 -0
  107. package/dist/runtime.d.mts +7 -6
  108. package/dist/runtime.d.mts.map +1 -1
  109. package/dist/runtime.mjs +3 -3
  110. package/dist/runtime.mjs.map +1 -1
  111. package/dist/schema-ir-annotations.d.mts +14 -0
  112. package/dist/schema-ir-annotations.d.mts.map +1 -0
  113. package/dist/schema-ir-annotations.mjs +2 -0
  114. package/dist/types.d.mts +4 -140
  115. package/dist/types.mjs +3 -2
  116. package/package.json +22 -17
  117. package/src/contract-free/checks.ts +73 -0
  118. package/src/contract-free/ddl.ts +45 -1
  119. package/src/core/authoring.ts +115 -1
  120. package/src/core/codecs.ts +35 -1
  121. package/src/core/ddl/nodes.ts +94 -2
  122. package/src/core/default-normalizer.ts +122 -2
  123. package/src/core/descriptor-meta.ts +4 -0
  124. package/src/core/entity-kinds.ts +16 -0
  125. package/src/core/migrations/bound-schema.ts +10 -0
  126. package/src/core/migrations/contract-to-postgres-database-schema-node.ts +125 -0
  127. package/src/core/migrations/control-policy.ts +3 -0
  128. package/src/core/migrations/diff-database-schema.ts +191 -0
  129. package/src/core/migrations/issue-planner.ts +44 -3
  130. package/src/core/migrations/op-factory-call.ts +109 -21
  131. package/src/core/migrations/operations/columns.ts +24 -12
  132. package/src/core/migrations/operations/data-transform.ts +6 -0
  133. package/src/core/migrations/operations/rls.ts +106 -0
  134. package/src/core/migrations/operations/shared.ts +0 -30
  135. package/src/core/migrations/planner-ddl-builders.ts +15 -56
  136. package/src/core/migrations/planner-recipes.ts +31 -13
  137. package/src/core/migrations/planner-strategies.ts +3 -11
  138. package/src/core/migrations/planner-target-details.ts +3 -1
  139. package/src/core/migrations/planner.ts +165 -33
  140. package/src/core/migrations/postgres-migration.ts +34 -4
  141. package/src/core/migrations/render-typescript.ts +42 -15
  142. package/src/core/migrations/resolve-ddl-schema.ts +24 -0
  143. package/src/core/migrations/runner.ts +13 -16
  144. package/src/core/migrations/verify-postgres-namespaces.ts +24 -19
  145. package/src/core/postgres-contract-serializer.ts +50 -33
  146. package/src/core/postgres-contract-view.ts +48 -0
  147. package/src/core/postgres-rls-policy.ts +64 -0
  148. package/src/core/postgres-role.ts +37 -0
  149. package/src/core/postgres-schema.ts +37 -13
  150. package/src/core/postgres-validators.ts +20 -0
  151. package/src/core/psl-infer/infer-psl-contract.ts +834 -0
  152. package/src/core/psl-infer/postgres-default-mapping.ts +16 -0
  153. package/src/core/psl-infer/postgres-type-map.ts +157 -0
  154. package/src/core/rls/canonicalize.ts +48 -0
  155. package/src/core/schema-ir/postgres-database-schema-node.ts +63 -0
  156. package/src/core/schema-ir/postgres-namespace-schema-node.ts +61 -0
  157. package/src/core/schema-ir/postgres-policy-schema-node.ts +93 -0
  158. package/src/core/schema-ir/postgres-role-schema-node.ts +66 -0
  159. package/src/core/schema-ir/postgres-table-schema-node.ts +107 -0
  160. package/src/core/schema-ir/schema-node-kinds.ts +28 -0
  161. package/src/exports/contract-free.ts +7 -1
  162. package/src/exports/control.ts +39 -12
  163. package/src/exports/ddl.ts +4 -0
  164. package/src/exports/migration.ts +1 -0
  165. package/src/exports/planner-ddl-builders.ts +0 -2
  166. package/src/exports/planner.ts +2 -0
  167. package/src/exports/rls-canonicalize.ts +6 -0
  168. package/src/exports/runtime.ts +1 -0
  169. package/src/exports/schema-ir-annotations.ts +1 -0
  170. package/src/exports/types.ts +28 -0
  171. package/dist/codecs--0A5_4Bq.d.mts.map +0 -1
  172. package/dist/ddl-QDyOSeLc.mjs.map +0 -1
  173. package/dist/default-normalizer-DyyCHQWs.mjs.map +0 -1
  174. package/dist/descriptor-meta-CpGygXpI.mjs +0 -140
  175. package/dist/descriptor-meta-CpGygXpI.mjs.map +0 -1
  176. package/dist/issue-planner-DL6g3CmE.mjs.map +0 -1
  177. package/dist/nodes-Bbhs2rwj.mjs.map +0 -1
  178. package/dist/nodes-pLeLgdis.d.mts +0 -67
  179. package/dist/nodes-pLeLgdis.d.mts.map +0 -1
  180. package/dist/op-factory-call-D_p5vxwt.mjs.map +0 -1
  181. package/dist/op-factory-call-DmQEc3XV.d.mts.map +0 -1
  182. package/dist/planner-Bs_baQax.mjs +0 -324
  183. package/dist/planner-Bs_baQax.mjs.map +0 -1
  184. package/dist/planner-ddl-builders-B2wOwLqI.mjs.map +0 -1
  185. package/dist/planner-target-details-CIY6tLeo.d.mts.map +0 -1
  186. package/dist/postgres-contract-serializer-k3TAcPMY.mjs.map +0 -1
  187. package/dist/postgres-migration-B5jKrXv3.mjs.map +0 -1
  188. package/dist/postgres-migration-Y4YBJqkS.d.mts.map +0 -1
  189. package/dist/postgres-schema-COGZ1ark.mjs.map +0 -1
  190. package/dist/render-typescript-KMgosran.mjs.map +0 -1
  191. package/dist/types.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"control.mjs","names":[],"sources":["../src/core/migrations/runner.ts","../src/core/postgres-schema-verifier.ts","../src/exports/control.ts"],"sourcesContent":["import type { Contract, ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n SqlMigrationRunnerSuccessValue,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { MigrationRunnerResult } from '@prisma-next/framework-components/control';\nimport { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlControlDriverInstance, SqlStorage } from '@prisma-next/sql-contract/types';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport type { SqlExecuteRequest } from '@prisma-next/sql-relational-core/ast';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok, okVoid } from '@prisma-next/utils/result';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n}\n\nconst LOCK_DOMAIN = 'prisma_next.contract.marker';\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family);\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(private readonly family: SqlControlFamilyInstance) {}\n\n /**\n * Body of the migration runner without transaction management. The\n * caller ({@link PostgresMigrationRunner.execute}) owns the\n * `BEGIN`/`COMMIT`/`ROLLBACK` lifecycle.\n */\n async executeOnConnection(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema =\n options.schemaName ??\n Object.keys(options.destinationContract.storage.namespaces).find(\n (id) => id !== UNBOUND_NAMESPACE_ID,\n ) ??\n UNBOUND_NAMESPACE_ID;\n const driver = options.driver;\n if (options.space !== undefined && options.space !== options.plan.spaceId) {\n throw new Error(\n `SqlMigrationRunner: options.space (${options.space}) does not match plan.spaceId (${options.plan.spaceId})`,\n );\n }\n const space = options.plan.spaceId;\n const lockKey = `${LOCK_DOMAIN}:${schema}:${space}`;\n\n // Materialize any async ops before running checks or executing.\n const planOps = blindCast<\n readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n 'ops were produced by the PG planner and are SqlMigrationPlanOperation<PostgresPlanTargetDetails>; MigrationPlan.operations uses the wider framework type to accommodate Promise covariance'\n >(await Promise.all(options.plan.operations));\n\n // Static checks (idempotent — safe to run again when the caller is\n // `execute(...)` because the cost is a single object comparison).\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) return destinationCheck;\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, planOps);\n if (!policyCheck.ok) return policyCheck;\n\n await this.acquireLock(driver, lockKey);\n const ensureResult = await this.ensureControlTables(driver, options.destinationContract);\n if (!ensureResult.ok) return ensureResult;\n const existingMarker = await this.family.readMarker({ driver, space });\n\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) return markerCheck;\n\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;\n const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options, planOps);\n if (!applyResult.ok) return applyResult;\n applyValue = applyResult.value;\n }\n\n // Schema verification on app-space only — extension spaces don't\n // own user-facing tables in the live schema, and `verifySqlSchema`\n // matches the destination contract against the database, which\n // would flag every app-space table as \"extra\" when called against\n // an extension contract.\n if (space === APP_SPACE_ID) {\n const schemaIR = await this.family.introspect({\n driver,\n contract: options.destinationContract,\n });\n const schemaVerifyResult = verifySqlSchema({\n contract: options.destinationContract,\n schema: schemaIR,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n typeMetadataRegistry: this.family.typeMetadataRegistry,\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n if (!schemaVerifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: { issues: schemaVerifyResult.schema.issues },\n });\n }\n }\n\n const incomingInvariants = options.plan.providedInvariants ?? [];\n const existingInvariants = new Set(existingMarker?.invariants ?? []);\n const incomingIsSubsetOfExisting = incomingInvariants.every((id) => existingInvariants.has(id));\n const isSelfEdgeNoOp =\n isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting;\n\n if (!isSelfEdgeNoOp) {\n const markerResult = await this.upsertMarker(driver, options, existingMarker, space);\n if (!markerResult.ok) return markerResult;\n await this.recordLedgerEntries(\n driver,\n options,\n applyValue.executedOperations,\n planOps.length,\n );\n }\n\n return runnerSuccess({\n operationsPlanned: planOps.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n }\n\n async execute(options: {\n readonly driver: SqlControlDriverInstance<string>;\n readonly perSpaceOptions: ReadonlyArray<\n SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>\n >;\n }): Promise<MigrationRunnerResult> {\n const driver = options.driver;\n const perSpaceOptions = options.perSpaceOptions;\n\n if (perSpaceOptions.length === 0) {\n return ok({ perSpaceResults: [] });\n }\n\n await this.beginTransaction(driver);\n let committed = false;\n try {\n const perSpaceResults: Array<{\n space: string;\n value: SqlMigrationRunnerSuccessValue;\n }> = [];\n for (const spaceOptions of perSpaceOptions) {\n const space = spaceOptions.space ?? spaceOptions.plan.spaceId;\n const result = await this.executeOnConnection({ ...spaceOptions, driver, space });\n if (!result.ok) {\n return notOk({ ...result.failure, failingSpace: space });\n }\n perSpaceResults.push({ space, value: result.value });\n }\n\n await this.commitTransaction(driver);\n committed = true;\n return ok({ perSpaceResults });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ops: readonly SqlMigrationPlanOperation<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 ops) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n // Idempotency probe: only run if both postchecks and idempotency checks are enabled\n if (runPostchecks && runIdempotency) {\n const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(\n driver,\n operation.postcheck,\n );\n if (postcheckAlreadySatisfied) {\n executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));\n continue;\n }\n }\n\n // Prechecks: only run if enabled\n if (runPrechecks) {\n const precheckResult = await this.runExpectationSteps(\n driver,\n operation.precheck,\n operation,\n 'precheck',\n );\n if (!precheckResult.ok) {\n return precheckResult;\n }\n }\n\n const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);\n if (!executeResult.ok) {\n return executeResult;\n }\n\n // Postchecks: only run if enabled\n if (runPostchecks) {\n const postcheckResult = await this.runExpectationSteps(\n driver,\n operation.postcheck,\n operation,\n 'postcheck',\n );\n if (!postcheckResult.ok) {\n return postcheckResult;\n }\n }\n\n executedOperations.push(operation);\n operationsExecuted += 1;\n } finally {\n options.callbacks?.onOperationComplete?.(operation);\n }\n }\n return ok({ operationsExecuted, executedOperations });\n }\n\n private async ensureControlTables(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n contract: Contract<SqlStorage>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const lowererContext = { contract };\n const bootstrapQueries = this.family.bootstrapControlTableQueries();\n const [schemaQuery, ...tableQueries] = bootstrapQueries;\n if (schemaQuery === undefined) {\n throw new Error('Postgres control-table bootstrap must include CREATE SCHEMA');\n }\n await this.executeStatement(driver, await this.family.lowerAst(schemaQuery, lowererContext));\n const legacyDetection = await this.detectLegacyMarkerShape(driver);\n if (!legacyDetection.ok) {\n return legacyDetection;\n }\n for (const query of tableQueries) {\n await this.executeStatement(driver, await this.family.lowerAst(query, lowererContext));\n }\n return okVoid();\n }\n\n private async detectLegacyMarkerShape(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const result = await driver.query<{ column_name: string }>(\n `select column_name\n from information_schema.columns\n where table_schema = 'prisma_contract'\n and table_name = 'marker'`,\n );\n if (result.rows.length === 0) {\n return okVoid();\n }\n const columns = new Set(result.rows.map((row) => row.column_name));\n if (columns.has('space')) {\n return okVoid();\n }\n return runnerFailure(\n 'LEGACY_MARKER_SHAPE',\n 'Legacy marker-table shape detected on prisma_contract.marker (no `space` column). ' +\n 'Prisma Next is in pre-1.0; the previous transitional auto-migration to the per-space-row schema has been removed. ' +\n 'Drop `prisma_contract.marker` and re-run `dbInit` to reinitialise from a clean baseline.',\n {\n meta: {\n table: 'prisma_contract.marker',\n columns: [...columns].sort(),\n },\n },\n );\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n phase: 'precheck' | 'postcheck',\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n const result = await driver.query(step.sql, step.params ?? []);\n if (!this.stepResultIsTrue(result.rows)) {\n const code = phase === 'precheck' ? 'PRECHECK_FAILED' : 'POSTCHECK_FAILED';\n return runnerFailure(\n code,\n `Operation ${operation.id} failed during ${phase}: ${step.description}`,\n {\n meta: {\n operationId: operation.id,\n phase,\n stepDescription: step.description,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private async runExecuteSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n try {\n await driver.query(step.sql, step.params ?? []);\n } catch (error: unknown) {\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n throw error;\n }\n }\n return okVoid();\n }\n\n private stepResultIsTrue(rows: readonly Record<string, unknown>[]): boolean {\n if (!rows || rows.length === 0) {\n return false;\n }\n const firstRow = rows[0];\n const firstValue = firstRow ? Object.values(firstRow)[0] : undefined;\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n // PostgreSQL boolean representations: 't'/'f', 'true'/'false', '1'/'0'\n if (lower === 't' || lower === 'true' || lower === '1') {\n return true;\n }\n if (lower === 'f' || lower === 'false' || lower === '0') {\n return false;\n }\n // For other strings, non-empty is truthy (though this case shouldn't occur for boolean checks)\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n ): Promise<boolean> {\n if (steps.length === 0) {\n return false;\n }\n for (const step of steps) {\n const result = await driver.query(step.sql, step.params ?? []);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n // Clone and freeze existing meta if present\n const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : undefined;\n\n // Create frozen runner metadata\n const runnerMeta = Object.freeze({\n skipped: true,\n reason: 'postcheck_pre_satisfied',\n });\n\n // Merge and freeze the combined meta\n const mergedMeta = Object.freeze({\n ...(clonedMeta ?? {}),\n runner: runnerMeta,\n });\n\n // Clone and freeze arrays to prevent mutation\n const frozenPostcheck = Object.freeze([...operation.postcheck]);\n\n return Object.freeze({\n id: operation.id,\n label: operation.label,\n ...ifDefined('summary', operation.summary),\n operationClass: operation.operationClass,\n target: operation.target, // Already frozen from plan creation\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: frozenPostcheck,\n ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\n return false;\n }\n if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {\n return false;\n }\n return true;\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${policy.allowedOperationClasses.join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n allowedClasses: policy.allowedOperationClasses,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n // No origin assertion on the plan — the caller does not want origin validation.\n // This is the case for `db update`, which introspects the live schema and does not\n // rely on marker continuity. `db init` handles its own marker checks before the runner.\n return okVoid();\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n {\n meta: {\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (origin.profileHash && marker.profileHash !== origin.profileHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`,\n {\n meta: {\n markerProfileHash: marker.profileHash,\n expectedOriginProfileHash: origin.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private ensurePlanMatchesDestinationContract(\n destination: SqlMigrationPlanContractInfo,\n contract: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['destinationContract'],\n ): Result<void, SqlMigrationRunnerFailure> {\n if (destination.storageHash !== contract.storage.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storage.storageHash,\n },\n },\n );\n }\n if (\n destination.profileHash &&\n contract.profileHash &&\n destination.profileHash !== contract.profileHash\n ) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`,\n {\n meta: {\n planProfileHash: destination.profileHash,\n contractProfileHash: contract.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async upsertMarker(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n space: string,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const destination = {\n storageHash: options.plan.destination.storageHash,\n profileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n invariants: options.plan.providedInvariants ?? [],\n };\n if (!existingMarker) {\n await this.family.initMarker({ driver, space, destination });\n return okVoid();\n }\n const updated = await this.family.updateMarker({\n driver,\n space,\n expectedFrom: existingMarker.storageHash,\n destination,\n });\n if (!updated) {\n return runnerFailure(\n 'MARKER_CAS_FAILURE',\n 'Marker was modified by another process during migration execution.',\n {\n meta: {\n space,\n expectedStorageHash: existingMarker.storageHash,\n destinationStorageHash: options.plan.destination.storageHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async recordLedgerEntries(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n planOpsLength: number,\n ): Promise<void> {\n const plan = options.plan;\n const space = plan.spaceId;\n const edges = options.migrationEdges;\n const totalEdgeOps = edges.reduce((sum, edge) => sum + edge.operationCount, 0);\n if (totalEdgeOps !== planOpsLength) {\n throw new Error(\n `Ledger write: plan.operations length (${planOpsLength}) does not match sum of migrationEdges operationCount (${totalEdgeOps})`,\n );\n }\n // The ledger records the operations as executed — idempotency-skipped ops\n // are substituted with skip records (empty `execute`) by `applyPlan`, so the\n // journal reflects what actually ran rather than the raw plan.\n let offset = 0;\n for (const edge of edges) {\n const edgeOps = executedOperations.slice(offset, offset + edge.operationCount);\n offset += edge.operationCount;\n await this.family.writeLedgerEntry({\n driver,\n space,\n entry: {\n edgeId: `${edge.from}->${edge.to}`,\n from: edge.from,\n to: edge.to,\n migrationName: edge.dirName,\n migrationHash: edge.migrationHash,\n operations: edgeOps,\n },\n });\n }\n }\n\n private async acquireLock(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n key: string,\n ): Promise<void> {\n await driver.query('select pg_advisory_xact_lock(hashtext($1))', [key]);\n }\n\n private async beginTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n statement: SqlExecuteRequest,\n ): Promise<void> {\n await driver.query(statement.sql, statement.params);\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { SqlSchemaVerifierBase } from '@prisma-next/family-sql/ir';\nimport type { SchemaIssue, SchemaVerifyOptions } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\n\n/**\n * Postgres target `SchemaVerifier` concretion. Plugs into the\n * SQL-shared verification surface; production verification today still\n * routes through the legacy `verifySqlSchema` entry point, which\n * carries options (codec hooks, normalizers, framework components)\n * that the framework-level `SchemaVerifyOptions` shape does not yet\n * surface.\n *\n * The hooks return the empty list pending the call-site migration that\n * routes the existing verifier behaviour through the SPI — at that\n * point `verifyCommonSqlSchema` will likely lift onto the family base\n * (mirroring `verifyCommonMongoSchema`) and `verifyTargetExtensions`\n * will house Postgres-only kinds (functions, RLS policies in a future\n * project).\n */\nexport class PostgresSchemaVerifier extends SqlSchemaVerifierBase<\n Contract<SqlStorage>,\n SqlSchemaIR\n> {\n protected verifyCommonSqlSchema(\n _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\n }\n\n protected verifyTargetExtensions(\n _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\n }\n}\n","import type { ColumnDefault, Contract } from '@prisma-next/contract/types';\nimport type { SqlControlTargetDescriptor } from '@prisma-next/family-sql/control';\nimport { contractToSchemaIR, extractCodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlTargetInstance,\n MigrationRunner,\n} from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\nimport { PostgresContractSerializer } from '../core/postgres-contract-serializer';\nimport { PostgresSchemaVerifier } from '../core/postgres-schema-verifier';\n\nfunction buildNativeTypeExpander(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n if (!frameworkComponents) {\n return undefined;\n }\n const codecHooks = extractCodecControlHooks(frameworkComponents);\n return (input: {\n readonly nativeType: string;\n readonly codecId?: string;\n readonly typeParams?: Record<string, unknown>;\n }) => {\n if (!input.typeParams) return input.nativeType;\n if (!input.codecId) return input.nativeType;\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) return input.nativeType;\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n contractSerializer: new PostgresContractSerializer(),\n schemaVerifier: new PostgresSchemaVerifier(),\n migrations: {\n createPlanner(adapter: SqlControlAdapter<'postgres'>) {\n return createPostgresMigrationPlanner(adapter);\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n // Blind cast: the framework SPI signature\n // (`control-migration-types.ts § contractToSchema`) types\n // `contract` as the generic `Contract | null`. Inside the\n // postgres target descriptor we know any contract reaching\n // this method is SQL-family — the family contract resolver\n // would have refused to construct a postgres target binding\n // otherwise — so we narrow the generic to\n // `Contract<SqlStorage>` for the lowering call.\n return contractToSchemaIR(contract as unknown as Contract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(adapter: SqlControlAdapter<'postgres'>) {\n return createPostgresMigrationPlanner(adapter);\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;;;;AAkCA,MAAM,cAAc;;;;;AAMpB,SAAS,qBAAwD,OAAa;CAC5E,MAAM,SAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,KAAK,GAC3C,IAAI,QAAQ,QAAQ,QA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Q;GACnB,OAAO,8BAA8B,MAAM;EAC7C;EACA,iBAAiB,UAAU,qBAAqB;GAU9C,OAAO,mBAAmB,UAAoD;IAC5E,qBAAqB;IACrB,GAAG,UAAU,oBAXE,wBAAwB,mBAWC,CAAC;IACzC,eAAe;GACjB,CAAC;EACH;CACF;CACA,SAAmD;EACjD,OAAO;GACL,UAAU;GACV,UAAU;EACZ;CACF;;;;;CAKA,cAAc,SAAwC;EACpD,OAAO,+BAA+B,OAAO;CAC/C;;;;;CAKA,aAAa,QAAQ;EACnB,OAAO,8BAA8B,MAAM;CAC7C;AACF"}
1
+ {"version":3,"file":"control.mjs","names":[],"sources":["../src/core/migrations/runner.ts","../src/core/postgres-schema-verifier.ts","../src/core/psl-infer/postgres-default-mapping.ts","../src/core/psl-infer/postgres-type-map.ts","../src/core/psl-infer/infer-psl-contract.ts","../src/exports/control.ts"],"sourcesContent":["import type { Contract, ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n SqlMigrationRunnerSuccessValue,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport type { MigrationRunnerResult } from '@prisma-next/framework-components/control';\nimport { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlControlDriverInstance, SqlStorage } from '@prisma-next/sql-contract/types';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport type { SqlExecuteRequest } from '@prisma-next/sql-relational-core/ast';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok, okVoid } from '@prisma-next/utils/result';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n}\n\nconst LOCK_DOMAIN = 'prisma_next.contract.marker';\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family);\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(private readonly family: SqlControlFamilyInstance) {}\n\n /**\n * Body of the migration runner without transaction management. The\n * caller ({@link PostgresMigrationRunner.execute}) owns the\n * `BEGIN`/`COMMIT`/`ROLLBACK` lifecycle.\n */\n async executeOnConnection(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema =\n options.schemaName ??\n Object.keys(options.destinationContract.storage.namespaces).find(\n (id) => id !== UNBOUND_NAMESPACE_ID,\n ) ??\n UNBOUND_NAMESPACE_ID;\n const driver = options.driver;\n if (options.space !== undefined && options.space !== options.plan.spaceId) {\n throw new Error(\n `SqlMigrationRunner: options.space (${options.space}) does not match plan.spaceId (${options.plan.spaceId})`,\n );\n }\n const space = options.plan.spaceId;\n const lockKey = `${LOCK_DOMAIN}:${schema}:${space}`;\n\n // Materialize any async ops before running checks or executing.\n const planOps = blindCast<\n readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n 'ops were produced by the PG planner and are SqlMigrationPlanOperation<PostgresPlanTargetDetails>; MigrationPlan.operations uses the wider framework type to accommodate Promise covariance'\n >(await Promise.all(options.plan.operations));\n\n // Static checks (idempotent — safe to run again when the caller is\n // `execute(...)` because the cost is a single object comparison).\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) return destinationCheck;\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, planOps);\n if (!policyCheck.ok) return policyCheck;\n\n await this.acquireLock(driver, lockKey);\n const ensureResult = await this.ensureControlTables(driver, options.destinationContract);\n if (!ensureResult.ok) return ensureResult;\n const existingMarker = await this.family.readMarker({ driver, space });\n\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) return markerCheck;\n\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;\n const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options, planOps);\n if (!applyResult.ok) return applyResult;\n applyValue = applyResult.value;\n }\n\n // Verify the schema on app-space only: extension spaces don't own\n // user-facing tables, so verifying the destination contract against the\n // database would flag every app-space table as \"extra\". Delegates to the\n // family `verifySchema` — the same comparison the CLI verify runs.\n if (space === APP_SPACE_ID) {\n const schemaNode = await this.family.introspect({\n driver,\n contract: options.destinationContract,\n });\n const schemaVerifyResult = this.family.verifySchema({\n contract: options.destinationContract,\n schema: schemaNode,\n strict: options.strictVerification ?? true,\n frameworkComponents: options.frameworkComponents,\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: [\n ...schemaVerifyResult.schema.issues,\n ...schemaVerifyResult.schema.schemaDiffIssues,\n ],\n },\n });\n }\n }\n\n const incomingInvariants = options.plan.providedInvariants ?? [];\n const existingInvariants = new Set(existingMarker?.invariants ?? []);\n const incomingIsSubsetOfExisting = incomingInvariants.every((id) => existingInvariants.has(id));\n const isSelfEdgeNoOp =\n isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting;\n\n if (!isSelfEdgeNoOp) {\n const markerResult = await this.upsertMarker(driver, options, existingMarker, space);\n if (!markerResult.ok) return markerResult;\n await this.recordLedgerEntries(\n driver,\n options,\n applyValue.executedOperations,\n planOps.length,\n );\n }\n\n return runnerSuccess({\n operationsPlanned: planOps.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n }\n\n async execute(options: {\n readonly driver: SqlControlDriverInstance<string>;\n readonly perSpaceOptions: ReadonlyArray<\n SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>\n >;\n }): Promise<MigrationRunnerResult> {\n const driver = options.driver;\n const perSpaceOptions = options.perSpaceOptions;\n\n if (perSpaceOptions.length === 0) {\n return ok({ perSpaceResults: [] });\n }\n\n await this.beginTransaction(driver);\n let committed = false;\n try {\n const perSpaceResults: Array<{\n space: string;\n value: SqlMigrationRunnerSuccessValue;\n }> = [];\n for (const spaceOptions of perSpaceOptions) {\n const space = spaceOptions.space ?? spaceOptions.plan.spaceId;\n const result = await this.executeOnConnection({ ...spaceOptions, driver, space });\n if (!result.ok) {\n return notOk({ ...result.failure, failingSpace: space });\n }\n perSpaceResults.push({ space, value: result.value });\n }\n\n await this.commitTransaction(driver);\n committed = true;\n return ok({ perSpaceResults });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ops: readonly SqlMigrationPlanOperation<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 ops) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n // Idempotency probe: only run if both postchecks and idempotency checks are enabled\n if (runPostchecks && runIdempotency) {\n const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(\n driver,\n operation.postcheck,\n );\n if (postcheckAlreadySatisfied) {\n executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));\n continue;\n }\n }\n\n // Prechecks: only run if enabled\n if (runPrechecks) {\n const precheckResult = await this.runExpectationSteps(\n driver,\n operation.precheck,\n operation,\n 'precheck',\n );\n if (!precheckResult.ok) {\n return precheckResult;\n }\n }\n\n const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);\n if (!executeResult.ok) {\n return executeResult;\n }\n\n // Postchecks: only run if enabled\n if (runPostchecks) {\n const postcheckResult = await this.runExpectationSteps(\n driver,\n operation.postcheck,\n operation,\n 'postcheck',\n );\n if (!postcheckResult.ok) {\n return postcheckResult;\n }\n }\n\n executedOperations.push(operation);\n operationsExecuted += 1;\n } finally {\n options.callbacks?.onOperationComplete?.(operation);\n }\n }\n return ok({ operationsExecuted, executedOperations });\n }\n\n private async ensureControlTables(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n contract: Contract<SqlStorage>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const lowererContext = { contract };\n const bootstrapQueries = this.family.bootstrapControlTableQueries();\n const [schemaQuery, ...tableQueries] = bootstrapQueries;\n if (schemaQuery === undefined) {\n throw new Error('Postgres control-table bootstrap must include CREATE SCHEMA');\n }\n await this.executeStatement(driver, await this.family.lowerAst(schemaQuery, lowererContext));\n const legacyDetection = await this.detectLegacyMarkerShape(driver);\n if (!legacyDetection.ok) {\n return legacyDetection;\n }\n for (const query of tableQueries) {\n await this.executeStatement(driver, await this.family.lowerAst(query, lowererContext));\n }\n return okVoid();\n }\n\n private async detectLegacyMarkerShape(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const result = await driver.query<{ column_name: string }>(\n `select column_name\n from information_schema.columns\n where table_schema = 'prisma_contract'\n and table_name = 'marker'`,\n );\n if (result.rows.length === 0) {\n return okVoid();\n }\n const columns = new Set(result.rows.map((row) => row.column_name));\n if (columns.has('space')) {\n return okVoid();\n }\n return runnerFailure(\n 'LEGACY_MARKER_SHAPE',\n 'Legacy marker-table shape detected on prisma_contract.marker (no `space` column). ' +\n 'Prisma Next is in pre-1.0; the previous transitional auto-migration to the per-space-row schema has been removed. ' +\n 'Drop `prisma_contract.marker` and re-run `dbInit` to reinitialise from a clean baseline.',\n {\n meta: {\n table: 'prisma_contract.marker',\n columns: [...columns].sort(),\n },\n },\n );\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n phase: 'precheck' | 'postcheck',\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n const result = await driver.query(step.sql, step.params ?? []);\n if (!this.stepResultIsTrue(result.rows)) {\n const code = phase === 'precheck' ? 'PRECHECK_FAILED' : 'POSTCHECK_FAILED';\n return runnerFailure(\n code,\n `Operation ${operation.id} failed during ${phase}: ${step.description}`,\n {\n meta: {\n operationId: operation.id,\n phase,\n stepDescription: step.description,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private async runExecuteSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n try {\n await driver.query(step.sql, step.params ?? []);\n } catch (error: unknown) {\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n throw error;\n }\n }\n return okVoid();\n }\n\n private stepResultIsTrue(rows: readonly Record<string, unknown>[]): boolean {\n if (!rows || rows.length === 0) {\n return false;\n }\n const firstRow = rows[0];\n const firstValue = firstRow ? Object.values(firstRow)[0] : undefined;\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n // PostgreSQL boolean representations: 't'/'f', 'true'/'false', '1'/'0'\n if (lower === 't' || lower === 'true' || lower === '1') {\n return true;\n }\n if (lower === 'f' || lower === 'false' || lower === '0') {\n return false;\n }\n // For other strings, non-empty is truthy (though this case shouldn't occur for boolean checks)\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n ): Promise<boolean> {\n if (steps.length === 0) {\n return false;\n }\n for (const step of steps) {\n const result = await driver.query(step.sql, step.params ?? []);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n // Clone and freeze existing meta if present\n const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : undefined;\n\n // Create frozen runner metadata\n const runnerMeta = Object.freeze({\n skipped: true,\n reason: 'postcheck_pre_satisfied',\n });\n\n // Merge and freeze the combined meta\n const mergedMeta = Object.freeze({\n ...(clonedMeta ?? {}),\n runner: runnerMeta,\n });\n\n // Clone and freeze arrays to prevent mutation\n const frozenPostcheck = Object.freeze([...operation.postcheck]);\n\n return Object.freeze({\n id: operation.id,\n label: operation.label,\n ...ifDefined('summary', operation.summary),\n operationClass: operation.operationClass,\n target: operation.target, // Already frozen from plan creation\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: frozenPostcheck,\n ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\n return false;\n }\n if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {\n return false;\n }\n return true;\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${policy.allowedOperationClasses.join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n allowedClasses: policy.allowedOperationClasses,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n // No origin assertion on the plan — the caller does not want origin validation.\n // This is the case for `db update`, which introspects the live schema and does not\n // rely on marker continuity. `db init` handles its own marker checks before the runner.\n return okVoid();\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n {\n meta: {\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (origin.profileHash && marker.profileHash !== origin.profileHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`,\n {\n meta: {\n markerProfileHash: marker.profileHash,\n expectedOriginProfileHash: origin.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private ensurePlanMatchesDestinationContract(\n destination: SqlMigrationPlanContractInfo,\n contract: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['destinationContract'],\n ): Result<void, SqlMigrationRunnerFailure> {\n if (destination.storageHash !== contract.storage.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storage.storageHash,\n },\n },\n );\n }\n if (\n destination.profileHash &&\n contract.profileHash &&\n destination.profileHash !== contract.profileHash\n ) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`,\n {\n meta: {\n planProfileHash: destination.profileHash,\n contractProfileHash: contract.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async upsertMarker(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n space: string,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const destination = {\n storageHash: options.plan.destination.storageHash,\n profileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n invariants: options.plan.providedInvariants ?? [],\n };\n if (!existingMarker) {\n await this.family.initMarker({ driver, space, destination });\n return okVoid();\n }\n const updated = await this.family.updateMarker({\n driver,\n space,\n expectedFrom: existingMarker.storageHash,\n destination,\n });\n if (!updated) {\n return runnerFailure(\n 'MARKER_CAS_FAILURE',\n 'Marker was modified by another process during migration execution.',\n {\n meta: {\n space,\n expectedStorageHash: existingMarker.storageHash,\n destinationStorageHash: options.plan.destination.storageHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async recordLedgerEntries(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n planOpsLength: number,\n ): Promise<void> {\n const plan = options.plan;\n const space = plan.spaceId;\n const edges = options.migrationEdges;\n const totalEdgeOps = edges.reduce((sum, edge) => sum + edge.operationCount, 0);\n if (totalEdgeOps !== planOpsLength) {\n throw new Error(\n `Ledger write: plan.operations length (${planOpsLength}) does not match sum of migrationEdges operationCount (${totalEdgeOps})`,\n );\n }\n // The ledger records the operations as executed — idempotency-skipped ops\n // are substituted with skip records (empty `execute`) by `applyPlan`, so the\n // journal reflects what actually ran rather than the raw plan.\n let offset = 0;\n for (const edge of edges) {\n const edgeOps = executedOperations.slice(offset, offset + edge.operationCount);\n offset += edge.operationCount;\n await this.family.writeLedgerEntry({\n driver,\n space,\n entry: {\n edgeId: `${edge.from}->${edge.to}`,\n from: edge.from,\n to: edge.to,\n migrationName: edge.dirName,\n migrationHash: edge.migrationHash,\n operations: edgeOps,\n },\n });\n }\n }\n\n private async acquireLock(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n key: string,\n ): Promise<void> {\n await driver.query('select pg_advisory_xact_lock(hashtext($1))', [key]);\n }\n\n private async beginTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n statement: SqlExecuteRequest,\n ): Promise<void> {\n await driver.query(statement.sql, statement.params);\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { SqlSchemaVerifierBase } from '@prisma-next/family-sql/ir';\nimport type { SchemaIssue, SchemaVerifyOptions } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\n\n/**\n * Postgres target `SchemaVerifier` concretion. Plugs into the\n * SQL-shared verification surface; production verification today still\n * routes through the legacy `verifySqlSchema` entry point, which\n * carries options (codec hooks, normalizers, framework components)\n * that the framework-level `SchemaVerifyOptions` shape does not yet\n * surface.\n *\n * The hooks return the empty list pending the call-site migration that\n * routes the existing verifier behaviour through the SPI — at that\n * point `verifyCommonSqlSchema` will likely lift onto the family base\n * (mirroring `verifyCommonMongoSchema`) and `verifyTargetExtensions`\n * will house Postgres-only kinds (functions, RLS policies in a future\n * project).\n */\nexport class PostgresSchemaVerifier extends SqlSchemaVerifierBase<\n Contract<SqlStorage>,\n SqlSchemaIR\n> {\n protected verifyCommonSqlSchema(\n _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\n }\n\n protected verifyTargetExtensions(\n _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\n }\n}\n","import type { DefaultMappingOptions } from '@prisma-next/family-sql/psl-infer';\n\nconst POSTGRES_FUNCTION_ATTRIBUTES: Readonly<Record<string, string>> = {\n 'gen_random_uuid()': '@default(dbgenerated(\"gen_random_uuid()\"))',\n};\n\nfunction formatDbGeneratedAttribute(expression: string): string {\n return `@default(dbgenerated(${JSON.stringify(expression)}))`;\n}\n\nexport function createPostgresDefaultMapping(): DefaultMappingOptions {\n return {\n functionAttributes: POSTGRES_FUNCTION_ATTRIBUTES,\n fallbackFunctionAttribute: formatDbGeneratedAttribute,\n };\n}\n","import type {\n EnumInfo,\n PslNativeTypeAttribute,\n PslTypeMap,\n PslTypeResolution,\n} from '@prisma-next/family-sql/psl-infer';\n\nconst POSTGRES_TO_PSL: Record<string, string> = {\n text: 'String',\n bool: 'Boolean',\n boolean: 'Boolean',\n int4: 'Int',\n integer: 'Int',\n int8: 'BigInt',\n bigint: 'BigInt',\n float8: 'Float',\n 'double precision': 'Float',\n numeric: 'Decimal',\n decimal: 'Decimal',\n timestamptz: 'DateTime',\n 'timestamp with time zone': 'DateTime',\n jsonb: 'Json',\n bytea: 'Bytes',\n};\n\nconst PRESERVED_NATIVE_TYPES: Record<\n string,\n { readonly pslType: string; readonly attributeName: string }\n> = {\n 'character varying': { pslType: 'String', attributeName: 'db.VarChar' },\n character: { pslType: 'String', attributeName: 'db.Char' },\n char: { pslType: 'String', attributeName: 'db.Char' },\n varchar: { pslType: 'String', attributeName: 'db.VarChar' },\n uuid: { pslType: 'String', attributeName: 'db.Uuid' },\n int2: { pslType: 'Int', attributeName: 'db.SmallInt' },\n smallint: { pslType: 'Int', attributeName: 'db.SmallInt' },\n float4: { pslType: 'Float', attributeName: 'db.Real' },\n real: { pslType: 'Float', attributeName: 'db.Real' },\n timestamp: { pslType: 'DateTime', attributeName: 'db.Timestamp' },\n 'timestamp without time zone': { pslType: 'DateTime', attributeName: 'db.Timestamp' },\n date: { pslType: 'DateTime', attributeName: 'db.Date' },\n time: { pslType: 'DateTime', attributeName: 'db.Time' },\n 'time without time zone': { pslType: 'DateTime', attributeName: 'db.Time' },\n timetz: { pslType: 'DateTime', attributeName: 'db.Timetz' },\n 'time with time zone': { pslType: 'DateTime', attributeName: 'db.Timetz' },\n json: { pslType: 'Json', attributeName: 'db.Json' },\n};\n\nconst PARAMETERIZED_NATIVE_TYPES: Record<\n string,\n { readonly pslType: string; readonly attributeName: string }\n> = {\n 'character varying': { pslType: 'String', attributeName: 'db.VarChar' },\n character: { pslType: 'String', attributeName: 'db.Char' },\n char: { pslType: 'String', attributeName: 'db.Char' },\n varchar: { pslType: 'String', attributeName: 'db.VarChar' },\n numeric: { pslType: 'Decimal', attributeName: 'db.Numeric' },\n timestamp: { pslType: 'DateTime', attributeName: 'db.Timestamp' },\n timestamptz: { pslType: 'DateTime', attributeName: 'db.Timestamptz' },\n time: { pslType: 'DateTime', attributeName: 'db.Time' },\n timetz: { pslType: 'DateTime', attributeName: 'db.Timetz' },\n};\n\nconst PARAMETERIZED_TYPE_PATTERN = /^(.+?)\\((.+)\\)$/;\n\nfunction getOwnMappingValue(map: Record<string, string>, key: string): string | undefined {\n return Object.hasOwn(map, key) ? map[key] : undefined;\n}\n\nfunction getOwnRecordValue<T>(map: Record<string, T>, key: string): T | undefined {\n return Object.hasOwn(map, key) ? map[key] : undefined;\n}\n\nfunction createNativeTypeAttribute(name: string, args?: readonly string[]): PslNativeTypeAttribute {\n return args && args.length > 0 ? { name, args } : { name };\n}\n\nfunction splitTypeParameterList(params: string): readonly string[] {\n return params\n .split(',')\n .map((part) => part.trim())\n .filter((part) => part.length > 0);\n}\n\nexport function createPostgresTypeMap(enumTypeNames?: ReadonlySet<string>): PslTypeMap {\n return {\n resolve(nativeType: string): PslTypeResolution {\n if (enumTypeNames?.has(nativeType)) {\n return { pslType: nativeType, nativeType };\n }\n\n const paramMatch = nativeType.match(PARAMETERIZED_TYPE_PATTERN);\n if (paramMatch) {\n const [, baseType = nativeType, params = ''] = paramMatch;\n const template = getOwnRecordValue(PARAMETERIZED_NATIVE_TYPES, baseType);\n if (template) {\n return {\n pslType: template.pslType,\n nativeType,\n typeParams: { baseType, params },\n nativeTypeAttribute: createNativeTypeAttribute(\n template.attributeName,\n splitTypeParameterList(params),\n ),\n };\n }\n }\n\n const preservedType = getOwnRecordValue(PRESERVED_NATIVE_TYPES, nativeType);\n if (preservedType) {\n return {\n pslType: preservedType.pslType,\n nativeType,\n nativeTypeAttribute: createNativeTypeAttribute(preservedType.attributeName),\n };\n }\n\n const pslType = getOwnMappingValue(POSTGRES_TO_PSL, nativeType);\n if (pslType) {\n return {\n pslType,\n nativeType,\n };\n }\n\n return { unsupported: true, nativeType };\n },\n };\n}\n\nexport function extractEnumInfo(annotations?: Record<string, unknown>): EnumInfo {\n const pgAnnotations = annotations?.['pg'] as Record<string, unknown> | undefined;\n const nativeEnumTypeNames = pgAnnotations?.['nativeEnumTypeNames'];\n\n const typeNames = new Set<string>();\n const definitions = new Map<string, readonly string[]>();\n\n if (Array.isArray(nativeEnumTypeNames)) {\n for (const name of nativeEnumTypeNames) {\n if (typeof name === 'string') {\n typeNames.add(name);\n }\n }\n }\n\n return { typeNames, definitions };\n}\n\nexport function extractEnumTypeNames(annotations?: Record<string, unknown>): ReadonlySet<string> {\n return extractEnumInfo(annotations).typeNames;\n}\n\nexport function extractEnumDefinitions(\n annotations?: Record<string, unknown>,\n): ReadonlyMap<string, readonly string[]> {\n return extractEnumInfo(annotations).definitions;\n}\n","import type { ColumnDefault } from '@prisma-next/contract/types';\nimport type {\n DefaultMappingOptions,\n PslNativeTypeAttribute,\n PslPrinterOptions,\n PslTypeMap,\n RelationField,\n} from '@prisma-next/family-sql/psl-infer';\nimport {\n inferRelations,\n mapDefault,\n parseRawDefault,\n toFieldName,\n toModelName,\n toNamedTypeName,\n} from '@prisma-next/family-sql/psl-infer';\nimport type {\n PslAttribute,\n PslAttributeArgument,\n PslDocumentAst,\n PslField,\n PslFieldAttribute,\n PslModel,\n PslModelAttribute,\n PslNamedTypeDeclaration,\n PslSpan,\n PslTypesBlock,\n} from '@prisma-next/framework-components/psl-ast';\nimport {\n makePslNamespace,\n makePslNamespaceEntries,\n UNSPECIFIED_PSL_NAMESPACE_ID,\n} from '@prisma-next/framework-components/psl-ast';\nimport type { SqlColumnIR, SqlSchemaIR, SqlTableIR } from '@prisma-next/sql-schema-ir/types';\nimport type { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { createPostgresDefaultMapping } from './postgres-default-mapping';\nimport { createPostgresTypeMap } from './postgres-type-map';\n\nconst SYNTHETIC_SPAN: PslSpan = {\n start: { offset: 0, line: 1, column: 1 },\n end: { offset: 0, line: 1, column: 1 },\n};\n\nconst PSL_SCALAR_TYPE_NAMES = new Set([\n 'String',\n 'Boolean',\n 'Int',\n 'BigInt',\n 'Float',\n 'Decimal',\n 'DateTime',\n 'Json',\n 'Bytes',\n]);\n\ntype ResolvedColumnFieldName = {\n readonly fieldName: string;\n readonly fieldMap?: string | undefined;\n};\n\ntype TableColumnFieldNameMap = ReadonlyMap<string, ResolvedColumnFieldName>;\n\ntype NamedTypeRegistryEntry = {\n readonly name: string;\n readonly baseType: string;\n readonly nativeTypeAttribute: PslNativeTypeAttribute;\n};\n\ntype NamedTypeRegistry = {\n readonly entriesByKey: Map<string, NamedTypeRegistryEntry>;\n readonly usedNames: Set<string>;\n};\n\ntype TopLevelNameResult = {\n readonly name: string;\n readonly map?: string | undefined;\n};\n\n/**\n * Infers a PSL AST (for `printPsl`) from an introspected Postgres schema tree.\n *\n * Target-owned inference: it walks the `PostgresDatabaseSchemaNode` tree and\n * owns the Postgres dialect knowledge — the native type map and default map.\n * Relation inference, name transforms, generic default mapping, and raw-default\n * parsing are shape-neutral utilities imported from the SQL family.\n *\n * This slice emits relational-only PSL, byte-identical to the prior flat\n * inference: the tree's tables (across its namespaces — `contract infer`\n * introspects a single live namespace) are gathered into the model set and\n * emitted as one `UNSPECIFIED_PSL_NAMESPACE_ID` bucket. Top-level entities\n * (policies/roles → PSL extension blocks) are a later slice.\n */\nexport function inferPostgresPslContract(tree: PostgresDatabaseSchemaNode): PslDocumentAst {\n const namespaces = Object.values(tree.namespaces);\n\n // Native Postgres enums (CREATE TYPE … AS ENUM) are not adoptable by\n // `contract infer`; throw an actionable diagnostic naming the type(s). Enum\n // names live on each namespace node's `nativeEnumTypeNames`.\n const enumTypeNames = [...new Set(namespaces.flatMap((ns) => ns.nativeEnumTypeNames))];\n if (enumTypeNames.length > 0) {\n const names = enumTypeNames.join(', ');\n throw new Error(\n `contract infer: the database contains native Postgres enum type(s): ${names}. ` +\n 'Native Postgres enums (CREATE TYPE … AS ENUM) are not adoptable by contract infer. ' +\n 'Drop the native type and replace each column with a text column carrying a CHECK constraint, ' +\n `then re-run contract infer. The domain enum (enum Name { @@type(\"pg/text@1\") … }) authoring ` +\n 'surface generates the required check automatically.',\n );\n }\n\n // Stopgap (TML-2958): flatten the schema-IR *tree* into the single `{ tables }`\n // map the PSL writer expects. The writer still walks a flat table map, so this\n // is a read-only projection — it does not reintroduce a stored flat schema.\n // The real fix is to extend the PSL writer to walk the namespace tree and emit\n // per-namespace `namespace { … }` blocks; until then `contract infer` handles a\n // single introspected namespace, and a same-named table in two schemas has no\n // unambiguous single-bucket model, so we throw rather than silently drop one.\n const tables: Record<string, SqlTableIR> = {};\n for (const namespace of namespaces) {\n for (const [tableName, table] of Object.entries(namespace.tables)) {\n if (tables[tableName] !== undefined) {\n throw new Error(\n `contract infer: duplicate table name \"${tableName}\" across schemas is not yet supported ` +\n '(single-namespace PSL inference emits one flat bucket; multi-namespace `namespace { … }` ' +\n 'output is a later slice).',\n );\n }\n tables[tableName] = table;\n }\n }\n const schemaIR: SqlSchemaIR = { tables };\n\n const options: PslPrinterOptions = {\n typeMap: createPostgresTypeMap(new Set()),\n defaultMapping: createPostgresDefaultMapping(),\n parseRawDefault,\n };\n\n return buildPslDocumentAst(schemaIR, options);\n}\n\nfunction buildPslDocumentAst(schemaIR: SqlSchemaIR, options: PslPrinterOptions): PslDocumentAst {\n const { typeMap, defaultMapping, parseRawDefault: rawDefaultParser } = options;\n\n const modelNames = buildTopLevelNameMap(\n Object.keys(schemaIR.tables),\n toModelName,\n 'model',\n 'table',\n );\n\n const modelNameMap = new Map(\n [...modelNames].map(([tableName, result]) => [tableName, result.name]),\n );\n const reservedNamedTypeNames = createReservedNamedTypeNames(modelNames);\n\n const fieldNamesByTable = buildFieldNamesByTable(schemaIR.tables);\n const { relationsByTable } = inferRelations(schemaIR.tables, modelNameMap);\n const namedTypes = seedNamedTypeRegistry(schemaIR, typeMap, new Map(), reservedNamedTypeNames);\n\n const models: PslModel[] = [];\n for (const table of Object.values(schemaIR.tables)) {\n models.push(\n buildModel(\n table,\n typeMap,\n new Map(),\n fieldNamesByTable,\n namedTypes,\n defaultMapping,\n rawDefaultParser,\n relationsByTable.get(table.name) ?? [],\n ),\n );\n }\n\n const sortedModels = topologicalSort(models, schemaIR.tables, modelNameMap);\n\n const namedTypeEntries = [...namedTypes.entriesByKey.values()].sort((a, b) =>\n a.name.localeCompare(b.name),\n );\n const types: PslTypesBlock | undefined =\n namedTypeEntries.length > 0\n ? {\n kind: 'types',\n declarations: namedTypeEntries.map(buildNamedTypeDeclaration),\n span: SYNTHETIC_SPAN,\n }\n : undefined;\n\n // Inferred PSL nodes will eventually be routed into per-namespace buckets\n // matching the source storage; for now we synthesise a single\n // `__unspecified__` bucket so round-tripping the AST through the framework\n // printer (which emits the synthesised bucket at top level with no\n // `namespace { … }` wrapper) preserves the existing introspection output\n // verbatim.\n const ast: PslDocumentAst = {\n kind: 'document',\n sourceId: '<sql-schema-ir>',\n namespaces: [\n makePslNamespace({\n kind: 'namespace',\n name: UNSPECIFIED_PSL_NAMESPACE_ID,\n entries: makePslNamespaceEntries(sortedModels, [], []),\n span: SYNTHETIC_SPAN,\n }),\n ],\n ...(types ? { types } : {}),\n span: SYNTHETIC_SPAN,\n };\n\n return ast;\n}\n\nfunction buildModel(\n table: SqlTableIR,\n typeMap: PslTypeMap,\n enumNameMap: ReadonlyMap<string, string>,\n fieldNamesByTable: ReadonlyMap<string, TableColumnFieldNameMap>,\n namedTypes: NamedTypeRegistry,\n defaultMapping: DefaultMappingOptions | undefined,\n rawDefaultParser: PslPrinterOptions['parseRawDefault'],\n relationFields: readonly RelationField[],\n): PslModel {\n const { name: modelName, map: mapName } = toModelName(table.name);\n const fieldNameMap = fieldNamesByTable.get(table.name);\n\n const pkColumns = new Set(table.primaryKey?.columns ?? []);\n const isSinglePk = pkColumns.size === 1;\n const singlePkConstraintName = isSinglePk ? table.primaryKey?.name : undefined;\n\n const uniqueColumns = new Map<string, string | undefined>();\n for (const unique of table.uniques) {\n if (unique.columns.length === 1) {\n const [columnName = ''] = unique.columns;\n const existingConstraintName = uniqueColumns.get(columnName);\n if (!uniqueColumns.has(columnName) || (existingConstraintName === undefined && unique.name)) {\n uniqueColumns.set(columnName, unique.name);\n }\n }\n }\n\n const fields: PslField[] = [];\n for (const column of Object.values(table.columns)) {\n fields.push(\n buildScalarField(\n column,\n table,\n typeMap,\n enumNameMap,\n fieldNameMap,\n namedTypes,\n defaultMapping,\n rawDefaultParser,\n pkColumns,\n isSinglePk,\n singlePkConstraintName,\n uniqueColumns,\n ),\n );\n }\n\n const usedFieldNames = new Set(fields.map((field) => field.name));\n for (const rel of relationFields) {\n fields.push(buildRelationField(rel, table.name, fieldNamesByTable, usedFieldNames));\n }\n\n const modelAttributes: PslModelAttribute[] = [];\n\n if (table.primaryKey && table.primaryKey.columns.length > 1) {\n const pkFieldNames = table.primaryKey.columns.map((columnName) =>\n resolveColumnFieldName(fieldNamesByTable, table.name, columnName),\n );\n modelAttributes.push(buildModelConstraintAttribute('id', pkFieldNames, table.primaryKey.name));\n }\n\n for (const unique of table.uniques) {\n if (unique.columns.length > 1) {\n const uniqueFieldNames = unique.columns.map((columnName) =>\n resolveColumnFieldName(fieldNamesByTable, table.name, columnName),\n );\n modelAttributes.push(buildModelConstraintAttribute('unique', uniqueFieldNames, unique.name));\n }\n }\n\n for (const index of table.indexes) {\n if (!index.unique) {\n const indexFieldNames = index.columns.map((columnName) =>\n resolveColumnFieldName(fieldNamesByTable, table.name, columnName),\n );\n modelAttributes.push(buildModelConstraintAttribute('index', indexFieldNames, index.name));\n }\n }\n\n if (mapName) {\n modelAttributes.push(buildMapAttribute('model', mapName));\n }\n\n // Surface introspection advisory: tables without a primary key cannot serve\n // as the right-hand side of a `findUnique`-style query downstream, so the\n // user should add an `@id`. This warning is part of the emitted SQL output\n // and is asserted byte-for-byte, so keep the exact wording.\n const comment = table.primaryKey\n ? undefined\n : '// WARNING: This table has no primary key in the database';\n\n return {\n kind: 'model',\n name: modelName,\n fields,\n attributes: modelAttributes,\n span: SYNTHETIC_SPAN,\n ...(comment !== undefined ? { comment } : {}),\n };\n}\n\nfunction buildScalarField(\n column: SqlColumnIR,\n table: SqlTableIR,\n typeMap: PslTypeMap,\n enumNameMap: ReadonlyMap<string, string>,\n fieldNameMap: TableColumnFieldNameMap | undefined,\n namedTypes: NamedTypeRegistry,\n defaultMapping: DefaultMappingOptions | undefined,\n rawDefaultParser: PslPrinterOptions['parseRawDefault'],\n pkColumns: ReadonlySet<string>,\n isSinglePk: boolean,\n singlePkConstraintName: string | undefined,\n uniqueColumns: ReadonlyMap<string, string | undefined>,\n): PslField {\n const resolvedField = fieldNameMap?.get(column.name);\n const fieldName = resolvedField?.fieldName ?? toFieldName(column.name).name;\n const fieldMap = resolvedField?.fieldMap;\n\n const resolution = typeMap.resolve(column.nativeType, table.annotations);\n\n if ('unsupported' in resolution) {\n const attrs: PslFieldAttribute[] = [];\n if (fieldMap !== undefined) {\n attrs.push(buildMapAttribute('field', fieldMap));\n }\n return {\n kind: 'field',\n name: fieldName,\n typeName: `Unsupported(\"${escapePslString(resolution.nativeType)}\")`,\n optional: column.nullable,\n list: column.many === true,\n attributes: attrs,\n span: SYNTHETIC_SPAN,\n };\n }\n\n let typeName = resolution.pslType;\n const enumPslName = enumNameMap.get(column.nativeType);\n if (enumPslName) {\n typeName = enumPslName;\n }\n if (resolution.nativeTypeAttribute && !enumPslName) {\n typeName = resolveNamedTypeName(namedTypes, resolution);\n }\n\n const attributes: PslFieldAttribute[] = [];\n const isId = isSinglePk && pkColumns.has(column.name);\n if (isId) {\n attributes.push(buildSimpleConstraintFieldAttribute('id', singlePkConstraintName));\n }\n\n if (column.default !== undefined) {\n const parsed = parseColumnDefault(column.default, column.nativeType, rawDefaultParser);\n if (parsed) {\n const result = mapDefault(parsed, defaultMapping);\n if ('attribute' in result) {\n attributes.push(parseDefaultAttributeString(result.attribute));\n }\n // 'comment' fallback (unrecognized raw default) is dropped — the\n // M1 legacy path emitted a `// Raw default: ...` line above the field via\n // `PrinterField.comment`. M2 drops this since it would require comment\n // nodes in the AST.\n }\n }\n\n if (uniqueColumns.has(column.name) && !isId) {\n const uniqueConstraintName = uniqueColumns.get(column.name);\n attributes.push(buildSimpleConstraintFieldAttribute('unique', uniqueConstraintName));\n }\n\n if (fieldMap !== undefined) {\n attributes.push(buildMapAttribute('field', fieldMap));\n }\n\n return {\n kind: 'field',\n name: fieldName,\n typeName,\n optional: column.nullable,\n list: column.many === true,\n attributes,\n span: SYNTHETIC_SPAN,\n };\n}\n\nfunction buildRelationField(\n rel: RelationField,\n hostTableName: string,\n fieldNamesByTable: ReadonlyMap<string, TableColumnFieldNameMap>,\n usedFieldNames: Set<string>,\n): PslField {\n const fieldName = createUniqueFieldName(rel.fieldName, usedFieldNames);\n usedFieldNames.add(fieldName);\n\n const args: PslAttributeArgument[] = [];\n\n if (rel.fields && rel.references) {\n if (rel.relationName) {\n args.push(namedArg('name', `\"${escapePslString(rel.relationName)}\"`));\n }\n args.push(\n namedArg(\n 'fields',\n `[${rel.fields\n .map((columnName) => resolveColumnFieldName(fieldNamesByTable, hostTableName, columnName))\n .join(', ')}]`,\n ),\n );\n args.push(\n namedArg(\n 'references',\n `[${rel.references\n .map((columnName) =>\n resolveColumnFieldName(fieldNamesByTable, rel.referencedTableName ?? '', columnName),\n )\n .join(', ')}]`,\n ),\n );\n if (rel.onDelete) {\n args.push(namedArg('onDelete', rel.onDelete));\n }\n if (rel.onUpdate) {\n args.push(namedArg('onUpdate', rel.onUpdate));\n }\n if (rel.fkName) {\n args.push(namedArg('map', `\"${escapePslString(rel.fkName)}\"`));\n }\n } else if (rel.relationName) {\n args.push(namedArg('name', `\"${escapePslString(rel.relationName)}\"`));\n }\n\n const attrs: PslFieldAttribute[] =\n args.length > 0 ? [buildAttribute('field', 'relation', args)] : [];\n\n return {\n kind: 'field',\n name: fieldName,\n typeName: rel.typeName,\n optional: rel.optional,\n list: rel.list,\n attributes: attrs,\n span: SYNTHETIC_SPAN,\n };\n}\n\nfunction buildModelConstraintAttribute(\n name: 'id' | 'unique' | 'index',\n fields: readonly string[],\n constraintName?: string,\n): PslModelAttribute {\n const args: PslAttributeArgument[] = [positionalArg(`[${fields.join(', ')}]`)];\n if (constraintName !== undefined) {\n args.push(namedArg('map', `\"${escapePslString(constraintName)}\"`));\n }\n return buildAttribute('model', name, args);\n}\n\nfunction buildSimpleConstraintFieldAttribute(\n name: 'id' | 'unique',\n constraintName: string | undefined,\n): PslFieldAttribute {\n if (constraintName === undefined) {\n return buildAttribute('field', name, []);\n }\n return buildAttribute('field', name, [namedArg('map', `\"${escapePslString(constraintName)}\"`)]);\n}\n\nfunction parseDefaultAttributeString(attributeText: string): PslFieldAttribute {\n // Strip leading \"@default(\" and trailing \")\" — `mapDefault` always returns one\n // top-level positional expression.\n const inner = attributeText.replace(/^@default\\(/, '').replace(/\\)$/, '');\n return buildAttribute('field', 'default', [positionalArg(inner)]);\n}\n\nfunction buildMapAttribute(target: 'model' | 'field' | 'enum', mapName: string): PslAttribute {\n return buildAttribute(target, 'map', [positionalArg(`\"${escapePslString(mapName)}\"`)]);\n}\n\nfunction buildAttribute(\n target: PslAttribute['target'],\n name: string,\n args: readonly PslAttributeArgument[],\n): PslAttribute {\n return {\n kind: 'attribute',\n target,\n name,\n args,\n span: SYNTHETIC_SPAN,\n };\n}\n\nfunction positionalArg(value: string): PslAttributeArgument {\n return { kind: 'positional', value, span: SYNTHETIC_SPAN };\n}\n\nfunction namedArg(name: string, value: string): PslAttributeArgument {\n return { kind: 'named', name, value, span: SYNTHETIC_SPAN };\n}\n\nfunction buildNamedTypeDeclaration(entry: NamedTypeRegistryEntry): PslNamedTypeDeclaration {\n const attribute = buildAttribute(\n 'namedType',\n entry.nativeTypeAttribute.name,\n (entry.nativeTypeAttribute.args ?? []).map(positionalArg),\n );\n return {\n kind: 'namedType',\n name: entry.name,\n baseType: entry.baseType,\n attributes: [attribute],\n span: SYNTHETIC_SPAN,\n };\n}\n\nfunction escapePslString(value: string): string {\n return value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r');\n}\n\n/**\n * Resolves a `SqlColumnIR.default` value into a normalized {@link ColumnDefault}.\n *\n * `SqlSchemaIR` types the column default as `string` (a raw database default\n * expression). Some legacy fixtures and tests still pass already-normalized\n * `ColumnDefault` objects in the same slot, so we accept either shape\n * defensively at runtime.\n */\nfunction parseColumnDefault(\n value: unknown,\n nativeType: string | undefined,\n rawDefaultParser: PslPrinterOptions['parseRawDefault'],\n): ColumnDefault | undefined {\n if (typeof value === 'string') {\n return rawDefaultParser ? rawDefaultParser(value, nativeType) : undefined;\n }\n if (value !== null && typeof value === 'object' && 'kind' in (value as Record<string, unknown>)) {\n return value as ColumnDefault;\n }\n return undefined;\n}\n\nfunction buildFieldNamesByTable(\n tables: Record<string, SqlTableIR>,\n): ReadonlyMap<string, TableColumnFieldNameMap> {\n const fieldNamesByTable = new Map<string, TableColumnFieldNameMap>();\n\n for (const table of Object.values(tables)) {\n const columns = Object.values(table.columns).map((column, index) => {\n const { name, map } = toFieldName(column.name);\n return {\n columnName: column.name,\n desiredFieldName: name,\n fieldMap: map,\n index,\n };\n });\n\n const assignmentOrder = [...columns].sort((left, right) => {\n const mapComparison =\n Number(left.fieldMap !== undefined) - Number(right.fieldMap !== undefined);\n if (mapComparison !== 0) {\n return mapComparison;\n }\n return left.index - right.index;\n });\n\n const usedFieldNames = new Set<string>();\n const tableFieldNames = new Map<string, ResolvedColumnFieldName>();\n\n for (const column of assignmentOrder) {\n const fieldName = createUniqueFieldName(column.desiredFieldName, usedFieldNames);\n usedFieldNames.add(fieldName);\n tableFieldNames.set(column.columnName, {\n fieldName,\n fieldMap: column.fieldMap,\n });\n }\n\n fieldNamesByTable.set(table.name, tableFieldNames);\n }\n\n return fieldNamesByTable;\n}\n\nfunction resolveColumnFieldName(\n fieldNamesByTable: ReadonlyMap<string, TableColumnFieldNameMap>,\n tableName: string,\n columnName: string,\n): string {\n return (\n fieldNamesByTable.get(tableName)?.get(columnName)?.fieldName ?? toFieldName(columnName).name\n );\n}\n\nfunction createUniqueFieldName(desiredName: string, usedFieldNames: ReadonlySet<string>): string {\n if (!usedFieldNames.has(desiredName)) {\n return desiredName;\n }\n\n let counter = 2;\n while (usedFieldNames.has(`${desiredName}${counter}`)) {\n counter++;\n }\n return `${desiredName}${counter}`;\n}\n\nfunction buildTopLevelNameMap(\n sources: Iterable<string>,\n normalize: (source: string) => TopLevelNameResult,\n kind: 'model' | 'enum',\n sourceKind: 'table' | 'enum type',\n): Map<string, TopLevelNameResult> {\n const results = new Map<string, TopLevelNameResult>();\n const normalizedToSources = new Map<string, string[]>();\n\n for (const source of sources) {\n const normalized = normalize(source);\n results.set(source, normalized);\n normalizedToSources.set(normalized.name, [\n ...(normalizedToSources.get(normalized.name) ?? []),\n source,\n ]);\n }\n\n const duplicates = [...normalizedToSources.entries()].filter(\n ([, conflictingSources]) => conflictingSources.length > 1,\n );\n if (duplicates.length > 0) {\n const details = duplicates.map(\n ([normalizedName, conflictingSources]) =>\n `- ${kind} \"${normalizedName}\" from ${sourceKind}s ${conflictingSources\n .map((source) => `\"${source}\"`)\n .join(', ')}`,\n );\n throw new Error(`PSL ${kind} name collisions detected:\\n${details.join('\\n')}`);\n }\n\n return results;\n}\n\nfunction createReservedNamedTypeNames(\n modelNames: ReadonlyMap<string, TopLevelNameResult>,\n): Set<string> {\n const reservedNames = new Set<string>(PSL_SCALAR_TYPE_NAMES);\n\n for (const result of modelNames.values()) {\n reservedNames.add(result.name);\n }\n\n return reservedNames;\n}\n\nfunction seedNamedTypeRegistry(\n schemaIR: SqlSchemaIR,\n typeMap: PslTypeMap,\n enumNameMap: ReadonlyMap<string, string>,\n reservedNames: ReadonlySet<string>,\n): NamedTypeRegistry {\n type Seed = {\n readonly baseType: string;\n readonly desiredName: string;\n readonly nativeTypeAttribute: PslNativeTypeAttribute;\n };\n\n const seeds = new Map<string, Seed>();\n\n for (const tableName of Object.keys(schemaIR.tables).sort()) {\n const table = schemaIR.tables[tableName];\n if (!table) {\n continue;\n }\n\n for (const columnName of Object.keys(table.columns).sort()) {\n const column = table.columns[columnName];\n if (!column) {\n continue;\n }\n\n const resolution = typeMap.resolve(column.nativeType, table.annotations);\n if (\n 'unsupported' in resolution ||\n enumNameMap.has(column.nativeType) ||\n !resolution.nativeTypeAttribute\n ) {\n continue;\n }\n\n const signatureKey = createNamedTypeSignatureKey(resolution);\n if (!seeds.has(signatureKey)) {\n seeds.set(signatureKey, {\n baseType: resolution.pslType,\n desiredName: toNamedTypeName(column.name),\n nativeTypeAttribute: resolution.nativeTypeAttribute,\n });\n }\n }\n }\n\n const registry: NamedTypeRegistry = {\n entriesByKey: new Map<string, NamedTypeRegistryEntry>(),\n usedNames: new Set<string>(reservedNames),\n };\n\n const sortedSeeds = [...seeds.entries()].sort((left, right) => {\n const desiredNameComparison = left[1].desiredName.localeCompare(right[1].desiredName);\n if (desiredNameComparison !== 0) {\n return desiredNameComparison;\n }\n return left[0].localeCompare(right[0]);\n });\n\n for (const [signatureKey, seed] of sortedSeeds) {\n const name = createUniqueFieldName(seed.desiredName, registry.usedNames);\n registry.entriesByKey.set(signatureKey, {\n name,\n baseType: seed.baseType,\n nativeTypeAttribute: seed.nativeTypeAttribute,\n });\n registry.usedNames.add(name);\n }\n\n return registry;\n}\n\nfunction resolveNamedTypeName(\n registry: NamedTypeRegistry,\n resolution: {\n readonly pslType: string;\n readonly nativeType: string;\n readonly typeParams?: Record<string, unknown>;\n readonly nativeTypeAttribute?: PslNativeTypeAttribute;\n },\n): string {\n const key = createNamedTypeSignatureKey(resolution);\n const existing = registry.entriesByKey.get(key);\n if (existing) {\n return existing.name;\n }\n\n throw new Error(`Named type registry was not seeded for native type \"${resolution.nativeType}\"`);\n}\n\nfunction createNamedTypeSignatureKey(resolution: {\n readonly pslType: string;\n readonly nativeType: string;\n readonly typeParams?: Record<string, unknown>;\n readonly nativeTypeAttribute?: PslNativeTypeAttribute;\n}): string {\n return JSON.stringify({\n baseType: resolution.pslType,\n nativeTypeAttribute: resolution.nativeTypeAttribute\n ? {\n name: resolution.nativeTypeAttribute.name,\n args: resolution.nativeTypeAttribute.args ?? null,\n }\n : null,\n });\n}\n\nfunction topologicalSort(\n models: PslModel[],\n tables: Record<string, SqlTableIR>,\n modelNameMap: ReadonlyMap<string, string>,\n): PslModel[] {\n const modelByName = new Map<string, PslModel>();\n for (const model of models) {\n modelByName.set(model.name, model);\n }\n\n const deps = new Map<string, Set<string>>();\n const tableToModel = new Map<string, string>();\n for (const tableName of Object.keys(tables)) {\n const modelName = modelNameMap.get(tableName) as string;\n tableToModel.set(tableName, modelName);\n deps.set(modelName, new Set());\n }\n\n for (const [tableName, table] of Object.entries(tables)) {\n const modelName = tableToModel.get(tableName) as string;\n for (const fk of table.foreignKeys) {\n const refModelName = tableToModel.get(fk.referencedTable);\n if (refModelName && refModelName !== modelName) {\n (deps.get(modelName) as Set<string>).add(refModelName);\n }\n }\n }\n\n const result: PslModel[] = [];\n const visited = new Set<string>();\n const visiting = new Set<string>();\n\n const sortedNames = [...deps.keys()].sort();\n\n function visit(name: string): void {\n if (visited.has(name)) return;\n if (visiting.has(name)) return;\n visiting.add(name);\n\n const sortedDeps = [...(deps.get(name) as Set<string>)].sort();\n for (const dep of sortedDeps) {\n visit(dep);\n }\n\n visiting.delete(name);\n visited.add(name);\n result.push(modelByName.get(name) as PslModel);\n }\n\n for (const name of sortedNames) {\n visit(name);\n }\n\n return result;\n}\n","import type { ColumnDefault } from '@prisma-next/contract/types';\nimport type { SqlControlTargetDescriptor } from '@prisma-next/family-sql/control';\nimport { extractCodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlTargetInstance,\n MigrationRunner,\n} from '@prisma-next/framework-components/control';\nimport type { StorageColumn } from '@prisma-next/sql-contract/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport { contractToPostgresDatabaseSchemaNode } from '../core/migrations/contract-to-postgres-database-schema-node';\nimport {\n diffPostgresDatabaseSchema,\n verifyPostgresDatabaseSchema,\n} from '../core/migrations/diff-database-schema';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\nimport { PostgresContractSerializer } from '../core/postgres-contract-serializer';\nimport type { PostgresContract } from '../core/postgres-schema';\nimport { PostgresSchemaVerifier } from '../core/postgres-schema-verifier';\nimport { inferPostgresPslContract } from '../core/psl-infer/infer-psl-contract';\nimport { PostgresDatabaseSchemaNode } from '../core/schema-ir/postgres-database-schema-node';\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 if (!input.codecId) return input.nativeType;\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) return input.nativeType;\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n contractSerializer: new PostgresContractSerializer(),\n schemaVerifier: new PostgresSchemaVerifier(),\n inferPslContract(schema) {\n PostgresDatabaseSchemaNode.assert(schema);\n return inferPostgresPslContract(schema);\n },\n diffDatabaseSchema(input) {\n return diffPostgresDatabaseSchema({\n contract: input.contract,\n actualSchema: input.schema,\n strict: input.strict,\n typeMetadataRegistry: input.typeMetadataRegistry,\n frameworkComponents: input.frameworkComponents,\n });\n },\n verifyDatabaseSchema(input) {\n return verifyPostgresDatabaseSchema({\n contract: input.contract,\n actualSchema: input.schema,\n strict: input.strict,\n typeMetadataRegistry: input.typeMetadataRegistry,\n frameworkComponents: input.frameworkComponents,\n });\n },\n migrations: {\n createPlanner(adapter: SqlControlAdapter<'postgres'>) {\n return createPostgresMigrationPlanner(adapter);\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n const postgresContract = blindCast<\n PostgresContract | null,\n 'the family resolver only binds this hook for a Postgres-target contract'\n >(contract);\n return contractToPostgresDatabaseSchemaNode(postgresContract, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(adapter: SqlControlAdapter<'postgres'>) {\n return createPostgresMigrationPlanner(adapter);\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;;;;AA+BA,MAAM,cAAc;;;;;AAMpB,SAAS,qBAAwD,OAAa;CAC5E,MAAM,SAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,KAAK,GAC3C,IAAI,QAAQ,QAAQ,QAAQ,KAAA,GAC1B,OAAO,OAAO;MACT,IAAI,MAAM,QAAQ,GAAG,GAC1B,OAAO,OAAO,OAAO,OAAO,CAAC,GAAG,GAAG,CAAC;MAC/B,IAAI,OAAO,QAAQ,UACxB,OAAO,OAAO,qBAAqB,GAA8B;MAEjE,OAAO,OAAO;CAGlB,OAAO,OAAO,OAAO,MAAM;AAC7B;AAEA,SAAgB,8BACd,QAC+C;CAC/C,OAAO,IAAI,wBAAwB,MAAM;AAC3C;AAEA,IAAM,0BAAN,MAAuF;CACxD;CAA7B,YAAY,QAAmD;EAAlC,KAAA,SAAA;CAAmC;;;;;;CAOhE,MAAM,oBACJ,SACmC;EACnC,MAAM,SACJ,QAAQ,cACR,OAAO,KAAK,QAAQ,oBAAoB,QAAQ,UAAU,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CACH,oBAAoB,IAAI,2BAA2B;CACnD,gBAAgB,IAAI,uBAAuB;CAC3C,iBAAiB,QAAQ;EACvB,2BAA2B,OAAO,MAAM;EACxC,OAAO,yBAAyB,MAAM;CACxC;CACA,mBAAmB,OAAO;EACxB,OAAO,2BAA2B;GAChC,UAAU,MAAM;GAChB,cAAc,MAAM;GACpB,QAAQ,MAAM;GACd,sBAAsB,MAAM;GAC5B,qBAAqB,MAAM;EAC7B,CAAC;CACH;CACA,qBAAqB,OAAO;EAC1B,OAAO,6BAA6B;GAClC,UAAU,MAAM;GAChB,cAAc,MAAM;GACpB,QAAQ,MAAM;GACd,sBAAsB,MAAM;GAC5B,qBAAqB,MAAM;EAC7B,CAAC;CACH;CACA,YAAY;EACV,cAAc,SAAwC;GACpD,OAAO,+BAA+B,OAAO;EAC/C;EACA,aAAa,QAAQ;GACnB,OAAO,8BAA8B,MAAM;EAC7C;EACA,iBAAiB,UAAU,qBAAqB;GAC9C,MAAM,WAAW,wBAAwB,mBAAmB;GAK5D,OAAO,qCAJkB,UAGvB,QACyD,GAAG;IAC5D,qBAAqB;IACrB,GAAG,UAAU,oBAAoB,QAAQ;IACzC,eAAe;GACjB,CAAC;EACH;CACF;CACA,SAAmD;EACjD,OAAO;GACL,UAAU;GACV,UAAU;EACZ;CACF;;;;;CAKA,cAAc,SAAwC;EACpD,OAAO,+BAA+B,OAAO;CAC/C;;;;;CAKA,aAAa,QAAQ;EACnB,OAAO,8BAA8B,MAAM;CAC7C;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"data-transform-BOWpliq8.mjs","names":[],"sources":["../src/core/migrations/operations/data-transform.ts"],"sourcesContent":["/**\n * User-facing `dataTransform` factory for the Postgres migration authoring\n * surface. Invoked directly inside a `migration.ts` file via the\n * `PostgresMigration` instance method (`this.dataTransform(...)`), which\n * supplies the control adapter from the migration's injected stack:\n *\n * ```ts\n * import endContract from './end-contract.json' with { type: 'json' };\n *\n * class M extends Migration {\n * override get operations() {\n * return [\n * this.dataTransform(endContract, 'backfill emails', {\n * check: () => db.users.select('id').where(({ email }) => email.isNull()).limit(1),\n * run: () => db.users.update({ email: '' }).where(({ email }) => email.isNull()),\n * }),\n * ];\n * }\n * }\n * ```\n *\n * The factory accepts lazy closures (`() => SqlQueryPlan | Buildable`),\n * invokes each one, asserts that its `meta.storageHash` matches the\n * `contract` it was handed (→ `PN-MIG-2005` on mismatch), and lowers the\n * plan via the supplied control adapter to a serialized `{sql, params}`\n * payload.\n *\n * The factory then lowers the data transform to the unified migration-op\n * shape `{ precheck, execute, postcheck }`. The user's `check` plan is\n * wrapped twice with opposite truth values:\n *\n * - precheck `SELECT EXISTS (<check>) AS ok` asserts there is work to do\n * (precheck is short-circuited by the runner's pre-satisfied-skip path\n * when nothing remains to backfill).\n * - postcheck `SELECT NOT EXISTS (<check>) AS ok` asserts the work is\n * complete after the run steps execute.\n *\n * The `check` plan is therefore expected to be a **rowset query whose\n * presence of any row signals \"work remains\"** — typically `select('id')\n * .where(<violation predicate>).limit(1)`. Scalar/aggregate shapes\n * (`count(*)`, `bool_and(...)`) do not work under this contract: they\n * always return exactly one row, so `EXISTS` is always true and\n * `NOT EXISTS` is always false. (This is the same row-presence contract\n * the pre-unification runner relied on; the wrapping is just lifting it\n * into SQL.)\n *\n * Each `run` plan becomes an execute step. Because the `Step.params`\n * field threads through `driver.query(sql, params)`, the user's bound\n * values flow through the driver's parameter binder rather than being\n * inlined into the SQL text.\n *\n * The free factory remains usable standalone (tests, ad-hoc tooling,\n * non-class contexts) by passing the adapter explicitly as the fourth\n * argument.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport { errorDataTransformContractMismatch } from '@prisma-next/errors/migration';\nimport type {\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n} from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlExecuteRequest } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresPlanTargetDetails } from '../planner-target-details';\n\ninterface Buildable<R = unknown> {\n build(): SqlQueryPlan<R>;\n}\n\n/**\n * A single-closure producer of a SQL query plan. Shared between\n * `check` and each `run` entry.\n */\nexport type DataTransformClosure = () => SqlQueryPlan | Buildable;\n\nexport interface DataTransformOptions {\n /**\n * Optional opt-in routing identity. Presence opts the transform into\n * invariant-aware routing; absence means it is path-dependent and\n * not referenceable from refs.\n */\n readonly invariantId?: string;\n /**\n * Optional pre-flight query. `undefined` means \"no check\". When\n * supplied, the closure must return a **rowset query** whose\n * presence of any row signals \"violations remain\". Conventional\n * shape: `db.<table>.select('id').where(<violation>).limit(1)`.\n * Scalar/aggregate shapes do not satisfy this contract.\n */\n readonly check?: DataTransformClosure;\n /** One or more mutation queries to execute. */\n readonly run: DataTransformClosure | readonly DataTransformClosure[];\n}\n\nexport async function dataTransform<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n name: string,\n options: DataTransformOptions,\n adapter: SqlControlAdapter<'postgres'>,\n): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n const runClosures: readonly DataTransformClosure[] = Array.isArray(options.run)\n ? options.run\n : [options.run as DataTransformClosure];\n\n const checkPlan = options.check\n ? await invokeAndLower(options.check, contract, adapter, name)\n : null;\n const runPlans = await Promise.all(\n runClosures.map((closure) => invokeAndLower(closure, contract, adapter, name)),\n );\n\n const precheck: readonly SqlMigrationPlanOperationStep[] = checkPlan\n ? [\n {\n description: `Check ${name} has work to do`,\n sql: `SELECT EXISTS (${checkPlan.sql}) AS ok`,\n params: checkPlan.params ?? [],\n },\n ]\n : [];\n\n const execute: readonly SqlMigrationPlanOperationStep[] = runPlans.map((plan) => ({\n description: `Run ${name}`,\n sql: plan.sql,\n params: plan.params ?? [],\n }));\n\n const postcheck: readonly SqlMigrationPlanOperationStep[] = checkPlan\n ? [\n {\n description: `Verify ${name} resolved all violations`,\n sql: `SELECT NOT EXISTS (${checkPlan.sql}) AS ok`,\n params: checkPlan.params ?? [],\n },\n ]\n : [];\n\n return {\n id: `data_migration.${name}`,\n label: `Data transform: ${name}`,\n operationClass: 'data',\n ...ifDefined('invariantId', options.invariantId),\n target: { id: 'postgres' },\n precheck,\n execute,\n postcheck,\n };\n}\n\nasync function invokeAndLower(\n closure: DataTransformClosure,\n contract: Contract<SqlStorage>,\n adapter: SqlControlAdapter<'postgres'>,\n name: string,\n): Promise<SqlExecuteRequest> {\n const result = closure();\n const plan = isBuildable(result) ? result.build() : result;\n assertContractMatches(plan, contract, name);\n return adapter.lowerToExecuteRequest(plan.ast, { contract });\n}\n\nfunction isBuildable(value: unknown): value is Buildable {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'build' in value &&\n typeof (value as { build: unknown }).build === 'function'\n );\n}\n\nfunction assertContractMatches(\n plan: SqlQueryPlan,\n contract: Contract<SqlStorage>,\n name: string,\n): void {\n if (plan.meta.storageHash !== contract.storage.storageHash) {\n throw errorDataTransformContractMismatch({\n dataTransformName: name,\n expected: contract.storage.storageHash,\n actual: plan.meta.storageHash,\n });\n }\n}\n"],"mappings":";;;AAkGA,eAAsB,cACpB,UACA,MACA,SACA,SAC+D;CAC/D,MAAM,cAA+C,MAAM,QAAQ,QAAQ,GAAG,IAC1E,QAAQ,MACR,CAAC,QAAQ,GAA2B;CAExC,MAAM,YAAY,QAAQ,QACtB,MAAM,eAAe,QAAQ,OAAO,UAAU,SAAS,IAAI,IAC3D;CACJ,MAAM,WAAW,MAAM,QAAQ,IAC7B,YAAY,KAAK,YAAY,eAAe,SAAS,UAAU,SAAS,IAAI,CAAC,CAC/E;CAEA,MAAM,WAAqD,YACvD,CACE;EACE,aAAa,SAAS,KAAK;EAC3B,KAAK,kBAAkB,UAAU,IAAI;EACrC,QAAQ,UAAU,UAAU,CAAC;CAC/B,CACF,IACA,CAAC;CAEL,MAAM,UAAoD,SAAS,KAAK,UAAU;EAChF,aAAa,OAAO;EACpB,KAAK,KAAK;EACV,QAAQ,KAAK,UAAU,CAAC;CAC1B,EAAE;CAEF,MAAM,YAAsD,YACxD,CACE;EACE,aAAa,UAAU,KAAK;EAC5B,KAAK,sBAAsB,UAAU,IAAI;EACzC,QAAQ,UAAU,UAAU,CAAC;CAC/B,CACF,IACA,CAAC;CAEL,OAAO;EACL,IAAI,kBAAkB;EACtB,OAAO,mBAAmB;EAC1B,gBAAgB;EAChB,GAAG,UAAU,eAAe,QAAQ,WAAW;EAC/C,QAAQ,EAAE,IAAI,WAAW;EACzB;EACA;EACA;CACF;AACF;AAEA,eAAe,eACb,SACA,UACA,SACA,MAC4B;CAC5B,MAAM,SAAS,QAAQ;CACvB,MAAM,OAAO,YAAY,MAAM,IAAI,OAAO,MAAM,IAAI;CACpD,sBAAsB,MAAM,UAAU,IAAI;CAC1C,OAAO,QAAQ,sBAAsB,KAAK,KAAK,EAAE,SAAS,CAAC;AAC7D;AAEA,SAAS,YAAY,OAAoC;CACvD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,WAAW,SACX,OAAQ,MAA6B,UAAU;AAEnD;AAEA,SAAS,sBACP,MACA,UACA,MACM;CACN,IAAI,KAAK,KAAK,gBAAgB,SAAS,QAAQ,aAC7C,MAAM,mCAAmC;EACvC,mBAAmB;EACnB,UAAU,SAAS,QAAQ;EAC3B,QAAQ,KAAK,KAAK;CACpB,CAAC;AAEL"}
1
+ {"version":3,"file":"data-transform-BOWpliq8.mjs","names":[],"sources":["../src/core/migrations/operations/data-transform.ts"],"sourcesContent":["/**\n * User-facing `dataTransform` factory for the Postgres migration authoring\n * surface. Invoked directly inside a `migration.ts` file via the\n * `PostgresMigration` instance method (`this.dataTransform(...)`), which\n * supplies the control adapter from the migration's injected stack:\n *\n * ```ts\n * import endContract from './end-contract.json' with { type: 'json' };\n *\n * class M extends Migration {\n * override get operations() {\n * return [\n * this.dataTransform(endContract, 'backfill emails', {\n * check: () => db.users.select('id').where(({ email }) => email.isNull()).limit(1),\n * run: () => db.users.update({ email: '' }).where(({ email }) => email.isNull()),\n * }),\n * ];\n * }\n * }\n * ```\n *\n * The factory accepts lazy closures (`() => SqlQueryPlan | Buildable`),\n * invokes each one, asserts that its `meta.storageHash` matches the\n * `contract` it was handed (→ `PN-MIG-2005` on mismatch), and lowers the\n * plan via the supplied control adapter to a serialized `{sql, params}`\n * payload.\n *\n * The factory then lowers the data transform to the unified migration-op\n * shape `{ precheck, execute, postcheck }`. The user's `check` plan is\n * wrapped twice with opposite truth values:\n *\n * - precheck `SELECT EXISTS (<check>) AS ok` asserts there is work to do\n * (precheck is short-circuited by the runner's pre-satisfied-skip path\n * when nothing remains to backfill).\n * - postcheck `SELECT NOT EXISTS (<check>) AS ok` asserts the work is\n * complete after the run steps execute.\n *\n * The `check` plan is therefore expected to be a **rowset query whose\n * presence of any row signals \"work remains\"** — typically `select('id')\n * .where(<violation predicate>).limit(1)`. Scalar/aggregate shapes\n * (`count(*)`, `bool_and(...)`) do not work under this contract: they\n * always return exactly one row, so `EXISTS` is always true and\n * `NOT EXISTS` is always false. (This is the same row-presence contract\n * the pre-unification runner relied on; the wrapping is just lifting it\n * into SQL.)\n *\n * Each `run` plan becomes an execute step. Because the `Step.params`\n * field threads through `driver.query(sql, params)`, the user's bound\n * values flow through the driver's parameter binder rather than being\n * inlined into the SQL text.\n *\n * The free factory remains usable standalone (tests, ad-hoc tooling,\n * non-class contexts) by passing the adapter explicitly as the fourth\n * argument.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport { errorDataTransformContractMismatch } from '@prisma-next/errors/migration';\nimport type {\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n} from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlExecuteRequest } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresPlanTargetDetails } from '../planner-target-details';\n\ninterface Buildable<R = unknown> {\n build(): SqlQueryPlan<R>;\n}\n\n/**\n * A single-closure producer of a SQL query plan. Shared between\n * `check` and each `run` entry.\n */\nexport type DataTransformClosure = () => SqlQueryPlan | Buildable;\n\nexport interface DataTransformOptions {\n /**\n * Optional opt-in routing identity. Presence opts the transform into\n * invariant-aware routing; absence means it is path-dependent and\n * not referenceable from refs.\n */\n readonly invariantId?: string;\n /**\n * Optional pre-flight query. `undefined` means \"no check\". When\n * supplied, the closure must return a **rowset query** whose\n * presence of any row signals \"violations remain\". Conventional\n * shape: `db.<table>.select('id').where(<violation>).limit(1)`.\n * Scalar/aggregate shapes do not satisfy this contract.\n */\n readonly check?: DataTransformClosure;\n /** One or more mutation queries to execute. */\n readonly run: DataTransformClosure | readonly DataTransformClosure[];\n}\n\nexport async function dataTransform<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n name: string,\n options: DataTransformOptions,\n adapter: SqlControlAdapter<'postgres'>,\n): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n const runClosures: readonly DataTransformClosure[] = Array.isArray(options.run)\n ? options.run\n : [options.run as DataTransformClosure];\n\n const checkPlan = options.check\n ? await invokeAndLower(options.check, contract, adapter, name)\n : null;\n const runPlans = await Promise.all(\n runClosures.map((closure) => invokeAndLower(closure, contract, adapter, name)),\n );\n\n // Raw remnant: the factory lowered the user's `check` plan above before\n // we get a chance to wrap it, so the EXISTS lifting only has text by the\n // time it runs. The fix is to rewrite the factory to defer lowering until\n // after wrapping — so `cfExpr.exists(checkPlan.ast)` can produce the\n // EXISTS query, then lower once at the boundary — not to grow new AST\n // substrate. Out of scope for the slice that introduced this comment.\n const precheck: readonly SqlMigrationPlanOperationStep[] = checkPlan\n ? [\n {\n description: `Check ${name} has work to do`,\n sql: `SELECT EXISTS (${checkPlan.sql}) AS ok`,\n params: checkPlan.params ?? [],\n },\n ]\n : [];\n\n const execute: readonly SqlMigrationPlanOperationStep[] = runPlans.map((plan) => ({\n description: `Run ${name}`,\n sql: plan.sql,\n params: plan.params ?? [],\n }));\n\n const postcheck: readonly SqlMigrationPlanOperationStep[] = checkPlan\n ? [\n {\n description: `Verify ${name} resolved all violations`,\n sql: `SELECT NOT EXISTS (${checkPlan.sql}) AS ok`,\n params: checkPlan.params ?? [],\n },\n ]\n : [];\n\n return {\n id: `data_migration.${name}`,\n label: `Data transform: ${name}`,\n operationClass: 'data',\n ...ifDefined('invariantId', options.invariantId),\n target: { id: 'postgres' },\n precheck,\n execute,\n postcheck,\n };\n}\n\nasync function invokeAndLower(\n closure: DataTransformClosure,\n contract: Contract<SqlStorage>,\n adapter: SqlControlAdapter<'postgres'>,\n name: string,\n): Promise<SqlExecuteRequest> {\n const result = closure();\n const plan = isBuildable(result) ? result.build() : result;\n assertContractMatches(plan, contract, name);\n return adapter.lowerToExecuteRequest(plan.ast, { contract });\n}\n\nfunction isBuildable(value: unknown): value is Buildable {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'build' in value &&\n typeof (value as { build: unknown }).build === 'function'\n );\n}\n\nfunction assertContractMatches(\n plan: SqlQueryPlan,\n contract: Contract<SqlStorage>,\n name: string,\n): void {\n if (plan.meta.storageHash !== contract.storage.storageHash) {\n throw errorDataTransformContractMismatch({\n dataTransformName: name,\n expected: contract.storage.storageHash,\n actual: plan.meta.storageHash,\n });\n }\n}\n"],"mappings":";;;AAkGA,eAAsB,cACpB,UACA,MACA,SACA,SAC+D;CAC/D,MAAM,cAA+C,MAAM,QAAQ,QAAQ,GAAG,IAC1E,QAAQ,MACR,CAAC,QAAQ,GAA2B;CAExC,MAAM,YAAY,QAAQ,QACtB,MAAM,eAAe,QAAQ,OAAO,UAAU,SAAS,IAAI,IAC3D;CACJ,MAAM,WAAW,MAAM,QAAQ,IAC7B,YAAY,KAAK,YAAY,eAAe,SAAS,UAAU,SAAS,IAAI,CAAC,CAC/E;CAQA,MAAM,WAAqD,YACvD,CACE;EACE,aAAa,SAAS,KAAK;EAC3B,KAAK,kBAAkB,UAAU,IAAI;EACrC,QAAQ,UAAU,UAAU,CAAC;CAC/B,CACF,IACA,CAAC;CAEL,MAAM,UAAoD,SAAS,KAAK,UAAU;EAChF,aAAa,OAAO;EACpB,KAAK,KAAK;EACV,QAAQ,KAAK,UAAU,CAAC;CAC1B,EAAE;CAEF,MAAM,YAAsD,YACxD,CACE;EACE,aAAa,UAAU,KAAK;EAC5B,KAAK,sBAAsB,UAAU,IAAI;EACzC,QAAQ,UAAU,UAAU,CAAC;CAC/B,CACF,IACA,CAAC;CAEL,OAAO;EACL,IAAI,kBAAkB;EACtB,OAAO,mBAAmB;EAC1B,gBAAgB;EAChB,GAAG,UAAU,eAAe,QAAQ,WAAW;EAC/C,QAAQ,EAAE,IAAI,WAAW;EACzB;EACA;EACA;CACF;AACF;AAEA,eAAe,eACb,SACA,UACA,SACA,MAC4B;CAC5B,MAAM,SAAS,QAAQ;CACvB,MAAM,OAAO,YAAY,MAAM,IAAI,OAAO,MAAM,IAAI;CACpD,sBAAsB,MAAM,UAAU,IAAI;CAC1C,OAAO,QAAQ,sBAAsB,KAAK,KAAK,EAAE,SAAS,CAAC;AAC7D;AAEA,SAAS,YAAY,OAAoC;CACvD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,WAAW,SACX,OAAQ,MAA6B,UAAU;AAEnD;AAEA,SAAS,sBACP,MACA,UACA,MACM;CACN,IAAI,KAAK,KAAK,gBAAgB,SAAS,QAAQ,aAC7C,MAAM,mCAAmC;EACvC,mBAAmB;EACnB,UAAU,SAAS,QAAQ;EAC3B,QAAQ,KAAK,KAAK;CACpB,CAAC;AAEL"}
@@ -1,4 +1,4 @@
1
- import { t as PostgresPlanTargetDetails } from "./planner-target-details-CIY6tLeo.mjs";
1
+ import { t as PostgresPlanTargetDetails } from "./planner-target-details-HkP4RrRO.mjs";
2
2
  import { SqlMigrationPlanOperation } from "@prisma-next/family-sql/control";
3
3
  import { SqlStorage } from "@prisma-next/sql-contract/types";
4
4
  import { Contract } from "@prisma-next/contract/types";
@@ -35,4 +35,4 @@ interface DataTransformOptions {
35
35
  declare function dataTransform<TContract extends Contract<SqlStorage>>(contract: TContract, name: string, options: DataTransformOptions, adapter: SqlControlAdapter<'postgres'>): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>;
36
36
  //#endregion
37
37
  export { DataTransformOptions as n, dataTransform as r, DataTransformClosure as t };
38
- //# sourceMappingURL=data-transform-DDgWdB5o.d.mts.map
38
+ //# sourceMappingURL=data-transform-qKy1U5V9.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"data-transform-DDgWdB5o.d.mts","names":[],"sources":["../src/core/migrations/operations/data-transform.ts"],"mappings":";;;;;;;;UAqEU,SAAA;EACR,KAAA,IAAS,YAAY,CAAC,CAAA;AAAA;;;AAiCsC;;KA1BlD,oBAAA,SAA6B,YAAA,GAAe,SAAS;AAAA,UAEhD,oBAAA;;;;;;WAMN,WAAA;;;;;;;;WAQA,KAAA,GAAQ,oBAAA;;WAER,GAAA,EAAK,oBAAA,YAAgC,oBAAA;AAAA;AAAA,iBAG1B,aAAA,mBAAgC,QAAA,CAAS,UAAA,GAC7D,QAAA,EAAU,SAAA,EACV,IAAA,UACA,OAAA,EAAS,oBAAA,EACT,OAAA,EAAS,iBAAA,eACR,OAAA,CAAQ,yBAAA,CAA0B,yBAAA"}
1
+ {"version":3,"file":"data-transform-qKy1U5V9.d.mts","names":[],"sources":["../src/core/migrations/operations/data-transform.ts"],"mappings":";;;;;;;;UAqEU,SAAA;EACR,KAAA,IAAS,YAAY,CAAC,CAAA;AAAA;;;AAiCsC;;KA1BlD,oBAAA,SAA6B,YAAA,GAAe,SAAS;AAAA,UAEhD,oBAAA;;;;;;WAMN,WAAA;;;;;;;;WAQA,KAAA,GAAQ,oBAAA;;WAER,GAAA,EAAK,oBAAA,YAAgC,oBAAA;AAAA;AAAA,iBAG1B,aAAA,mBAAgC,QAAA,CAAS,UAAA,GAC7D,QAAA,EAAU,SAAA,EACV,IAAA,UACA,OAAA,EAAS,oBAAA,EACT,OAAA,EAAS,iBAAA,eACR,OAAA,CAAQ,yBAAA,CAA0B,yBAAA"}
@@ -1,2 +1,2 @@
1
- import { r as dataTransform } from "./data-transform-DDgWdB5o.mjs";
1
+ import { r as dataTransform } from "./data-transform-qKy1U5V9.mjs";
2
2
  export { dataTransform };
@@ -1,6 +1,6 @@
1
1
  import { _ as PG_TEXT_CODEC_ID } from "./codec-ids-BvytN2P8.mjs";
2
- import { a as PostgresTableSource, i as postgresCreateNamespace } from "./postgres-schema-COGZ1ark.mjs";
3
- import { i as PostgresCreateTable, n as PostgresAlterTable, r as PostgresCreateSchema, t as AddColumnAction } from "./nodes-Bbhs2rwj.mjs";
2
+ import { i as postgresCreateNamespace, s as PostgresTableSource } from "./postgres-schema-BLIHBEfX.mjs";
3
+ import { a as PostgresCreateSchema, c as PostgresDropPolicy, i as PostgresCreatePolicy, n as DropDefaultAction, o as PostgresCreateTable, r as PostgresAlterTable, t as AddColumnAction } from "./nodes-Dh__NS58.mjs";
4
4
  import { cfExpr, cfTable, exprSelect } from "@prisma-next/sql-relational-core/contract-free";
5
5
  //#region src/contract-free/checks.ts
6
6
  /**
@@ -194,6 +194,39 @@ function extensionExistsAst(extensionName) {
194
194
  };
195
195
  }
196
196
  /**
197
+ * Typed RLS-policy existence check over `pg_policies`, with schema, table,
198
+ * and policy names bound as text parameters (never inlined). The `schema`
199
+ * coordinate is the resolved live-database schema name (e.g. `'public'`),
200
+ * compared against `pg_policies.schemaname` as a bound parameter.
201
+ */
202
+ function rlsPolicyExistsAst(options) {
203
+ const inner = () => exprSelect().from(cfTable("pg_policies")).project("one", cfExpr.lit(1)).where(cfExpr.allOf([
204
+ cfExpr.identifierRef("schemaname").eqParam(options.schema, PG_TEXT_CODEC_ID),
205
+ cfExpr.identifierRef("tablename").eqParam(options.table, PG_TEXT_CODEC_ID),
206
+ cfExpr.identifierRef("policyname").eqParam(options.policyName, PG_TEXT_CODEC_ID)
207
+ ]));
208
+ return {
209
+ policyPresent: () => exprSelect().project("result", cfExpr.exists(inner())).build(),
210
+ policyAbsent: () => exprSelect().project("result", cfExpr.notExists(inner())).build()
211
+ };
212
+ }
213
+ /**
214
+ * Typed row-level-security enabled check over `pg_class` joined to
215
+ * `pg_namespace`, comparing `pg_class.relrowsecurity` against the expected
216
+ * boolean. Schema and table names are bound as text parameters.
217
+ */
218
+ function rlsEnabledAst(schema, table) {
219
+ const inner = (enabled) => exprSelect().from(cfTable("pg_class", "c")).join(cfTable("pg_namespace", "n"), cfExpr.columnRef("n", "oid").eqExpr(cfExpr.columnRef("c", "relnamespace"))).project("one", cfExpr.lit(1)).where(cfExpr.allOf([
220
+ cfExpr.columnRef("n", "nspname").eqParam(schema, PG_TEXT_CODEC_ID),
221
+ cfExpr.columnRef("c", "relname").eqParam(table, PG_TEXT_CODEC_ID),
222
+ enabled ? cfExpr.columnRef("c", "relrowsecurity") : cfExpr.columnRef("c", "relrowsecurity").not()
223
+ ]));
224
+ return {
225
+ rlsEnabled: () => exprSelect().project("result", cfExpr.exists(inner(true))).build(),
226
+ rlsDisabled: () => exprSelect().project("result", cfExpr.exists(inner(false))).build()
227
+ };
228
+ }
229
+ /**
197
230
  * Typed index existence check riding the same `to_regclass` vocabulary as
198
231
  * `tableExistsAst`, with the qualified index name bound as a text parameter.
199
232
  */
@@ -239,13 +272,37 @@ function addColumnAction(column) {
239
272
  return new AddColumnAction(column);
240
273
  }
241
274
  /**
275
+ * Build a `DROP DEFAULT` action (`ALTER COLUMN "<name>" DROP DEFAULT`) for
276
+ * use inside {@link alterTable}. The renderer quotes the column name.
277
+ */
278
+ function dropDefaultAction(columnName) {
279
+ return new DropDefaultAction(columnName);
280
+ }
281
+ /**
242
282
  * Build a Postgres `ALTER TABLE` query node carrying one or more actions.
243
- * See {@link addColumnAction} for building actions.
283
+ * See {@link addColumnAction} / {@link dropDefaultAction} for building actions.
244
284
  */
245
285
  function alterTable(options) {
246
286
  return new PostgresAlterTable(options);
247
287
  }
288
+ /**
289
+ * Build a Postgres `CREATE POLICY` DDL node.
290
+ *
291
+ * Identifiers (`schema`, `table`, `name`) are quoted by the renderer.
292
+ * `using` and `withCheck` are emitted verbatim as predicate SQL — callers
293
+ * must supply safe, pre-validated SQL expressions.
294
+ */
295
+ function createPolicy(options) {
296
+ return new PostgresCreatePolicy(options);
297
+ }
298
+ /**
299
+ * Build a Postgres `DROP POLICY` DDL node.
300
+ * Identifiers (`schema`, `table`, `name`) are quoted by the renderer.
301
+ */
302
+ function dropPolicy(options) {
303
+ return new PostgresDropPolicy(options);
304
+ }
248
305
  //#endregion
249
- export { columnDefaultAst as a, columnTypeAst as c, indexExistsAst as d, noNullValuesAst as f, toRegclass as g, tablePrimaryKeyAst as h, createTable as i, constraintExistsAst as l, tableIsEmptyAst as m, alterTable as n, columnExistsAst as o, tableExistsAst as p, createSchema as r, columnNullabilityAst as s, addColumnAction as t, extensionExistsAst as u };
306
+ export { rlsPolicyExistsAst as _, createTable as a, tablePrimaryKeyAst as b, columnDefaultAst as c, columnTypeAst as d, constraintExistsAst as f, rlsEnabledAst as g, noNullValuesAst as h, createSchema as i, columnExistsAst as l, indexExistsAst as m, alterTable as n, dropDefaultAction as o, extensionExistsAst as p, createPolicy as r, dropPolicy as s, addColumnAction as t, columnNullabilityAst as u, tableExistsAst as v, toRegclass as x, tableIsEmptyAst as y };
250
307
 
251
- //# sourceMappingURL=ddl-QDyOSeLc.mjs.map
308
+ //# sourceMappingURL=ddl-BmLIe1z_.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ddl-BmLIe1z_.mjs","names":[],"sources":["../src/contract-free/checks.ts","../src/contract-free/ddl.ts"],"sourcesContent":["import type { SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport {\n type CfExpr,\n type CfExprSelectQuery,\n cfExpr,\n cfTable,\n exprSelect,\n} from '@prisma-next/sql-relational-core/contract-free';\nimport { PostgresTableSource } from '../core/ast/table-source';\nimport { PG_TEXT_CODEC_ID } from '../core/codec-ids';\nimport { postgresCreateNamespace } from '../core/postgres-schema';\n\n/**\n * `to_regclass($1)` with the qualified table name bound as a text parameter.\n * Thin vocabulary wrapper over the core `cfExpr.fn` helper — the target\n * supplies only the template and the codec'd operand.\n */\nexport function toRegclass(qualifiedName: string): CfExpr {\n return cfExpr.fn({\n method: 'to_regclass',\n template: 'to_regclass({{self}})',\n self: cfExpr.param(qualifiedName, PG_TEXT_CODEC_ID),\n returns: { codecId: PG_TEXT_CODEC_ID, nullable: true },\n });\n}\n\nexport interface TableExistsCheckBuilder {\n tableAbsent(): SelectAst;\n tablePresent(): SelectAst;\n}\n\n/**\n * Typed builder for the migration planner's table-existence checks. Produces\n * FROM-less `SELECT to_regclass($1) IS [NOT] NULL AS \"result\"` ASTs with the\n * qualified table name bound as a text parameter — never inlined into the SQL.\n *\n * `schema` is a namespace coordinate: the framework `__unbound__` sentinel\n * elides the qualifier (search_path decides at runtime); any other id\n * qualifies as `\"schema\".\"table\"`.\n */\nexport function tableExistsAst(schema: string, table: string): TableExistsCheckBuilder {\n const qualified = postgresCreateNamespace({ id: schema, entries: { table: {} } }).qualifyTable(\n table,\n );\n const regclass = toRegclass(qualified);\n return {\n tableAbsent: () => exprSelect().project('result', regclass.isNull()).build(),\n tablePresent: () => exprSelect().project('result', regclass.isNotNull()).build(),\n };\n}\n\nexport interface ConstraintExistsCheckBuilder {\n constraintPresent(): SelectAst;\n constraintAbsent(): SelectAst;\n}\n\n/**\n * Typed builder for the migration planner's constraint-existence checks.\n * Produces `SELECT [NOT ]EXISTS (SELECT 1 FROM pg_constraint c JOIN\n * pg_namespace n ON n.oid = c.connamespace WHERE c.conname = $1 AND\n * n.nspname = $2 [AND c.conrelid = to_regclass($3)]) AS \"result\"` with the\n * constraint name, schema name, and qualified table name bound as text\n * parameters.\n *\n * When `table` is omitted the check matches by name + schema across all\n * tables. Pass `table` to scope the check to a single table (prevents false\n * matches on identically-named constraints in different tables). `schema`\n * is a namespace coordinate: the `__unbound__` sentinel compares `nspname`\n * against `current_schema()` instead of a bound parameter.\n */\nexport function constraintExistsAst(options: {\n readonly constraintName: string;\n readonly schema: string;\n readonly table?: string;\n}): ConstraintExistsCheckBuilder {\n const namespace = postgresCreateNamespace({ id: options.schema, entries: { table: {} } });\n const conditions = [\n cfExpr.columnRef('c', 'conname').eqParam(options.constraintName, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('n', 'nspname').eqExpr(namespace.schemaFilterExpression()),\n ];\n if (options.table !== undefined) {\n conditions.push(\n cfExpr.columnRef('c', 'conrelid').eqExpr(toRegclass(namespace.qualifyTable(options.table))),\n );\n }\n const inner = (): CfExprSelectQuery =>\n exprSelect()\n .from(cfTable('pg_constraint', 'c'))\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('c', 'connamespace')),\n )\n .project('one', cfExpr.lit(1))\n .where(cfExpr.allOf(conditions));\n return {\n constraintPresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n constraintAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\nfunction checkNamespace(schema: string) {\n return postgresCreateNamespace({ id: schema, entries: { table: {} } });\n}\n\nfunction informationSchemaColumns(): PostgresTableSource {\n return new PostgresTableSource({ schema: 'information_schema', name: 'columns' });\n}\n\nfunction infoSchemaColumnConditions(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n}): CfExpr[] {\n return [\n cfExpr\n .identifierRef('table_schema')\n .eqExpr(checkNamespace(options.schema).schemaFilterExpression()),\n cfExpr.identifierRef('table_name').eqParam(options.table, PG_TEXT_CODEC_ID),\n cfExpr.identifierRef('column_name').eqParam(options.column, PG_TEXT_CODEC_ID),\n ];\n}\n\nfunction infoSchemaColumnQuery(conditions: ReadonlyArray<CfExpr>): CfExprSelectQuery {\n return exprSelect()\n .from(informationSchemaColumns())\n .project('one', cfExpr.lit(1))\n .where(cfExpr.allOf(conditions));\n}\n\nexport interface ColumnExistsCheckBuilder {\n columnPresent(): SelectAst;\n columnAbsent(): SelectAst;\n}\n\n/**\n * Typed builder for column-existence checks over\n * `information_schema.columns`, with schema, table, and column names bound\n * as text parameters.\n */\nexport function columnExistsAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n}): ColumnExistsCheckBuilder {\n const inner = () => infoSchemaColumnQuery(infoSchemaColumnConditions(options));\n return {\n columnPresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n columnAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\n/**\n * Typed nullability check: EXISTS over `information_schema.columns` with\n * `is_nullable` compared against the bound `'YES'` / `'NO'` marker.\n */\nexport function columnNullabilityAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n readonly nullable: boolean;\n}): SelectAst {\n const conditions = [\n ...infoSchemaColumnConditions(options),\n cfExpr.identifierRef('is_nullable').eqParam(options.nullable ? 'YES' : 'NO', PG_TEXT_CODEC_ID),\n ];\n return exprSelect()\n .project('result', cfExpr.exists(infoSchemaColumnQuery(conditions)))\n .build();\n}\n\nexport interface ColumnDefaultCheckBuilder {\n defaultPresent(): SelectAst;\n defaultAbsent(): SelectAst;\n noDefault(): SelectAst;\n}\n\n/**\n * Typed default-presence checks over `information_schema.columns`.\n * `defaultPresent` / `defaultAbsent` assert the column row exists with a\n * non-null / null `column_default`; `noDefault` is the NOT EXISTS variant\n * (also true when the column row is missing entirely).\n */\nexport function columnDefaultAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n}): ColumnDefaultCheckBuilder {\n const withDefault = () =>\n infoSchemaColumnQuery([\n ...infoSchemaColumnConditions(options),\n cfExpr.identifierRef('column_default').isNotNull(),\n ]);\n const withoutDefault = () =>\n infoSchemaColumnQuery([\n ...infoSchemaColumnConditions(options),\n cfExpr.identifierRef('column_default').isNull(),\n ]);\n return {\n defaultPresent: () => exprSelect().project('result', cfExpr.exists(withDefault())).build(),\n defaultAbsent: () => exprSelect().project('result', cfExpr.exists(withoutDefault())).build(),\n noDefault: () => exprSelect().project('result', cfExpr.notExists(withDefault())).build(),\n };\n}\n\n/**\n * Typed column-type check: EXISTS over `pg_attribute` joined to `pg_class`\n * and `pg_namespace`, comparing `format_type(a.atttypid, a.atttypmod)`\n * against the bound expected display type and excluding dropped columns.\n */\nexport function columnTypeAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n readonly expectedType: string;\n}): SelectAst {\n const formatType = cfExpr.fn({\n method: 'format_type',\n template: 'format_type({{self}}, {{arg0}})',\n self: cfExpr.columnRef('a', 'atttypid'),\n args: [cfExpr.columnRef('a', 'atttypmod')],\n returns: { codecId: PG_TEXT_CODEC_ID, nullable: false },\n });\n const inner = exprSelect()\n .from(cfTable('pg_attribute', 'a'))\n .join(\n cfTable('pg_class', 'c'),\n cfExpr.columnRef('c', 'oid').eqExpr(cfExpr.columnRef('a', 'attrelid')),\n )\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('c', 'relnamespace')),\n )\n .project('one', cfExpr.lit(1))\n .where(\n cfExpr.allOf([\n cfExpr\n .columnRef('n', 'nspname')\n .eqExpr(checkNamespace(options.schema).schemaFilterExpression()),\n cfExpr.columnRef('c', 'relname').eqParam(options.table, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('a', 'attname').eqParam(options.column, PG_TEXT_CODEC_ID),\n formatType.eqParam(options.expectedType, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('a', 'attisdropped').not(),\n ]),\n );\n return exprSelect().project('result', cfExpr.exists(inner)).build();\n}\n\nexport interface TablePrimaryKeyCheckBuilder {\n pkPresent(): SelectAst;\n pkAbsent(): SelectAst;\n}\n\n/**\n * Typed primary-key existence check over `pg_index` joined to `pg_class`\n * and `pg_namespace`, with a LEFT JOIN on the index relation so an\n * optional `constraintName` can scope the match to a named constraint.\n */\nexport function tablePrimaryKeyAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraintName?: string;\n}): TablePrimaryKeyCheckBuilder {\n const conditions = [\n cfExpr\n .columnRef('n', 'nspname')\n .eqExpr(checkNamespace(options.schema).schemaFilterExpression()),\n cfExpr.columnRef('c', 'relname').eqParam(options.table, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('i', 'indisprimary'),\n ];\n if (options.constraintName !== undefined) {\n conditions.push(\n cfExpr.columnRef('c2', 'relname').eqParam(options.constraintName, PG_TEXT_CODEC_ID),\n );\n }\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_index', 'i'))\n .join(\n cfTable('pg_class', 'c'),\n cfExpr.columnRef('c', 'oid').eqExpr(cfExpr.columnRef('i', 'indrelid')),\n )\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('c', 'relnamespace')),\n )\n .leftJoin(\n cfTable('pg_class', 'c2'),\n cfExpr.columnRef('c2', 'oid').eqExpr(cfExpr.columnRef('i', 'indexrelid')),\n )\n .project('one', cfExpr.lit(1))\n .where(cfExpr.allOf(conditions));\n return {\n pkPresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n pkAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\n/**\n * Typed emptiness check: NOT EXISTS over the user table itself with\n * `LIMIT 1`. The table is addressed through the namespace's polymorphic\n * `tableSource` (qualified for named schemas, bare for the unbound slot).\n */\nexport function tableIsEmptyAst(schema: string, table: string): SelectAst {\n const inner = exprSelect()\n .from(checkNamespace(schema).tableSource(table))\n .project('one', cfExpr.lit(1))\n .limit(1);\n return exprSelect().project('result', cfExpr.notExists(inner)).build();\n}\n\n/**\n * Typed no-NULL-values data check used by `SET NOT NULL` prechecks:\n * NOT EXISTS over the user table where the column IS NULL.\n */\nexport function noNullValuesAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n}): SelectAst {\n const inner = exprSelect()\n .from(checkNamespace(options.schema).tableSource(options.table))\n .project('one', cfExpr.lit(1))\n .where(cfExpr.identifierRef(options.column).isNull());\n return exprSelect().project('result', cfExpr.notExists(inner)).build();\n}\n\nexport interface ExtensionExistsCheckBuilder {\n extensionPresent(): SelectAst;\n extensionAbsent(): SelectAst;\n}\n\n/**\n * Typed extension existence check over `pg_extension`, with the extension\n * name bound as a text parameter.\n */\nexport function extensionExistsAst(extensionName: string): ExtensionExistsCheckBuilder {\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_extension'))\n .project('one', cfExpr.lit(1))\n .where(cfExpr.identifierRef('extname').eqParam(extensionName, PG_TEXT_CODEC_ID));\n return {\n extensionPresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n extensionAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\nexport interface RlsPolicyExistsCheckBuilder {\n policyPresent(): SelectAst;\n policyAbsent(): SelectAst;\n}\n\n/**\n * Typed RLS-policy existence check over `pg_policies`, with schema, table,\n * and policy names bound as text parameters (never inlined). The `schema`\n * coordinate is the resolved live-database schema name (e.g. `'public'`),\n * compared against `pg_policies.schemaname` as a bound parameter.\n */\nexport function rlsPolicyExistsAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly policyName: string;\n}): RlsPolicyExistsCheckBuilder {\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_policies'))\n .project('one', cfExpr.lit(1))\n .where(\n cfExpr.allOf([\n cfExpr.identifierRef('schemaname').eqParam(options.schema, PG_TEXT_CODEC_ID),\n cfExpr.identifierRef('tablename').eqParam(options.table, PG_TEXT_CODEC_ID),\n cfExpr.identifierRef('policyname').eqParam(options.policyName, PG_TEXT_CODEC_ID),\n ]),\n );\n return {\n policyPresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n policyAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\nexport interface RlsEnabledCheckBuilder {\n rlsEnabled(): SelectAst;\n rlsDisabled(): SelectAst;\n}\n\n/**\n * Typed row-level-security enabled check over `pg_class` joined to\n * `pg_namespace`, comparing `pg_class.relrowsecurity` against the expected\n * boolean. Schema and table names are bound as text parameters.\n */\nexport function rlsEnabledAst(schema: string, table: string): RlsEnabledCheckBuilder {\n const inner = (enabled: boolean) =>\n exprSelect()\n .from(cfTable('pg_class', 'c'))\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('c', 'relnamespace')),\n )\n .project('one', cfExpr.lit(1))\n .where(\n cfExpr.allOf([\n cfExpr.columnRef('n', 'nspname').eqParam(schema, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('c', 'relname').eqParam(table, PG_TEXT_CODEC_ID),\n enabled\n ? cfExpr.columnRef('c', 'relrowsecurity')\n : cfExpr.columnRef('c', 'relrowsecurity').not(),\n ]),\n );\n return {\n rlsEnabled: () =>\n exprSelect()\n .project('result', cfExpr.exists(inner(true)))\n .build(),\n rlsDisabled: () =>\n exprSelect()\n .project('result', cfExpr.exists(inner(false)))\n .build(),\n };\n}\n\nexport interface IndexExistsCheckBuilder {\n indexPresent(): SelectAst;\n indexAbsent(): SelectAst;\n}\n\n/**\n * Typed index existence check riding the same `to_regclass` vocabulary as\n * `tableExistsAst`, with the qualified index name bound as a text parameter.\n */\nexport function indexExistsAst(schema: string, indexName: string): IndexExistsCheckBuilder {\n const regclass = toRegclass(checkNamespace(schema).qualifyTable(indexName));\n return {\n indexPresent: () => exprSelect().project('result', regclass.isNotNull()).build(),\n indexAbsent: () => exprSelect().project('result', regclass.isNull()).build(),\n };\n}\n","import type { DdlColumn, DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';\nimport {\n AddColumnAction,\n type AnyAlterTableAction,\n DropDefaultAction,\n PostgresAlterTable,\n PostgresCreatePolicy,\n PostgresCreateSchema,\n PostgresCreateTable,\n PostgresDropPolicy,\n type RlsPolicyOperation,\n} from '../core/ddl/nodes';\n\n/**\n * Build a Postgres `CREATE TABLE` query node.\n *\n * Pass `constraints` for table-level composite primary keys, foreign keys, and\n * unique constraints — use the {@link PrimaryKeyConstraint}, {@link ForeignKeyConstraint},\n * and {@link UniqueConstraint} classes from `@prisma-next/sql-relational-core/ast`.\n *\n * Precondition: identifiers (`table`, `schema`, column names/types) are\n * emitted to SQL verbatim — they are not quoted or escaped, so callers must\n * pass pre-trusted values (e.g. fixed control-plane identifiers). String-literal\n * default values, by contrast, are single-quote-escaped (embedded `'` doubled)\n * by the renderer. Identifier quoting for untrusted identifiers is added when\n * the migration planner adopts this lowering path.\n */\nexport function createTable(options: {\n readonly table: string;\n readonly schema?: string;\n readonly ifNotExists?: boolean;\n readonly columns: readonly DdlColumn[];\n readonly constraints?: readonly DdlTableConstraint[];\n}): PostgresCreateTable {\n return new PostgresCreateTable(options);\n}\n\n/**\n * Build a Postgres `CREATE SCHEMA` query node. See {@link createTable} for the\n * pre-trusted-identifier precondition.\n */\nexport function createSchema(options: {\n readonly schema: string;\n readonly ifNotExists?: boolean;\n}): PostgresCreateSchema {\n return new PostgresCreateSchema(options);\n}\n\n/**\n * Build an `ADD COLUMN` action for use inside {@link alterTable}.\n * The column is a structured `DdlColumn` so codec-encoded defaults flow\n * through the adapter's `pgRenderDdlColumn` → `pgRenderDdlColumnDefault` path.\n */\nexport function addColumnAction(column: DdlColumn): AddColumnAction {\n return new AddColumnAction(column);\n}\n\n/**\n * Build a `DROP DEFAULT` action (`ALTER COLUMN \"<name>\" DROP DEFAULT`) for\n * use inside {@link alterTable}. The renderer quotes the column name.\n */\nexport function dropDefaultAction(columnName: string): DropDefaultAction {\n return new DropDefaultAction(columnName);\n}\n\n/**\n * Build a Postgres `ALTER TABLE` query node carrying one or more actions.\n * See {@link addColumnAction} / {@link dropDefaultAction} for building actions.\n */\nexport function alterTable(options: {\n readonly table: string;\n readonly schema?: string;\n readonly actions: readonly AnyAlterTableAction[];\n}): PostgresAlterTable {\n return new PostgresAlterTable(options);\n}\n\n/**\n * Build a Postgres `CREATE POLICY` DDL node.\n *\n * Identifiers (`schema`, `table`, `name`) are quoted by the renderer.\n * `using` and `withCheck` are emitted verbatim as predicate SQL — callers\n * must supply safe, pre-validated SQL expressions.\n */\nexport function createPolicy(options: {\n readonly schema: string;\n readonly table: string;\n readonly name: string;\n readonly permissive: boolean;\n readonly operation: RlsPolicyOperation;\n readonly roles: readonly string[];\n readonly using?: string;\n readonly withCheck?: string;\n}): PostgresCreatePolicy {\n return new PostgresCreatePolicy(options);\n}\n\n/**\n * Build a Postgres `DROP POLICY` DDL node.\n * Identifiers (`schema`, `table`, `name`) are quoted by the renderer.\n */\nexport function dropPolicy(options: {\n readonly schema: string;\n readonly table: string;\n readonly name: string;\n}): PostgresDropPolicy {\n return new PostgresDropPolicy(options);\n}\n"],"mappings":";;;;;;;;;;AAiBA,SAAgB,WAAW,eAA+B;CACxD,OAAO,OAAO,GAAG;EACf,QAAQ;EACR,UAAU;EACV,MAAM,OAAO,MAAM,eAAe,gBAAgB;EAClD,SAAS;GAAE,SAAS;GAAkB,UAAU;EAAK;CACvD,CAAC;AACH;;;;;;;;;;AAgBA,SAAgB,eAAe,QAAgB,OAAwC;CAIrF,MAAM,WAAW,WAHC,wBAAwB;EAAE,IAAI;EAAQ,SAAS,EAAE,OAAO,CAAC,EAAE;CAAE,CAAC,CAAC,CAAC,aAChF,KAEkC,CAAC;CACrC,OAAO;EACL,mBAAmB,WAAW,CAAC,CAAC,QAAQ,UAAU,SAAS,OAAO,CAAC,CAAC,CAAC,MAAM;EAC3E,oBAAoB,WAAW,CAAC,CAAC,QAAQ,UAAU,SAAS,UAAU,CAAC,CAAC,CAAC,MAAM;CACjF;AACF;;;;;;;;;;;;;;;AAqBA,SAAgB,oBAAoB,SAIH;CAC/B,MAAM,YAAY,wBAAwB;EAAE,IAAI,QAAQ;EAAQ,SAAS,EAAE,OAAO,CAAC,EAAE;CAAE,CAAC;CACxF,MAAM,aAAa,CACjB,OAAO,UAAU,KAAK,SAAS,CAAC,CAAC,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ACF;;;;;;;;;;;;;;;;;ACxZA,SAAgB,YAAY,SAMJ;CACtB,OAAO,IAAI,oBAAoB,OAAO;AACxC;;;;;AAMA,SAAgB,aAAa,SAGJ;CACvB,OAAO,IAAI,qBAAqB,OAAO;AACzC;;;;;;AAOA,SAAgB,gBAAgB,QAAoC;CAClE,OAAO,IAAI,gBAAgB,MAAM;AACnC;;;;;AAMA,SAAgB,kBAAkB,YAAuC;CACvE,OAAO,IAAI,kBAAkB,UAAU;AACzC;;;;;AAMA,SAAgB,WAAW,SAIJ;CACrB,OAAO,IAAI,mBAAmB,OAAO;AACvC;;;;;;;;AASA,SAAgB,aAAa,SASJ;CACvB,OAAO,IAAI,qBAAqB,OAAO;AACzC;;;;;AAMA,SAAgB,WAAW,SAIJ;CACrB,OAAO,IAAI,mBAAmB,OAAO;AACvC"}
package/dist/ddl.d.mts CHANGED
@@ -1,2 +1,3 @@
1
- import { a as PostgresAlterTable, c as PostgresDdlNode, i as AnyPostgresDdlNode, l as PostgresDdlVisitor, n as AlterTableActionVisitor, o as PostgresCreateSchema, r as AnyAlterTableAction, s as PostgresCreateTable, t as AddColumnAction } from "./nodes-pLeLgdis.mjs";
2
- export { AddColumnAction, type AlterTableActionVisitor, type AnyAlterTableAction, type AnyPostgresDdlNode, PostgresAlterTable, PostgresCreateSchema, PostgresCreateTable, PostgresDdlNode, type PostgresDdlVisitor };
1
+ import { n as RlsPolicyOperation } from "./canonicalize-CAbXtVtB.mjs";
2
+ import { a as DropDefaultAction, c as PostgresCreateSchema, d as PostgresDdlVisitor, f as PostgresDropPolicy, i as AnyPostgresDdlNode, l as PostgresCreateTable, n as AlterTableActionVisitor, o as PostgresAlterTable, r as AnyAlterTableAction, s as PostgresCreatePolicy, t as AddColumnAction, u as PostgresDdlNode } from "./nodes-CSkPX3rI.mjs";
3
+ export { AddColumnAction, type AlterTableActionVisitor, type AnyAlterTableAction, type AnyPostgresDdlNode, DropDefaultAction, PostgresAlterTable, PostgresCreatePolicy, PostgresCreateSchema, PostgresCreateTable, PostgresDdlNode, type PostgresDdlVisitor, PostgresDropPolicy, type RlsPolicyOperation };
package/dist/ddl.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { a as PostgresDdlNode, i as PostgresCreateTable, n as PostgresAlterTable, r as PostgresCreateSchema, t as AddColumnAction } from "./nodes-Bbhs2rwj.mjs";
2
- export { AddColumnAction, PostgresAlterTable, PostgresCreateSchema, PostgresCreateTable, PostgresDdlNode };
1
+ import { a as PostgresCreateSchema, c as PostgresDropPolicy, i as PostgresCreatePolicy, n as DropDefaultAction, o as PostgresCreateTable, r as PostgresAlterTable, s as PostgresDdlNode, t as AddColumnAction } from "./nodes-Dh__NS58.mjs";
2
+ export { AddColumnAction, DropDefaultAction, PostgresAlterTable, PostgresCreatePolicy, PostgresCreateSchema, PostgresCreateTable, PostgresDdlNode, PostgresDropPolicy };