@prisma-next/target-postgres 0.15.0 → 0.16.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/dist/{authoring-BtsOWgI3.mjs → authoring-34L18kA1.mjs} +18 -8
  2. package/dist/authoring-34L18kA1.mjs.map +1 -0
  3. package/dist/canonicalize-D1F4vUnP.d.mts.map +1 -1
  4. package/dist/{codec-ids-CI144z7g.d.mts → codec-ids-BswpvvND.d.mts} +3 -3
  5. package/dist/codec-ids-BswpvvND.d.mts.map +1 -0
  6. package/dist/{codec-ids-B10ZZHzw.mjs → codec-ids-D3G8K0YM.mjs} +3 -2
  7. package/dist/codec-ids-D3G8K0YM.mjs.map +1 -0
  8. package/dist/codec-ids.d.mts +2 -2
  9. package/dist/codec-ids.mjs +2 -2
  10. package/dist/{codec-types-CTfT4U4O.d.mts → codec-types-CQ07nOz-.d.mts} +4 -5
  11. package/dist/codec-types-CQ07nOz-.d.mts.map +1 -0
  12. package/dist/codec-types.d.mts +1 -1
  13. package/dist/{codecs-D7W9O0Xx.d.mts → codecs-G4DTY0F_.d.mts} +35 -7
  14. package/dist/codecs-G4DTY0F_.d.mts.map +1 -0
  15. package/dist/{codecs-DRbb26Or.mjs → codecs-TCsGgW-Y.mjs} +77 -5
  16. package/dist/codecs-TCsGgW-Y.mjs.map +1 -0
  17. package/dist/codecs.d.mts +2 -3
  18. package/dist/codecs.d.mts.map +1 -1
  19. package/dist/codecs.mjs +2 -2
  20. package/dist/contract-free.d.mts +2 -3
  21. package/dist/contract-free.d.mts.map +1 -1
  22. package/dist/contract-free.mjs +3 -3
  23. package/dist/{control-policy-DtbkLLGv.mjs → control-policy-CZKdMztu.mjs} +44 -75
  24. package/dist/control-policy-CZKdMztu.mjs.map +1 -0
  25. package/dist/control.d.mts +0 -1
  26. package/dist/control.d.mts.map +1 -1
  27. package/dist/control.mjs +75 -25
  28. package/dist/control.mjs.map +1 -1
  29. package/dist/data-transform-BOWpliq8.mjs.map +1 -1
  30. package/dist/{data-transform-DPzwBMhW.d.mts → data-transform-CGvE8yGx.d.mts} +1 -2
  31. package/dist/data-transform-CGvE8yGx.d.mts.map +1 -0
  32. package/dist/data-transform.d.mts +1 -1
  33. package/dist/{ddl-GTTOvjx_.mjs → ddl-DHXKzQ99.mjs} +3 -3
  34. package/dist/{ddl-GTTOvjx_.mjs.map → ddl-DHXKzQ99.mjs.map} +1 -1
  35. package/dist/ddl.d.mts +1 -1
  36. package/dist/default-normalizer-B9ZUiyUE.mjs +264 -0
  37. package/dist/default-normalizer-B9ZUiyUE.mjs.map +1 -0
  38. package/dist/default-normalizer.d.mts +14 -2
  39. package/dist/default-normalizer.d.mts.map +1 -1
  40. package/dist/default-normalizer.mjs +2 -248
  41. package/dist/{descriptor-meta-CFQKLXl_.mjs → descriptor-meta-qubYaxQA.mjs} +9 -4
  42. package/dist/descriptor-meta-qubYaxQA.mjs.map +1 -0
  43. package/dist/{diff-database-schema-GncqMuSI.mjs → diff-database-schema-C-hnJ5mr.mjs} +92 -26
  44. package/dist/diff-database-schema-C-hnJ5mr.mjs.map +1 -0
  45. package/dist/diff-database-schema.d.mts +4 -13
  46. package/dist/diff-database-schema.d.mts.map +1 -1
  47. package/dist/diff-database-schema.mjs +1 -1
  48. package/dist/{errors-DO-w0EUS.mjs → errors-ByDS0xJL.mjs} +6 -6
  49. package/dist/errors-ByDS0xJL.mjs.map +1 -0
  50. package/dist/errors.d.mts +4 -4
  51. package/dist/errors.d.mts.map +1 -1
  52. package/dist/errors.mjs +1 -1
  53. package/dist/issue-planner.d.mts +1 -2
  54. package/dist/issue-planner.d.mts.map +1 -1
  55. package/dist/issue-planner.mjs +1 -1
  56. package/dist/migration.d.mts +3 -4
  57. package/dist/migration.d.mts.map +1 -1
  58. package/dist/migration.mjs +2 -2
  59. package/dist/native-type-normalizer.d.mts.map +1 -1
  60. package/dist/{nodes-Dv5eCSq9.d.mts → nodes-CQzM2hR0.d.mts} +1 -2
  61. package/dist/nodes-CQzM2hR0.d.mts.map +1 -0
  62. package/dist/{op-factory-call-Bn9zDx4_.d.mts → op-factory-call-DT7kdjVP.d.mts} +10 -7
  63. package/dist/op-factory-call-DT7kdjVP.d.mts.map +1 -0
  64. package/dist/{op-factory-call-C38NzvQD.mjs → op-factory-call-DuRj7WXX.mjs} +37 -16
  65. package/dist/{op-factory-call-C38NzvQD.mjs.map → op-factory-call-DuRj7WXX.mjs.map} +1 -1
  66. package/dist/op-factory-call.d.mts +2 -2
  67. package/dist/op-factory-call.mjs +2 -2
  68. package/dist/pack.d.mts +122 -6
  69. package/dist/pack.d.mts.map +1 -1
  70. package/dist/pack.mjs +1 -1
  71. package/dist/{planner-kql24i_F.mjs → planner-DPGxFcXo.mjs} +13 -13
  72. package/dist/planner-DPGxFcXo.mjs.map +1 -0
  73. package/dist/planner-ddl-builders.d.mts +1 -2
  74. package/dist/planner-ddl-builders.d.mts.map +1 -1
  75. package/dist/planner-identity-values.d.mts +0 -1
  76. package/dist/planner-identity-values.d.mts.map +1 -1
  77. package/dist/{planner-produced-postgres-migration-BEY1T0Xm.d.mts → planner-produced-postgres-migration-C-dwGdb2.d.mts} +2 -3
  78. package/dist/planner-produced-postgres-migration-C-dwGdb2.d.mts.map +1 -0
  79. package/dist/{planner-produced-postgres-migration-D7y-PEHK.mjs → planner-produced-postgres-migration-CFDpqWWE.mjs} +2 -2
  80. package/dist/planner-produced-postgres-migration-CFDpqWWE.mjs.map +1 -0
  81. package/dist/planner-produced-postgres-migration.d.mts +1 -1
  82. package/dist/planner-produced-postgres-migration.mjs +1 -1
  83. package/dist/planner-schema-lookup.d.mts +0 -1
  84. package/dist/planner-schema-lookup.d.mts.map +1 -1
  85. package/dist/{planner-sql-checks-zqNfs2XZ.mjs → planner-sql-checks-BuB877wH.mjs} +2 -2
  86. package/dist/{planner-sql-checks-zqNfs2XZ.mjs.map → planner-sql-checks-BuB877wH.mjs.map} +1 -1
  87. package/dist/planner-sql-checks.d.mts +0 -1
  88. package/dist/planner-sql-checks.d.mts.map +1 -1
  89. package/dist/planner-sql-checks.mjs +1 -1
  90. package/dist/planner-target-details-HkP4RrRO.d.mts.map +1 -1
  91. package/dist/planner.d.mts +3 -4
  92. package/dist/planner.d.mts.map +1 -1
  93. package/dist/planner.mjs +2 -2
  94. package/dist/{postgres-contract-view-C9j5cqP0.d.mts → postgres-contract-view-CeU7FJjW.d.mts} +4 -3
  95. package/dist/postgres-contract-view-CeU7FJjW.d.mts.map +1 -0
  96. package/dist/{postgres-contract-view-DM8sN1Ot.mjs → postgres-contract-view-DebHMqGR.mjs} +4 -4
  97. package/dist/{postgres-contract-view-DM8sN1Ot.mjs.map → postgres-contract-view-DebHMqGR.mjs.map} +1 -1
  98. package/dist/{postgres-database-schema-node-CJv5bfbs.d.mts → postgres-database-schema-node-DMXsIwAb.d.mts} +12 -4
  99. package/dist/postgres-database-schema-node-DMXsIwAb.d.mts.map +1 -0
  100. package/dist/{postgres-migration-arMSWU9b.mjs → postgres-migration-C_OPFhIF.mjs} +22 -6
  101. package/dist/postgres-migration-C_OPFhIF.mjs.map +1 -0
  102. package/dist/{postgres-migration-DbckK1su.d.mts → postgres-migration-DLIvzHjX.d.mts} +31 -7
  103. package/dist/postgres-migration-DLIvzHjX.d.mts.map +1 -0
  104. package/dist/{postgres-rls-policy--CSddvMR.d.mts → postgres-rls-policy-CYXdqG9B.d.mts} +1 -2
  105. package/dist/postgres-rls-policy-CYXdqG9B.d.mts.map +1 -0
  106. package/dist/{postgres-role-schema-node-Cm-j0ZGM.mjs → postgres-role-schema-node-bg32e7I-.mjs} +3 -2
  107. package/dist/postgres-role-schema-node-bg32e7I-.mjs.map +1 -0
  108. package/dist/{postgres-schema-Cm4DtiGA.mjs → postgres-schema-CewLYHB7.mjs} +2 -2
  109. package/dist/{postgres-schema-Cm4DtiGA.mjs.map → postgres-schema-CewLYHB7.mjs.map} +1 -1
  110. package/dist/{postgres-schema-DKq6s1P3.d.mts → postgres-schema-FdKRwe7X.d.mts} +3 -4
  111. package/dist/postgres-schema-FdKRwe7X.d.mts.map +1 -0
  112. package/dist/render-ops.d.mts +0 -1
  113. package/dist/render-ops.d.mts.map +1 -1
  114. package/dist/render-typescript.d.mts +0 -1
  115. package/dist/render-typescript.d.mts.map +1 -1
  116. package/dist/{resolve-ddl-schema-XyBaaenM.mjs → resolve-ddl-schema-D0wi_P9Q.mjs} +2 -2
  117. package/dist/{resolve-ddl-schema-XyBaaenM.mjs.map → resolve-ddl-schema-D0wi_P9Q.mjs.map} +1 -1
  118. package/dist/rls-canonicalize.d.mts +0 -1
  119. package/dist/rls-canonicalize.d.mts.map +1 -1
  120. package/dist/runtime.d.mts +1 -2
  121. package/dist/runtime.d.mts.map +1 -1
  122. package/dist/runtime.mjs +1 -1
  123. package/dist/schema-ir-annotations.d.mts +0 -1
  124. package/dist/schema-ir-annotations.d.mts.map +1 -1
  125. package/dist/schema-ir-annotations.mjs +1 -1
  126. package/dist/schema-node-kinds-DxvWh2Ic.d.mts +29 -0
  127. package/dist/schema-node-kinds-DxvWh2Ic.d.mts.map +1 -0
  128. package/dist/sql-utils.d.mts.map +1 -1
  129. package/dist/{table-source-BvFo7gVs.d.mts → table-source-D5c2fxAQ.d.mts} +1 -2
  130. package/dist/table-source-D5c2fxAQ.d.mts.map +1 -0
  131. package/dist/{types-BDKkx8MA.d.mts → types-D2MLzLBD.d.mts} +1 -2
  132. package/dist/types-D2MLzLBD.d.mts.map +1 -0
  133. package/dist/types.d.mts +6 -5
  134. package/dist/types.mjs +4 -4
  135. package/package.json +21 -21
  136. package/src/core/authoring.ts +18 -5
  137. package/src/core/codec-helpers.ts +53 -1
  138. package/src/core/codec-ids.ts +1 -0
  139. package/src/core/codecs.ts +56 -3
  140. package/src/core/default-normalizer.ts +22 -0
  141. package/src/core/descriptor-meta.ts +2 -0
  142. package/src/core/errors.ts +5 -5
  143. package/src/core/index-types.ts +15 -0
  144. package/src/core/migrations/contract-to-postgres-database-schema-node.ts +99 -19
  145. package/src/core/migrations/control-policy.ts +4 -3
  146. package/src/core/migrations/diff-database-schema.ts +6 -3
  147. package/src/core/migrations/issue-planner.ts +41 -80
  148. package/src/core/migrations/op-factory-call.ts +40 -16
  149. package/src/core/migrations/operations/data-transform.ts +1 -1
  150. package/src/core/migrations/planner-produced-postgres-migration.ts +1 -1
  151. package/src/core/migrations/planner-strategies.ts +6 -6
  152. package/src/core/migrations/planner.ts +5 -4
  153. package/src/core/migrations/postgres-migration.ts +62 -2
  154. package/src/core/migrations/runner.ts +12 -11
  155. package/src/core/migrations/verify-postgres-namespaces.ts +0 -1
  156. package/src/core/psl-infer/infer-psl-contract.ts +130 -12
  157. package/src/core/schema-ir/postgres-policy-schema-node.ts +12 -2
  158. package/src/exports/codecs.ts +2 -0
  159. package/src/exports/control.ts +2 -0
  160. package/src/exports/default-normalizer.ts +1 -1
  161. package/src/exports/op-factory-call.ts +5 -0
  162. package/src/exports/types.ts +1 -0
  163. package/dist/authoring-BtsOWgI3.mjs.map +0 -1
  164. package/dist/codec-ids-B10ZZHzw.mjs.map +0 -1
  165. package/dist/codec-ids-CI144z7g.d.mts.map +0 -1
  166. package/dist/codec-types-CTfT4U4O.d.mts.map +0 -1
  167. package/dist/codecs-D7W9O0Xx.d.mts.map +0 -1
  168. package/dist/codecs-DRbb26Or.mjs.map +0 -1
  169. package/dist/control-policy-DtbkLLGv.mjs.map +0 -1
  170. package/dist/data-transform-DPzwBMhW.d.mts.map +0 -1
  171. package/dist/default-normalizer.mjs.map +0 -1
  172. package/dist/descriptor-meta-CFQKLXl_.mjs.map +0 -1
  173. package/dist/diff-database-schema-GncqMuSI.mjs.map +0 -1
  174. package/dist/errors-DO-w0EUS.mjs.map +0 -1
  175. package/dist/nodes-Dv5eCSq9.d.mts.map +0 -1
  176. package/dist/op-factory-call-Bn9zDx4_.d.mts.map +0 -1
  177. package/dist/planner-kql24i_F.mjs.map +0 -1
  178. package/dist/planner-produced-postgres-migration-BEY1T0Xm.d.mts.map +0 -1
  179. package/dist/planner-produced-postgres-migration-D7y-PEHK.mjs.map +0 -1
  180. package/dist/postgres-contract-view-C9j5cqP0.d.mts.map +0 -1
  181. package/dist/postgres-database-schema-node-CJv5bfbs.d.mts.map +0 -1
  182. package/dist/postgres-migration-DbckK1su.d.mts.map +0 -1
  183. package/dist/postgres-migration-arMSWU9b.mjs.map +0 -1
  184. package/dist/postgres-rls-policy--CSddvMR.d.mts.map +0 -1
  185. package/dist/postgres-role-schema-node-Cm-j0ZGM.mjs.map +0 -1
  186. package/dist/postgres-schema-DKq6s1P3.d.mts.map +0 -1
  187. package/dist/table-source-BvFo7gVs.d.mts.map +0 -1
  188. package/dist/types-BDKkx8MA.d.mts.map +0 -1
@@ -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 // 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
+ {"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 (→ `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH` 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"}
@@ -4,7 +4,6 @@ import { SqlMigrationPlanOperation } from "@prisma-next/family-sql/control";
4
4
  import { Contract } from "@prisma-next/contract/types";
5
5
  import { SqlControlAdapter } from "@prisma-next/family-sql/control-adapter";
6
6
  import { SqlQueryPlan } from "@prisma-next/sql-relational-core/plan";
7
-
8
7
  //#region src/core/migrations/operations/data-transform.d.ts
9
8
  interface Buildable<R = unknown> {
10
9
  build(): SqlQueryPlan<R>;
@@ -35,4 +34,4 @@ interface DataTransformOptions {
35
34
  declare function dataTransform<TContract extends Contract<SqlStorage>>(contract: TContract, name: string, options: DataTransformOptions, adapter: SqlControlAdapter<'postgres'>): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>;
36
35
  //#endregion
37
36
  export { DataTransformOptions as n, dataTransform as r, DataTransformClosure as t };
38
- //# sourceMappingURL=data-transform-DPzwBMhW.d.mts.map
37
+ //# sourceMappingURL=data-transform-CGvE8yGx.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"data-transform-CGvE8yGx.d.mts","names":[],"sources":["../src/core/migrations/operations/data-transform.ts"],"mappings":";;;;;;;UAqEU,UAAU;EAClB,SAAS,aAAa;;;;;;KAOZ,6BAA6B,eAAe;UAEvC;;;;;;WAMN;;;;;;;;WAQA,QAAQ;;WAER,KAAK,gCAAgC;;iBAG1B,cAAc,kBAAkB,SAAS,aAC7D,UAAU,WACV,cACA,SAAS,sBACT,SAAS,gCACR,QAAQ,0BAA0B"}
@@ -1,2 +1,2 @@
1
- import { r as dataTransform } from "./data-transform-DPzwBMhW.mjs";
1
+ import { r as dataTransform } from "./data-transform-CGvE8yGx.mjs";
2
2
  export { dataTransform };
@@ -1,5 +1,5 @@
1
- import { y as PG_TEXT_CODEC_ID } from "./codec-ids-B10ZZHzw.mjs";
2
- import { i as postgresCreateNamespace, l as PostgresTableSource } from "./postgres-schema-Cm4DtiGA.mjs";
1
+ import { b as PG_TEXT_CODEC_ID } from "./codec-ids-D3G8K0YM.mjs";
2
+ import { i as postgresCreateNamespace, l as PostgresTableSource } from "./postgres-schema-CewLYHB7.mjs";
3
3
  import { a as PostgresCreatePolicy, c as PostgresCreateType, d as PostgresDropPolicy, f as PostgresDropType, i as PostgresAlterTable, n as DropDefaultAction, o as PostgresCreateSchema, r as PostgresAlterPolicyRename, s as PostgresCreateTable, t as AddColumnAction, u as PostgresDisableRowLevelSecurity } from "./nodes-DJC5B8Id.mjs";
4
4
  import { cfExpr, cfTable, exprSelect } from "@prisma-next/sql-relational-core/contract-free";
5
5
  //#region src/contract-free/checks.ts
@@ -370,4 +370,4 @@ function disableRowLevelSecurity(options) {
370
370
  //#endregion
371
371
  export { rlsPolicyExistsAst as C, toRegclass as D, tablePrimaryKeyAst as E, rlsEnabledAst as S, tableIsEmptyAst as T, extensionExistsAst as _, createSchema as a, nativeEnumValueExistsAst as b, disableRowLevelSecurity as c, dropType as d, columnDefaultAst as f, constraintExistsAst as g, columnTypeAst as h, createPolicy as i, dropDefaultAction as l, columnNullabilityAst as m, alterPolicyRename as n, createTable as o, columnExistsAst as p, alterTable as r, createType as s, addColumnAction as t, dropPolicy as u, indexExistsAst as v, tableExistsAst as w, noNullValuesAst as x, nativeEnumTypeExistsAst as y };
372
372
 
373
- //# sourceMappingURL=ddl-GTTOvjx_.mjs.map
373
+ //# sourceMappingURL=ddl-DHXKzQ99.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ddl-GTTOvjx_.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\nexport interface NativeEnumTypeExistsCheckBuilder {\n typePresent(): SelectAst;\n typeAbsent(): SelectAst;\n}\n\n/**\n * Typed native-enum type existence check over `pg_type` joined to\n * `pg_namespace`, restricted to enum types (`typtype = 'e'`). Schema and\n * type name are bound as text parameters; `schema` is a namespace\n * coordinate (the `__unbound__` sentinel compares against\n * `current_schema()`), matching {@link tableExistsAst} et al.\n */\nexport function nativeEnumTypeExistsAst(\n schema: string,\n typeName: string,\n): NativeEnumTypeExistsCheckBuilder {\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_type', 't'))\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('t', 'typnamespace')),\n )\n .project('one', cfExpr.lit(1))\n .where(\n cfExpr.allOf([\n cfExpr.columnRef('n', 'nspname').eqExpr(checkNamespace(schema).schemaFilterExpression()),\n cfExpr.columnRef('t', 'typname').eqParam(typeName, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('t', 'typtype').eqParam('e', PG_TEXT_CODEC_ID),\n ]),\n );\n return {\n typePresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n typeAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\nexport interface NativeEnumValueExistsCheckBuilder {\n valuePresent(): SelectAst;\n valueAbsent(): SelectAst;\n}\n\n/**\n * Typed native-enum member-value existence check over `pg_enum` joined to\n * `pg_type` and `pg_namespace`. Schema, type name, and the candidate member\n * value are bound as text parameters — used by `addNativeEnumValue`'s\n * precheck (value absent) and postcheck (value present).\n */\nexport function nativeEnumValueExistsAst(options: {\n readonly schema: string;\n readonly typeName: string;\n readonly value: string;\n}): NativeEnumValueExistsCheckBuilder {\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_enum', 'e'))\n .join(\n cfTable('pg_type', 't'),\n cfExpr.columnRef('t', 'oid').eqExpr(cfExpr.columnRef('e', 'enumtypid')),\n )\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('t', 'typnamespace')),\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('t', 'typname').eqParam(options.typeName, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('e', 'enumlabel').eqParam(options.value, PG_TEXT_CODEC_ID),\n ]),\n );\n return {\n valuePresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n valueAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n","import type { DdlColumn, DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';\nimport {\n AddColumnAction,\n type AnyAlterTableAction,\n DropDefaultAction,\n PostgresAlterPolicyRename,\n PostgresAlterTable,\n PostgresCreatePolicy,\n PostgresCreateSchema,\n PostgresCreateTable,\n PostgresCreateType,\n PostgresDisableRowLevelSecurity,\n PostgresDropPolicy,\n PostgresDropType,\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 a Postgres `CREATE TYPE … AS ENUM (…)` DDL node. The type name (and\n * optional schema) are quoted by the renderer; the enum member `values` are\n * emitted as single-quote-escaped string literals. An absent `schema` renders\n * the type name unqualified so the connection's `search_path` resolves it.\n */\nexport function createType(options: {\n readonly schema?: string;\n readonly name: string;\n readonly values: readonly string[];\n}): PostgresCreateType {\n return new PostgresCreateType(options);\n}\n\n/**\n * Build a Postgres `DROP TYPE` DDL node. See {@link createType} for the\n * identifier-quoting and unqualified-when-schemaless behaviour.\n */\nexport function dropType(options: {\n readonly schema?: string;\n readonly name: string;\n}): PostgresDropType {\n return new PostgresDropType(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\n/**\n * Build a Postgres `ALTER POLICY … RENAME TO` DDL node.\n * Identifiers (`schema`, `table`, `name`, `newName`) are quoted by the renderer.\n */\nexport function alterPolicyRename(options: {\n readonly schema: string;\n readonly table: string;\n readonly name: string;\n readonly newName: string;\n}): PostgresAlterPolicyRename {\n return new PostgresAlterPolicyRename(options);\n}\n\n/**\n * Build a Postgres `ALTER TABLE … DISABLE ROW LEVEL SECURITY` DDL node.\n * Identifiers (`schema`, `table`) are quoted by the renderer.\n */\nexport function disableRowLevelSecurity(options: {\n readonly schema: string;\n readonly table: string;\n}): PostgresDisableRowLevelSecurity {\n return new PostgresDisableRowLevelSecurity(options);\n}\n"],"mappings":";;;;;;;;;;AAiBA,SAAgB,WAAW,eAA+B;CACxD,OAAO,OAAO,GAA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,OAAO;AACzC;;;;;;;AAQA,SAAgB,WAAW,SAIJ;CACrB,OAAO,IAAI,mBAAmB,OAAO;AACvC;;;;;AAMA,SAAgB,SAAS,SAGJ;CACnB,OAAO,IAAI,iBAAiB,OAAO;AACrC;;;;;;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;;;;;AAMA,SAAgB,kBAAkB,SAKJ;CAC5B,OAAO,IAAI,0BAA0B,OAAO;AAC9C;;;;;AAMA,SAAgB,wBAAwB,SAGJ;CAClC,OAAO,IAAI,gCAAgC,OAAO;AACpD"}
1
+ {"version":3,"file":"ddl-DHXKzQ99.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\nexport interface NativeEnumTypeExistsCheckBuilder {\n typePresent(): SelectAst;\n typeAbsent(): SelectAst;\n}\n\n/**\n * Typed native-enum type existence check over `pg_type` joined to\n * `pg_namespace`, restricted to enum types (`typtype = 'e'`). Schema and\n * type name are bound as text parameters; `schema` is a namespace\n * coordinate (the `__unbound__` sentinel compares against\n * `current_schema()`), matching {@link tableExistsAst} et al.\n */\nexport function nativeEnumTypeExistsAst(\n schema: string,\n typeName: string,\n): NativeEnumTypeExistsCheckBuilder {\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_type', 't'))\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('t', 'typnamespace')),\n )\n .project('one', cfExpr.lit(1))\n .where(\n cfExpr.allOf([\n cfExpr.columnRef('n', 'nspname').eqExpr(checkNamespace(schema).schemaFilterExpression()),\n cfExpr.columnRef('t', 'typname').eqParam(typeName, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('t', 'typtype').eqParam('e', PG_TEXT_CODEC_ID),\n ]),\n );\n return {\n typePresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n typeAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\nexport interface NativeEnumValueExistsCheckBuilder {\n valuePresent(): SelectAst;\n valueAbsent(): SelectAst;\n}\n\n/**\n * Typed native-enum member-value existence check over `pg_enum` joined to\n * `pg_type` and `pg_namespace`. Schema, type name, and the candidate member\n * value are bound as text parameters — used by `addNativeEnumValue`'s\n * precheck (value absent) and postcheck (value present).\n */\nexport function nativeEnumValueExistsAst(options: {\n readonly schema: string;\n readonly typeName: string;\n readonly value: string;\n}): NativeEnumValueExistsCheckBuilder {\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_enum', 'e'))\n .join(\n cfTable('pg_type', 't'),\n cfExpr.columnRef('t', 'oid').eqExpr(cfExpr.columnRef('e', 'enumtypid')),\n )\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('t', 'typnamespace')),\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('t', 'typname').eqParam(options.typeName, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('e', 'enumlabel').eqParam(options.value, PG_TEXT_CODEC_ID),\n ]),\n );\n return {\n valuePresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n valueAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n","import type { DdlColumn, DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';\nimport {\n AddColumnAction,\n type AnyAlterTableAction,\n DropDefaultAction,\n PostgresAlterPolicyRename,\n PostgresAlterTable,\n PostgresCreatePolicy,\n PostgresCreateSchema,\n PostgresCreateTable,\n PostgresCreateType,\n PostgresDisableRowLevelSecurity,\n PostgresDropPolicy,\n PostgresDropType,\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 a Postgres `CREATE TYPE … AS ENUM (…)` DDL node. The type name (and\n * optional schema) are quoted by the renderer; the enum member `values` are\n * emitted as single-quote-escaped string literals. An absent `schema` renders\n * the type name unqualified so the connection's `search_path` resolves it.\n */\nexport function createType(options: {\n readonly schema?: string;\n readonly name: string;\n readonly values: readonly string[];\n}): PostgresCreateType {\n return new PostgresCreateType(options);\n}\n\n/**\n * Build a Postgres `DROP TYPE` DDL node. See {@link createType} for the\n * identifier-quoting and unqualified-when-schemaless behaviour.\n */\nexport function dropType(options: {\n readonly schema?: string;\n readonly name: string;\n}): PostgresDropType {\n return new PostgresDropType(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\n/**\n * Build a Postgres `ALTER POLICY … RENAME TO` DDL node.\n * Identifiers (`schema`, `table`, `name`, `newName`) are quoted by the renderer.\n */\nexport function alterPolicyRename(options: {\n readonly schema: string;\n readonly table: string;\n readonly name: string;\n readonly newName: string;\n}): PostgresAlterPolicyRename {\n return new PostgresAlterPolicyRename(options);\n}\n\n/**\n * Build a Postgres `ALTER TABLE … DISABLE ROW LEVEL SECURITY` DDL node.\n * Identifiers (`schema`, `table`) are quoted by the renderer.\n */\nexport function disableRowLevelSecurity(options: {\n readonly schema: string;\n readonly table: string;\n}): PostgresDisableRowLevelSecurity {\n return new PostgresDisableRowLevelSecurity(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,QAAQ,QAAQ,gBAAgB,gBAAgB,GACjF,OAAO,UAAU,KAAK,SAAS,CAAC,CAAC,OAAO,UAAU,uBAAuB,CAAC,CAC5E;CACA,IAAI,QAAQ,UAAU,KAAA,GACpB,WAAW,KACT,OAAO,UAAU,KAAK,UAAU,CAAC,CAAC,OAAO,WAAW,UAAU,aAAa,QAAQ,KAAK,CAAC,CAAC,CAC5F;CAEF,MAAM,cACJ,WAAW,CAAC,CACT,KAAK,QAAQ,iBAAiB,GAAG,CA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AmB,WAAW,CAAC,CAAC,QAAQ,UAAU,OAAO,UAAU,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM;CACrF;AACF;;;;;;;;;;;;;;;;;ACpeA,SAAgB,YAAY,SAMJ;CACtB,OAAO,IAAI,oBAAoB,OAAO;AACxC;;;;;AAMA,SAAgB,aAAa,SAGJ;CACvB,OAAO,IAAI,qBAAqB,OAAO;AACzC;;;;;;;AAQA,SAAgB,WAAW,SAIJ;CACrB,OAAO,IAAI,mBAAmB,OAAO;AACvC;;;;;AAMA,SAAgB,SAAS,SAGJ;CACnB,OAAO,IAAI,iBAAiB,OAAO;AACrC;;;;;;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;;;;;AAMA,SAAgB,kBAAkB,SAKJ;CAC5B,OAAO,IAAI,0BAA0B,OAAO;AAC9C;;;;;AAMA,SAAgB,wBAAwB,SAGJ;CAClC,OAAO,IAAI,gCAAgC,OAAO;AACpD"}
package/dist/ddl.d.mts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { r as RlsPolicyOperation } from "./canonicalize-D1F4vUnP.mjs";
2
- import { a as DropDefaultAction, c as PostgresCreatePolicy, d as PostgresCreateType, f as PostgresDdlNode, g as PostgresDropType, h as PostgresDropPolicy, i as AnyPostgresDdlNode, l as PostgresCreateSchema, m as PostgresDisableRowLevelSecurity, n as AlterTableActionVisitor, o as PostgresAlterPolicyRename, p as PostgresDdlVisitor, r as AnyAlterTableAction, s as PostgresAlterTable, t as AddColumnAction, u as PostgresCreateTable } from "./nodes-Dv5eCSq9.mjs";
2
+ import { a as DropDefaultAction, c as PostgresCreatePolicy, d as PostgresCreateType, f as PostgresDdlNode, g as PostgresDropType, h as PostgresDropPolicy, i as AnyPostgresDdlNode, l as PostgresCreateSchema, m as PostgresDisableRowLevelSecurity, n as AlterTableActionVisitor, o as PostgresAlterPolicyRename, p as PostgresDdlVisitor, r as AnyAlterTableAction, s as PostgresAlterTable, t as AddColumnAction, u as PostgresCreateTable } from "./nodes-CQzM2hR0.mjs";
3
3
  export { AddColumnAction, type AlterTableActionVisitor, type AnyAlterTableAction, type AnyPostgresDdlNode, DropDefaultAction, PostgresAlterPolicyRename, PostgresAlterTable, PostgresCreatePolicy, PostgresCreateSchema, PostgresCreateTable, PostgresCreateType, PostgresDdlNode, type PostgresDdlVisitor, PostgresDisableRowLevelSecurity, PostgresDropPolicy, PostgresDropType, type RlsPolicyOperation };
@@ -0,0 +1,264 @@
1
+ //#region src/core/default-normalizer.ts
2
+ /**
3
+ * Pre-compiled regex patterns for performance.
4
+ * These are compiled once at module load time rather than on each function call.
5
+ */
6
+ const NEXTVAL_PATTERN = /^nextval\s*\(/i;
7
+ const NOW_FUNCTION_PATTERN = /^(now\s*\(\s*\)|CURRENT_TIMESTAMP)$/i;
8
+ const CLOCK_TIMESTAMP_PATTERN = /^clock_timestamp\s*\(\s*\)$/i;
9
+ const TIMESTAMP_CAST_SUFFIX = /::timestamp(?:tz|\s+(?:with|without)\s+time\s+zone)?$/i;
10
+ const TEXT_CAST_SUFFIX = /::text$/i;
11
+ const NOW_LITERAL_PATTERN = /^'now'$/i;
12
+ const UUID_PATTERN = /^gen_random_uuid\s*\(\s*\)$/i;
13
+ const UUID_OSSP_PATTERN = /^uuid_generate_v4\s*\(\s*\)$/i;
14
+ const NULL_PATTERN = /^NULL(?:::.+)?$/i;
15
+ const TRUE_PATTERN = /^true$/i;
16
+ const FALSE_PATTERN = /^false$/i;
17
+ const NUMERIC_PATTERN = /^-?\d+(\.\d+)?$/;
18
+ const STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:"[^"]+"|[\w\s]+)(?:\(\d+\))?)?$/;
19
+ /**
20
+ * Matches a Postgres array literal default of the form `'{...}'::elemtype[]`.
21
+ * The literal body is captured in group 1; the cast (including `[]`) is optional.
22
+ * Examples: `'{}'::text[]`, `'{1,2}'::integer[]`, `'{}'`
23
+ */
24
+ const ARRAY_LITERAL_PATTERN = /^'(\{.*\})'(?:::.+\[\])?$/;
25
+ /**
26
+ * Returns the canonical expression for a timestamp default function, or undefined
27
+ * if the expression is not a recognized timestamp default.
28
+ *
29
+ * Keeps now()/CURRENT_TIMESTAMP and clock_timestamp() distinct:
30
+ * - now(), CURRENT_TIMESTAMP, ('now'::text)::timestamp... → 'now()'
31
+ * - clock_timestamp(), clock_timestamp()::timestamptz → 'clock_timestamp()'
32
+ *
33
+ * These are semantically different in Postgres: now() returns the transaction
34
+ * start time (constant within a transaction), while clock_timestamp() returns
35
+ * the actual wall-clock time (can differ across rows in a single INSERT).
36
+ */
37
+ function canonicalizeTimestampDefault(expr) {
38
+ if (NOW_FUNCTION_PATTERN.test(expr)) return "now()";
39
+ if (CLOCK_TIMESTAMP_PATTERN.test(expr)) return "clock_timestamp()";
40
+ if (!TIMESTAMP_CAST_SUFFIX.test(expr)) return void 0;
41
+ let inner = expr.replace(TIMESTAMP_CAST_SUFFIX, "").trim();
42
+ if (inner.startsWith("(") && inner.endsWith(")")) inner = inner.slice(1, -1).trim();
43
+ if (NOW_FUNCTION_PATTERN.test(inner)) return "now()";
44
+ if (CLOCK_TIMESTAMP_PATTERN.test(inner)) return "clock_timestamp()";
45
+ inner = inner.replace(TEXT_CAST_SUFFIX, "").trim();
46
+ if (NOW_LITERAL_PATTERN.test(inner)) return "now()";
47
+ }
48
+ /**
49
+ * Splits a Postgres array literal body (without the enclosing braces) into its
50
+ * element tokens, honouring quoting. A comma only separates elements when it is
51
+ * outside double quotes; inside a quoted element a doubled quote (`""`) or a
52
+ * backslash-escaped quote (`\"`) is a literal quote, and a backslash escapes the
53
+ * next character. Returns undefined if the body is malformed (e.g. an unbalanced
54
+ * quote).
55
+ */
56
+ function splitArrayElements(inner) {
57
+ const tokens = [];
58
+ let current = "";
59
+ let inQuotes = false;
60
+ let quoted = false;
61
+ for (let i = 0; i < inner.length; i++) {
62
+ const char = inner[i];
63
+ if (inQuotes) {
64
+ if (char === "\\") {
65
+ const next = inner[i + 1];
66
+ if (next === void 0) return void 0;
67
+ current += next;
68
+ i++;
69
+ continue;
70
+ }
71
+ if (char === "\"") {
72
+ if (inner[i + 1] === "\"") {
73
+ current += "\"";
74
+ i++;
75
+ continue;
76
+ }
77
+ inQuotes = false;
78
+ continue;
79
+ }
80
+ current += char;
81
+ continue;
82
+ }
83
+ if (char === "\"") {
84
+ inQuotes = true;
85
+ quoted = true;
86
+ continue;
87
+ }
88
+ if (char === ",") {
89
+ tokens.push({
90
+ value: current,
91
+ quoted
92
+ });
93
+ current = "";
94
+ quoted = false;
95
+ continue;
96
+ }
97
+ current += char;
98
+ }
99
+ if (inQuotes) return void 0;
100
+ tokens.push({
101
+ value: current,
102
+ quoted
103
+ });
104
+ return tokens;
105
+ }
106
+ /**
107
+ * Parses a Postgres array literal body (`{...}`) into a JS array of primitives.
108
+ * Returns undefined if the body cannot be reliably parsed.
109
+ *
110
+ * Handles:
111
+ * - `{}` → `[]`
112
+ * - `{elem1,elem2,...}` → `[elem1, elem2, ...]` with numeric and string element coercion
113
+ * - quoted elements that contain commas, doubled/escaped quotes, and the literal
114
+ * strings `NULL`/`true`/`false` (a quoted token is always a string)
115
+ */
116
+ function parseArrayLiteralBody(body) {
117
+ const inner = body.slice(1, -1).trim();
118
+ if (inner === "") return [];
119
+ const tokens = splitArrayElements(inner);
120
+ if (tokens === void 0) return void 0;
121
+ const result = [];
122
+ for (const token of tokens) {
123
+ if (token.quoted) {
124
+ result.push(token.value);
125
+ continue;
126
+ }
127
+ const el = token.value.trim();
128
+ if (el.toUpperCase() === "NULL") {
129
+ result.push(null);
130
+ continue;
131
+ }
132
+ if (el === "true") {
133
+ result.push(true);
134
+ continue;
135
+ }
136
+ if (el === "false") {
137
+ result.push(false);
138
+ continue;
139
+ }
140
+ if (NUMERIC_PATTERN.test(el)) {
141
+ result.push(Number(el));
142
+ continue;
143
+ }
144
+ return;
145
+ }
146
+ return result;
147
+ }
148
+ /**
149
+ * Parses a raw Postgres column default expression into a normalized ColumnDefault.
150
+ * This enables semantic comparison between contract defaults and introspected schema defaults.
151
+ *
152
+ * Used by the migration diff layer to normalize raw database defaults during comparison,
153
+ * keeping the introspection layer focused on faithful data capture.
154
+ *
155
+ * @param rawDefault - Raw default expression from information_schema.columns.column_default
156
+ * @param nativeType - Native column type, used for type-aware parsing (array, bigint, JSON)
157
+ * @returns Normalized ColumnDefault or undefined if the expression cannot be parsed
158
+ */
159
+ function parsePostgresDefault(rawDefault, nativeType) {
160
+ const trimmed = rawDefault.trim();
161
+ const normalizedType = nativeType?.toLowerCase();
162
+ const isBigInt = normalizedType === "bigint" || normalizedType === "int8";
163
+ const isArrayType = normalizedType?.endsWith("[]") ?? false;
164
+ if (NEXTVAL_PATTERN.test(trimmed)) return {
165
+ kind: "function",
166
+ expression: "autoincrement()"
167
+ };
168
+ if (isArrayType) {
169
+ const arrayMatch = trimmed.match(ARRAY_LITERAL_PATTERN);
170
+ if (arrayMatch?.[1] !== void 0) {
171
+ const parsed = parseArrayLiteralBody(arrayMatch[1]);
172
+ if (parsed !== void 0) return {
173
+ kind: "literal",
174
+ value: parsed
175
+ };
176
+ }
177
+ }
178
+ const canonicalTimestamp = canonicalizeTimestampDefault(trimmed);
179
+ if (canonicalTimestamp) return {
180
+ kind: "function",
181
+ expression: canonicalTimestamp
182
+ };
183
+ if (UUID_PATTERN.test(trimmed)) return {
184
+ kind: "function",
185
+ expression: "gen_random_uuid()"
186
+ };
187
+ if (UUID_OSSP_PATTERN.test(trimmed)) return {
188
+ kind: "function",
189
+ expression: "gen_random_uuid()"
190
+ };
191
+ if (NULL_PATTERN.test(trimmed)) return {
192
+ kind: "literal",
193
+ value: null
194
+ };
195
+ if (TRUE_PATTERN.test(trimmed)) return {
196
+ kind: "literal",
197
+ value: true
198
+ };
199
+ if (FALSE_PATTERN.test(trimmed)) return {
200
+ kind: "literal",
201
+ value: false
202
+ };
203
+ if (NUMERIC_PATTERN.test(trimmed)) {
204
+ const num = Number(trimmed);
205
+ if (!Number.isFinite(num)) return void 0;
206
+ if (isBigInt && !Number.isSafeInteger(num)) return {
207
+ kind: "literal",
208
+ value: trimmed
209
+ };
210
+ return {
211
+ kind: "literal",
212
+ value: num
213
+ };
214
+ }
215
+ const stringMatch = trimmed.match(STRING_LITERAL_PATTERN);
216
+ if (stringMatch?.[1] !== void 0) {
217
+ const unescaped = stringMatch[1].replace(/''/g, "'");
218
+ if (normalizedType === "json" || normalizedType === "jsonb") try {
219
+ return {
220
+ kind: "literal",
221
+ value: JSON.parse(unescaped)
222
+ };
223
+ } catch {}
224
+ if (isBigInt && NUMERIC_PATTERN.test(unescaped)) {
225
+ const num = Number(unescaped);
226
+ if (Number.isSafeInteger(num)) return {
227
+ kind: "literal",
228
+ value: num
229
+ };
230
+ return {
231
+ kind: "literal",
232
+ value: unescaped
233
+ };
234
+ }
235
+ return {
236
+ kind: "literal",
237
+ value: unescaped
238
+ };
239
+ }
240
+ return {
241
+ kind: "function",
242
+ expression: trimmed
243
+ };
244
+ }
245
+ /**
246
+ * Normalizes a contract-declared default through {@link parsePostgresDefault}
247
+ * — the same parser introspection uses — so a function-shaped default the
248
+ * parser recognizes as a literal (e.g. `dbgenerated("'{}'::jsonb")`)
249
+ * resolves to the same `resolvedDefault` shape a live introspected column
250
+ * would produce. Compensates once, at `SchemaIR` construction of the
251
+ * expected (contract-derived) side (`contractToSchemaIR`'s `resolveDefault`
252
+ * hook), instead of at every site that later compares the two sides. A
253
+ * literal default, or a function form the parser doesn't recognize, passes
254
+ * through unchanged; `nextval(...)` normalizes to `autoincrement()` on both
255
+ * sides, matching a `serial`/identity column's introspected counterpart.
256
+ */
257
+ function postgresResolveDefault(def, resolvedNativeType) {
258
+ if (def.kind !== "function") return def;
259
+ return parsePostgresDefault(def.expression, resolvedNativeType) ?? def;
260
+ }
261
+ //#endregion
262
+ export { postgresResolveDefault as n, parsePostgresDefault as t };
263
+
264
+ //# sourceMappingURL=default-normalizer-B9ZUiyUE.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"default-normalizer-B9ZUiyUE.mjs","names":[],"sources":["../src/core/default-normalizer.ts"],"sourcesContent":["import type { ColumnDefault, JsonValue } from '@prisma-next/contract/types';\n\n/**\n * Pre-compiled regex patterns for performance.\n * These are compiled once at module load time rather than on each function call.\n */\nconst NEXTVAL_PATTERN = /^nextval\\s*\\(/i;\nconst NOW_FUNCTION_PATTERN = /^(now\\s*\\(\\s*\\)|CURRENT_TIMESTAMP)$/i;\nconst CLOCK_TIMESTAMP_PATTERN = /^clock_timestamp\\s*\\(\\s*\\)$/i;\nconst TIMESTAMP_CAST_SUFFIX = /::timestamp(?:tz|\\s+(?:with|without)\\s+time\\s+zone)?$/i;\nconst TEXT_CAST_SUFFIX = /::text$/i;\nconst NOW_LITERAL_PATTERN = /^'now'$/i;\nconst UUID_PATTERN = /^gen_random_uuid\\s*\\(\\s*\\)$/i;\nconst UUID_OSSP_PATTERN = /^uuid_generate_v4\\s*\\(\\s*\\)$/i;\nconst NULL_PATTERN = /^NULL(?:::.+)?$/i;\nconst TRUE_PATTERN = /^true$/i;\nconst FALSE_PATTERN = /^false$/i;\nconst NUMERIC_PATTERN = /^-?\\d+(\\.\\d+)?$/;\nconst STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:\"[^\"]+\"|[\\w\\s]+)(?:\\(\\d+\\))?)?$/;\n\n/**\n * Matches a Postgres array literal default of the form `'{...}'::elemtype[]`.\n * The literal body is captured in group 1; the cast (including `[]`) is optional.\n * Examples: `'{}'::text[]`, `'{1,2}'::integer[]`, `'{}'`\n */\nconst ARRAY_LITERAL_PATTERN = /^'(\\{.*\\})'(?:::.+\\[\\])?$/;\n\n/**\n * Returns the canonical expression for a timestamp default function, or undefined\n * if the expression is not a recognized timestamp default.\n *\n * Keeps now()/CURRENT_TIMESTAMP and clock_timestamp() distinct:\n * - now(), CURRENT_TIMESTAMP, ('now'::text)::timestamp... → 'now()'\n * - clock_timestamp(), clock_timestamp()::timestamptz → 'clock_timestamp()'\n *\n * These are semantically different in Postgres: now() returns the transaction\n * start time (constant within a transaction), while clock_timestamp() returns\n * the actual wall-clock time (can differ across rows in a single INSERT).\n */\nfunction canonicalizeTimestampDefault(expr: string): string | undefined {\n if (NOW_FUNCTION_PATTERN.test(expr)) return 'now()';\n if (CLOCK_TIMESTAMP_PATTERN.test(expr)) return 'clock_timestamp()';\n\n if (!TIMESTAMP_CAST_SUFFIX.test(expr)) return undefined;\n\n let inner = expr.replace(TIMESTAMP_CAST_SUFFIX, '').trim();\n\n if (inner.startsWith('(') && inner.endsWith(')')) {\n inner = inner.slice(1, -1).trim();\n }\n\n if (NOW_FUNCTION_PATTERN.test(inner)) return 'now()';\n if (CLOCK_TIMESTAMP_PATTERN.test(inner)) return 'clock_timestamp()';\n\n inner = inner.replace(TEXT_CAST_SUFFIX, '').trim();\n if (NOW_LITERAL_PATTERN.test(inner)) return 'now()';\n\n return undefined;\n}\n\ntype ArrayElementToken = { readonly value: string; readonly quoted: boolean };\n\n/**\n * Splits a Postgres array literal body (without the enclosing braces) into its\n * element tokens, honouring quoting. A comma only separates elements when it is\n * outside double quotes; inside a quoted element a doubled quote (`\"\"`) or a\n * backslash-escaped quote (`\\\"`) is a literal quote, and a backslash escapes the\n * next character. Returns undefined if the body is malformed (e.g. an unbalanced\n * quote).\n */\nfunction splitArrayElements(inner: string): readonly ArrayElementToken[] | undefined {\n const tokens: ArrayElementToken[] = [];\n let current = '';\n let inQuotes = false;\n let quoted = false;\n\n for (let i = 0; i < inner.length; i++) {\n const char = inner[i];\n if (inQuotes) {\n if (char === '\\\\') {\n const next = inner[i + 1];\n if (next === undefined) return undefined;\n current += next;\n i++;\n continue;\n }\n if (char === '\"') {\n if (inner[i + 1] === '\"') {\n current += '\"';\n i++;\n continue;\n }\n inQuotes = false;\n continue;\n }\n current += char;\n continue;\n }\n if (char === '\"') {\n inQuotes = true;\n quoted = true;\n continue;\n }\n if (char === ',') {\n tokens.push({ value: current, quoted });\n current = '';\n quoted = false;\n continue;\n }\n current += char;\n }\n\n if (inQuotes) return undefined;\n tokens.push({ value: current, quoted });\n return tokens;\n}\n\n/**\n * Parses a Postgres array literal body (`{...}`) into a JS array of primitives.\n * Returns undefined if the body cannot be reliably parsed.\n *\n * Handles:\n * - `{}` → `[]`\n * - `{elem1,elem2,...}` → `[elem1, elem2, ...]` with numeric and string element coercion\n * - quoted elements that contain commas, doubled/escaped quotes, and the literal\n * strings `NULL`/`true`/`false` (a quoted token is always a string)\n */\nfunction parseArrayLiteralBody(body: string): readonly JsonValue[] | undefined {\n const inner = body.slice(1, -1).trim();\n if (inner === '') return [];\n const tokens = splitArrayElements(inner);\n if (tokens === undefined) return undefined;\n const result: JsonValue[] = [];\n for (const token of tokens) {\n if (token.quoted) {\n // A quoted token is always a string — `\"NULL\"`, `\"true\"`, `\"1\"` are the\n // literal text, never the keyword/number.\n result.push(token.value);\n continue;\n }\n const el = token.value.trim();\n if (el.toUpperCase() === 'NULL') {\n result.push(null);\n continue;\n }\n if (el === 'true') {\n result.push(true);\n continue;\n }\n if (el === 'false') {\n result.push(false);\n continue;\n }\n if (NUMERIC_PATTERN.test(el)) {\n result.push(Number(el));\n continue;\n }\n return undefined;\n }\n return result;\n}\n\n/**\n * Parses a raw Postgres column default expression into a normalized ColumnDefault.\n * This enables semantic comparison between contract defaults and introspected schema defaults.\n *\n * Used by the migration diff layer to normalize raw database defaults during comparison,\n * keeping the introspection layer focused on faithful data capture.\n *\n * @param rawDefault - Raw default expression from information_schema.columns.column_default\n * @param nativeType - Native column type, used for type-aware parsing (array, bigint, JSON)\n * @returns Normalized ColumnDefault or undefined if the expression cannot be parsed\n */\nexport function parsePostgresDefault(\n rawDefault: string,\n nativeType?: string,\n): ColumnDefault | undefined {\n const trimmed = rawDefault.trim();\n const normalizedType = nativeType?.toLowerCase();\n const isBigInt = normalizedType === 'bigint' || normalizedType === 'int8';\n const isArrayType = normalizedType?.endsWith('[]') ?? false;\n\n if (NEXTVAL_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'autoincrement()' };\n }\n\n if (isArrayType) {\n const arrayMatch = trimmed.match(ARRAY_LITERAL_PATTERN);\n if (arrayMatch?.[1] !== undefined) {\n const parsed = parseArrayLiteralBody(arrayMatch[1]);\n if (parsed !== undefined) {\n return { kind: 'literal', value: parsed };\n }\n }\n }\n\n const canonicalTimestamp = canonicalizeTimestampDefault(trimmed);\n if (canonicalTimestamp) {\n return { kind: 'function', expression: canonicalTimestamp };\n }\n\n if (UUID_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'gen_random_uuid()' };\n }\n\n if (UUID_OSSP_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'gen_random_uuid()' };\n }\n\n if (NULL_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: null };\n }\n\n if (TRUE_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: true };\n }\n if (FALSE_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: false };\n }\n\n if (NUMERIC_PATTERN.test(trimmed)) {\n const num = Number(trimmed);\n if (!Number.isFinite(num)) return undefined;\n if (isBigInt && !Number.isSafeInteger(num)) {\n return { kind: 'literal', value: trimmed };\n }\n return { kind: 'literal', value: num };\n }\n\n const stringMatch = trimmed.match(STRING_LITERAL_PATTERN);\n if (stringMatch?.[1] !== undefined) {\n const unescaped = stringMatch[1].replace(/''/g, \"'\");\n if (normalizedType === 'json' || normalizedType === 'jsonb') {\n try {\n return { kind: 'literal', value: JSON.parse(unescaped) };\n } catch {\n // Keep legacy behavior for malformed/non-JSON string content.\n }\n }\n if (isBigInt && NUMERIC_PATTERN.test(unescaped)) {\n const num = Number(unescaped);\n if (Number.isSafeInteger(num)) {\n return { kind: 'literal', value: num };\n }\n return { kind: 'literal', value: unescaped };\n }\n return { kind: 'literal', value: unescaped };\n }\n\n return { kind: 'function', expression: trimmed };\n}\n\n/**\n * Normalizes a contract-declared default through {@link parsePostgresDefault}\n * — the same parser introspection uses — so a function-shaped default the\n * parser recognizes as a literal (e.g. `dbgenerated(\"'{}'::jsonb\")`)\n * resolves to the same `resolvedDefault` shape a live introspected column\n * would produce. Compensates once, at `SchemaIR` construction of the\n * expected (contract-derived) side (`contractToSchemaIR`'s `resolveDefault`\n * hook), instead of at every site that later compares the two sides. A\n * literal default, or a function form the parser doesn't recognize, passes\n * through unchanged; `nextval(...)` normalizes to `autoincrement()` on both\n * sides, matching a `serial`/identity column's introspected counterpart.\n */\nexport function postgresResolveDefault(\n def: ColumnDefault,\n resolvedNativeType: string,\n): ColumnDefault {\n if (def.kind !== 'function') {\n return def;\n }\n return parsePostgresDefault(def.expression, resolvedNativeType) ?? def;\n}\n"],"mappings":";;;;;AAMA,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;AAC7B,MAAM,0BAA0B;AAChC,MAAM,wBAAwB;AAC9B,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAC5B,MAAM,eAAe;AACrB,MAAM,oBAAoB;AAC1B,MAAM,eAAe;AACrB,MAAM,eAAe;AACrB,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;AACxB,MAAM,yBAAyB;;;;;;AAO/B,MAAM,wBAAwB;;;;;;;;;;;;;AAc9B,SAAS,6BAA6B,MAAkC;CACtE,IAAI,qBAAqB,KAAK,IAAI,GAAG,OAAO;CAC5C,IAAI,wBAAwB,KAAK,IAAI,GAAG,OAAO;CAE/C,IAAI,CAAC,sBAAsB,KAAK,IAAI,GAAG,OAAO,KAAA;CAE9C,IAAI,QAAQ,KAAK,QAAQ,uBAAuB,EAAE,CAAC,CAAC,KAAK;C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alizer.d.ts
4
3
  /**
5
4
  * Parses a raw Postgres column default expression into a normalized ColumnDefault.
@@ -13,6 +12,19 @@ import { ColumnDefault } from "@prisma-next/contract/types";
13
12
  * @returns Normalized ColumnDefault or undefined if the expression cannot be parsed
14
13
  */
15
14
  declare function parsePostgresDefault(rawDefault: string, nativeType?: string): ColumnDefault | undefined;
15
+ /**
16
+ * Normalizes a contract-declared default through {@link parsePostgresDefault}
17
+ * — the same parser introspection uses — so a function-shaped default the
18
+ * parser recognizes as a literal (e.g. `dbgenerated("'{}'::jsonb")`)
19
+ * resolves to the same `resolvedDefault` shape a live introspected column
20
+ * would produce. Compensates once, at `SchemaIR` construction of the
21
+ * expected (contract-derived) side (`contractToSchemaIR`'s `resolveDefault`
22
+ * hook), instead of at every site that later compares the two sides. A
23
+ * literal default, or a function form the parser doesn't recognize, passes
24
+ * through unchanged; `nextval(...)` normalizes to `autoincrement()` on both
25
+ * sides, matching a `serial`/identity column's introspected counterpart.
26
+ */
27
+ declare function postgresResolveDefault(def: ColumnDefault, resolvedNativeType: string): ColumnDefault;
16
28
  //#endregion
17
- export { parsePostgresDefault };
29
+ export { parsePostgresDefault, postgresResolveDefault };
18
30
  //# sourceMappingURL=default-normalizer.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"default-normalizer.d.mts","names":[],"sources":["../src/core/default-normalizer.ts"],"mappings":";;;;;AA6KA;;;;;;;;AAGgB;iBAHA,oBAAA,CACd,UAAA,UACA,UAAA,YACC,aAAa"}
1
+ {"version":3,"file":"default-normalizer.d.mts","names":[],"sources":["../src/core/default-normalizer.ts"],"mappings":";;;;;;;;;;;;;iBA6KgB,qBACd,oBACA,sBACC;;;;;;;;;;;;;iBAwFa,uBACd,KAAK,eACL,6BACC"}