@prisma-next/target-postgres 0.14.0-dev.9 → 0.14.0-dev.90

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 (266) hide show
  1. package/dist/authoring-BtsOWgI3.mjs +674 -0
  2. package/dist/authoring-BtsOWgI3.mjs.map +1 -0
  3. package/dist/canonicalize-D1F4vUnP.d.mts +48 -0
  4. package/dist/canonicalize-D1F4vUnP.d.mts.map +1 -0
  5. package/dist/{codec-ids-BvytN2P8.mjs → codec-ids-B10ZZHzw.mjs} +4 -2
  6. package/dist/codec-ids-B10ZZHzw.mjs.map +1 -0
  7. package/dist/{codec-ids-CnXu9Qy3.d.mts → codec-ids-CI144z7g.d.mts} +4 -2
  8. package/dist/codec-ids-CI144z7g.d.mts.map +1 -0
  9. package/dist/codec-ids.d.mts +2 -2
  10. package/dist/codec-ids.mjs +2 -2
  11. package/dist/{codec-types-DHCkwPKE.d.mts → codec-types-CTfT4U4O.d.mts} +4 -2
  12. package/dist/codec-types-CTfT4U4O.d.mts.map +1 -0
  13. package/dist/codec-types.d.mts +1 -1
  14. package/dist/{codecs--0A5_4Bq.d.mts → codecs-D7W9O0Xx.d.mts} +134 -4
  15. package/dist/codecs-D7W9O0Xx.d.mts.map +1 -0
  16. package/dist/codecs-DRbb26Or.mjs +955 -0
  17. package/dist/codecs-DRbb26Or.mjs.map +1 -0
  18. package/dist/codecs.d.mts +2 -2
  19. package/dist/codecs.mjs +3 -757
  20. package/dist/codecs.mjs.map +1 -1
  21. package/dist/contract-free.d.mts +33 -3
  22. package/dist/contract-free.d.mts.map +1 -1
  23. package/dist/contract-free.mjs +23 -7
  24. package/dist/contract-free.mjs.map +1 -1
  25. package/dist/control-policy-DtbkLLGv.mjs +1285 -0
  26. package/dist/control-policy-DtbkLLGv.mjs.map +1 -0
  27. package/dist/control.d.mts +2 -2
  28. package/dist/control.d.mts.map +1 -1
  29. package/dist/control.mjs +880 -36
  30. package/dist/control.mjs.map +1 -1
  31. package/dist/data-transform-BOWpliq8.mjs.map +1 -1
  32. package/dist/{data-transform-DDgWdB5o.d.mts → data-transform-DPzwBMhW.d.mts} +3 -3
  33. package/dist/{data-transform-DDgWdB5o.d.mts.map → data-transform-DPzwBMhW.d.mts.map} +1 -1
  34. package/dist/data-transform.d.mts +1 -1
  35. package/dist/{ddl-QDyOSeLc.mjs → ddl-GTTOvjx_.mjs} +128 -6
  36. package/dist/ddl-GTTOvjx_.mjs.map +1 -0
  37. package/dist/ddl.d.mts +3 -2
  38. package/dist/ddl.mjs +2 -2
  39. package/dist/default-normalizer.d.mts +1 -1
  40. package/dist/default-normalizer.d.mts.map +1 -1
  41. package/dist/default-normalizer.mjs +247 -1
  42. package/dist/default-normalizer.mjs.map +1 -0
  43. package/dist/descriptor-meta-CFQKLXl_.mjs +23 -0
  44. package/dist/descriptor-meta-CFQKLXl_.mjs.map +1 -0
  45. package/dist/descriptor-meta-runtime-UwYdV8fD.mjs +12 -0
  46. package/dist/descriptor-meta-runtime-UwYdV8fD.mjs.map +1 -0
  47. package/dist/diff-database-schema-GncqMuSI.mjs +305 -0
  48. package/dist/diff-database-schema-GncqMuSI.mjs.map +1 -0
  49. package/dist/diff-database-schema.d.mts +46 -0
  50. package/dist/diff-database-schema.d.mts.map +1 -0
  51. package/dist/diff-database-schema.mjs +2 -0
  52. package/dist/errors-DO-w0EUS.mjs +35 -0
  53. package/dist/errors-DO-w0EUS.mjs.map +1 -0
  54. package/dist/errors.d.mts +11 -9
  55. package/dist/errors.d.mts.map +1 -1
  56. package/dist/errors.mjs +1 -1
  57. package/dist/issue-planner.d.mts +35 -11
  58. package/dist/issue-planner.d.mts.map +1 -1
  59. package/dist/issue-planner.mjs +2 -2
  60. package/dist/migration.d.mts +5 -5
  61. package/dist/migration.d.mts.map +1 -1
  62. package/dist/migration.mjs +4 -4
  63. package/dist/namespace-ids-xtp_ZY86.mjs +7 -0
  64. package/dist/namespace-ids-xtp_ZY86.mjs.map +1 -0
  65. package/dist/native-type-normalizer.mjs +37 -1
  66. package/dist/native-type-normalizer.mjs.map +1 -0
  67. package/dist/nodes-DJC5B8Id.mjs +192 -0
  68. package/dist/nodes-DJC5B8Id.mjs.map +1 -0
  69. package/dist/nodes-Dv5eCSq9.d.mts +170 -0
  70. package/dist/nodes-Dv5eCSq9.d.mts.map +1 -0
  71. package/dist/{op-factory-call-DmQEc3XV.d.mts → op-factory-call-Bn9zDx4_.d.mts} +114 -15
  72. package/dist/op-factory-call-Bn9zDx4_.d.mts.map +1 -0
  73. package/dist/{op-factory-call-D_p5vxwt.mjs → op-factory-call-C38NzvQD.mjs} +469 -32
  74. package/dist/op-factory-call-C38NzvQD.mjs.map +1 -0
  75. package/dist/op-factory-call.d.mts +2 -2
  76. package/dist/op-factory-call.mjs +2 -2
  77. package/dist/pack.d.mts +321 -3
  78. package/dist/pack.d.mts.map +1 -1
  79. package/dist/pack.mjs +1 -1
  80. package/dist/{planner-ddl-builders-B2wOwLqI.mjs → planner-ddl-builders-BKlmGDJl.mjs} +17 -28
  81. package/dist/planner-ddl-builders-BKlmGDJl.mjs.map +1 -0
  82. package/dist/planner-ddl-builders.d.mts +4 -6
  83. package/dist/planner-ddl-builders.d.mts.map +1 -1
  84. package/dist/planner-ddl-builders.mjs +2 -2
  85. package/dist/planner-identity-values-CJPha2Sz.mjs.map +1 -1
  86. package/dist/planner-identity-values.d.mts +8 -2
  87. package/dist/planner-identity-values.d.mts.map +1 -1
  88. package/dist/planner-identity-values.mjs +2 -2
  89. package/dist/planner-kql24i_F.mjs +390 -0
  90. package/dist/planner-kql24i_F.mjs.map +1 -0
  91. package/dist/{planner-produced-postgres-migration-QqHa2C2l.d.mts → planner-produced-postgres-migration-BEY1T0Xm.d.mts} +4 -4
  92. package/dist/{planner-produced-postgres-migration-QqHa2C2l.d.mts.map → planner-produced-postgres-migration-BEY1T0Xm.d.mts.map} +1 -1
  93. package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs → planner-produced-postgres-migration-D7y-PEHK.mjs} +3 -3
  94. package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs.map → planner-produced-postgres-migration-D7y-PEHK.mjs.map} +1 -1
  95. package/dist/planner-produced-postgres-migration.d.mts +1 -1
  96. package/dist/planner-produced-postgres-migration.mjs +1 -1
  97. package/dist/{planner-sql-checks-jqUUGyQR.mjs → planner-sql-checks-zqNfs2XZ.mjs} +5 -5
  98. package/dist/{planner-sql-checks-jqUUGyQR.mjs.map → planner-sql-checks-zqNfs2XZ.mjs.map} +1 -1
  99. package/dist/planner-sql-checks.d.mts +2 -2
  100. package/dist/planner-sql-checks.d.mts.map +1 -1
  101. package/dist/planner-sql-checks.mjs +1 -1
  102. package/dist/{planner-target-details-CIY6tLeo.d.mts → planner-target-details-HkP4RrRO.d.mts} +2 -2
  103. package/dist/planner-target-details-HkP4RrRO.d.mts.map +1 -0
  104. package/dist/planner-target-details.d.mts +1 -1
  105. package/dist/planner.d.mts +72 -17
  106. package/dist/planner.d.mts.map +1 -1
  107. package/dist/planner.mjs +3 -2
  108. package/dist/postgres-contract-view-C9j5cqP0.d.mts +34 -0
  109. package/dist/postgres-contract-view-C9j5cqP0.d.mts.map +1 -0
  110. package/dist/{postgres-contract-serializer-k3TAcPMY.mjs → postgres-contract-view-DM8sN1Ot.mjs} +45 -41
  111. package/dist/postgres-contract-view-DM8sN1Ot.mjs.map +1 -0
  112. package/dist/postgres-database-schema-node-CJv5bfbs.d.mts +262 -0
  113. package/dist/postgres-database-schema-node-CJv5bfbs.d.mts.map +1 -0
  114. package/dist/{postgres-migration-Y4YBJqkS.d.mts → postgres-migration-DbckK1su.d.mts} +58 -9
  115. package/dist/postgres-migration-DbckK1su.d.mts.map +1 -0
  116. package/dist/{postgres-migration-B5jKrXv3.mjs → postgres-migration-arMSWU9b.mjs} +78 -45
  117. package/dist/postgres-migration-arMSWU9b.mjs.map +1 -0
  118. package/dist/postgres-native-enum-BwVNf0Ku.mjs +45 -0
  119. package/dist/postgres-native-enum-BwVNf0Ku.mjs.map +1 -0
  120. package/dist/postgres-rls-policy--CSddvMR.d.mts +52 -0
  121. package/dist/postgres-rls-policy--CSddvMR.d.mts.map +1 -0
  122. package/dist/postgres-role-schema-node-Cm-j0ZGM.mjs +190 -0
  123. package/dist/postgres-role-schema-node-Cm-j0ZGM.mjs.map +1 -0
  124. package/dist/{postgres-schema-COGZ1ark.mjs → postgres-schema-Cm4DtiGA.mjs} +200 -11
  125. package/dist/postgres-schema-Cm4DtiGA.mjs.map +1 -0
  126. package/dist/postgres-schema-DKq6s1P3.d.mts +269 -0
  127. package/dist/postgres-schema-DKq6s1P3.d.mts.map +1 -0
  128. package/dist/postgres-table-schema-node-D6LvInCe.mjs +216 -0
  129. package/dist/postgres-table-schema-node-D6LvInCe.mjs.map +1 -0
  130. package/dist/render-ops.d.mts +1 -1
  131. package/dist/{render-typescript-KMgosran.mjs → render-typescript-7yqILcwr.mjs} +45 -16
  132. package/dist/render-typescript-7yqILcwr.mjs.map +1 -0
  133. package/dist/render-typescript.mjs +1 -1
  134. package/dist/resolve-ddl-schema-XyBaaenM.mjs +22 -0
  135. package/dist/resolve-ddl-schema-XyBaaenM.mjs.map +1 -0
  136. package/dist/rls-canonicalize.d.mts +27 -0
  137. package/dist/rls-canonicalize.d.mts.map +1 -0
  138. package/dist/rls-canonicalize.mjs +2 -0
  139. package/dist/runtime.d.mts +6 -8
  140. package/dist/runtime.d.mts.map +1 -1
  141. package/dist/runtime.mjs +3 -3
  142. package/dist/runtime.mjs.map +1 -1
  143. package/dist/schema-ir-annotations.d.mts +15 -0
  144. package/dist/schema-ir-annotations.d.mts.map +1 -0
  145. package/dist/schema-ir-annotations.mjs +2 -0
  146. package/dist/{sql-utils-DcfMz4MQ.mjs → sql-utils-SU4FDvIV.mjs} +12 -3
  147. package/dist/{sql-utils-DcfMz4MQ.mjs.map → sql-utils-SU4FDvIV.mjs.map} +1 -1
  148. package/dist/sql-utils.d.mts +8 -1
  149. package/dist/sql-utils.d.mts.map +1 -1
  150. package/dist/sql-utils.mjs +2 -2
  151. package/dist/types.d.mts +4 -140
  152. package/dist/types.mjs +5 -2
  153. package/dist/wire-name-DbQ9-2RC.mjs +104 -0
  154. package/dist/wire-name-DbQ9-2RC.mjs.map +1 -0
  155. package/package.json +26 -20
  156. package/src/contract-free/checks.ts +153 -0
  157. package/src/contract-free/control-bootstrap.ts +20 -3
  158. package/src/contract-free/ddl.ts +98 -1
  159. package/src/core/authoring.ts +726 -2
  160. package/src/core/codec-helpers.ts +33 -7
  161. package/src/core/codec-ids.ts +2 -0
  162. package/src/core/codec-type-map.ts +4 -0
  163. package/src/core/codecs.ts +236 -12
  164. package/src/core/ddl/nodes.ts +185 -2
  165. package/src/core/default-normalizer.ts +122 -2
  166. package/src/core/descriptor-meta.ts +12 -1
  167. package/src/core/entity-kinds.ts +41 -0
  168. package/src/core/errors.ts +14 -12
  169. package/src/core/migrations/bound-schema.ts +10 -0
  170. package/src/core/migrations/column-ddl-rendering.ts +117 -0
  171. package/src/core/migrations/contract-to-postgres-database-schema-node.ts +189 -0
  172. package/src/core/migrations/control-policy.ts +217 -65
  173. package/src/core/migrations/diff-database-schema.ts +252 -0
  174. package/src/core/migrations/issue-planner.ts +817 -656
  175. package/src/core/migrations/op-factory-call.ts +383 -23
  176. package/src/core/migrations/operations/columns.ts +24 -12
  177. package/src/core/migrations/operations/constraints.ts +1 -1
  178. package/src/core/migrations/operations/data-transform.ts +6 -0
  179. package/src/core/migrations/operations/dependencies.ts +2 -1
  180. package/src/core/migrations/operations/native-enum-types.ts +62 -0
  181. package/src/core/migrations/operations/rls.ts +187 -0
  182. package/src/core/migrations/operations/shared.ts +0 -30
  183. package/src/core/migrations/planner-ddl-builders.ts +31 -59
  184. package/src/core/migrations/planner-identity-values.ts +1 -1
  185. package/src/core/migrations/planner-recipes.ts +31 -13
  186. package/src/core/migrations/planner-sql-checks.ts +1 -1
  187. package/src/core/migrations/planner-strategies.ts +248 -216
  188. package/src/core/migrations/planner-target-details.ts +3 -1
  189. package/src/core/migrations/planner.ts +357 -67
  190. package/src/core/migrations/postgres-migration.ts +118 -86
  191. package/src/core/migrations/render-typescript.ts +42 -15
  192. package/src/core/migrations/resolve-ddl-schema.ts +26 -0
  193. package/src/core/migrations/runner.ts +11 -16
  194. package/src/core/migrations/verify-postgres-namespaces.ts +46 -31
  195. package/src/core/namespace-ids.ts +3 -0
  196. package/src/core/postgres-contract-serializer.ts +46 -71
  197. package/src/core/postgres-contract-view.ts +48 -0
  198. package/src/core/postgres-native-enum.ts +61 -0
  199. package/src/core/postgres-rls-enablement.ts +34 -0
  200. package/src/core/postgres-rls-policy.ts +64 -0
  201. package/src/core/postgres-role.ts +59 -0
  202. package/src/core/postgres-schema-verifier.ts +10 -7
  203. package/src/core/postgres-schema.ts +85 -15
  204. package/src/core/postgres-validators.ts +34 -0
  205. package/src/core/psl-infer/infer-psl-contract.ts +1290 -0
  206. package/src/core/psl-infer/postgres-default-mapping.ts +16 -0
  207. package/src/core/psl-infer/postgres-type-map.ts +129 -0
  208. package/src/core/rls/canonicalize.ts +65 -0
  209. package/src/core/rls/wire-name.ts +33 -0
  210. package/src/core/schema-ir/node-storage-coordinate.ts +26 -0
  211. package/src/core/schema-ir/postgres-database-schema-node.ts +61 -0
  212. package/src/core/schema-ir/postgres-namespace-schema-node.ts +70 -0
  213. package/src/core/schema-ir/postgres-native-enum-schema-node.ts +83 -0
  214. package/src/core/schema-ir/postgres-policy-schema-node.ts +90 -0
  215. package/src/core/schema-ir/postgres-role-schema-node.ts +65 -0
  216. package/src/core/schema-ir/postgres-table-schema-node.ts +140 -0
  217. package/src/core/schema-ir/schema-node-kinds.ts +122 -0
  218. package/src/core/sql-utils.ts +15 -2
  219. package/src/exports/codecs.ts +5 -0
  220. package/src/exports/contract-free.ts +11 -1
  221. package/src/exports/control.ts +27 -33
  222. package/src/exports/ddl.ts +8 -0
  223. package/src/exports/diff-database-schema.ts +7 -0
  224. package/src/exports/issue-planner.ts +1 -1
  225. package/src/exports/migration.ts +1 -0
  226. package/src/exports/op-factory-call.ts +4 -0
  227. package/src/exports/planner-ddl-builders.ts +0 -2
  228. package/src/exports/planner-identity-values.ts +4 -1
  229. package/src/exports/planner.ts +1 -0
  230. package/src/exports/rls-canonicalize.ts +12 -0
  231. package/src/exports/runtime.ts +1 -0
  232. package/src/exports/schema-ir-annotations.ts +1 -0
  233. package/src/exports/sql-utils.ts +1 -0
  234. package/src/exports/types.ts +37 -0
  235. package/dist/codec-ids-BvytN2P8.mjs.map +0 -1
  236. package/dist/codec-ids-CnXu9Qy3.d.mts.map +0 -1
  237. package/dist/codec-types-DHCkwPKE.d.mts.map +0 -1
  238. package/dist/codecs--0A5_4Bq.d.mts.map +0 -1
  239. package/dist/ddl-QDyOSeLc.mjs.map +0 -1
  240. package/dist/default-normalizer-DyyCHQWs.mjs +0 -131
  241. package/dist/default-normalizer-DyyCHQWs.mjs.map +0 -1
  242. package/dist/descriptor-meta-CpGygXpI.mjs +0 -140
  243. package/dist/descriptor-meta-CpGygXpI.mjs.map +0 -1
  244. package/dist/errors-CUk87ByX.mjs +0 -33
  245. package/dist/errors-CUk87ByX.mjs.map +0 -1
  246. package/dist/issue-planner-DL6g3CmE.mjs +0 -824
  247. package/dist/issue-planner-DL6g3CmE.mjs.map +0 -1
  248. package/dist/native-type-normalizer-Bc9XJzWC.mjs +0 -38
  249. package/dist/native-type-normalizer-Bc9XJzWC.mjs.map +0 -1
  250. package/dist/nodes-Bbhs2rwj.mjs +0 -76
  251. package/dist/nodes-Bbhs2rwj.mjs.map +0 -1
  252. package/dist/nodes-pLeLgdis.d.mts +0 -67
  253. package/dist/nodes-pLeLgdis.d.mts.map +0 -1
  254. package/dist/op-factory-call-D_p5vxwt.mjs.map +0 -1
  255. package/dist/op-factory-call-DmQEc3XV.d.mts.map +0 -1
  256. package/dist/planner-Bs_baQax.mjs +0 -324
  257. package/dist/planner-Bs_baQax.mjs.map +0 -1
  258. package/dist/planner-ddl-builders-B2wOwLqI.mjs.map +0 -1
  259. package/dist/planner-target-details-CIY6tLeo.d.mts.map +0 -1
  260. package/dist/postgres-contract-serializer-k3TAcPMY.mjs.map +0 -1
  261. package/dist/postgres-migration-B5jKrXv3.mjs.map +0 -1
  262. package/dist/postgres-migration-Y4YBJqkS.d.mts.map +0 -1
  263. package/dist/postgres-schema-COGZ1ark.mjs.map +0 -1
  264. package/dist/render-typescript-KMgosran.mjs.map +0 -1
  265. package/dist/types.d.mts.map +0 -1
  266. package/src/core/postgres-enum-type-schema.ts +0 -17
@@ -0,0 +1,305 @@
1
+ import { r as isPostgresSchema } from "./postgres-schema-Cm4DtiGA.mjs";
2
+ import { a as postgresDiffSubjectGranularity, n as PostgresNativeEnumSchemaNode, t as PostgresTableSchemaNode } from "./postgres-table-schema-node-D6LvInCe.mjs";
3
+ import { i as PostgresDatabaseSchemaNode, n as PostgresPolicySchemaNode, r as PostgresNamespaceSchemaNode, t as PostgresRoleSchemaNode } from "./postgres-role-schema-node-Cm-j0ZGM.mjs";
4
+ import { t as resolveDdlSchemaForNamespaceStorage } from "./resolve-ddl-schema-XyBaaenM.mjs";
5
+ import { i as resolvePostgresNodeIssueControlPolicySubject } from "./control-policy-DtbkLLGv.mjs";
6
+ import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
7
+ import { blindCast } from "@prisma-next/utils/casts";
8
+ import { buildNativeTypeExpander, contractNamespaceToSchemaIR } from "@prisma-next/family-sql/control";
9
+ import { ifDefined } from "@prisma-next/utils/defined";
10
+ import { SqlForeignKeyIR } from "@prisma-next/sql-schema-ir/types";
11
+ import { classifyDiffSubjectGranularity } from "@prisma-next/family-sql/diff";
12
+ import { diffSchemas } from "@prisma-next/framework-components/control";
13
+ //#region src/core/migrations/contract-to-postgres-database-schema-node.ts
14
+ function toPolicyNode(policy, namespaceId) {
15
+ return new PostgresPolicySchemaNode({
16
+ name: policy.name,
17
+ prefix: policy.prefix,
18
+ tableName: policy.tableName,
19
+ namespaceId,
20
+ operation: policy.operation,
21
+ roles: [...policy.roles],
22
+ ...ifDefined("using", policy.using),
23
+ ...ifDefined("withCheck", policy.withCheck),
24
+ permissive: policy.permissive
25
+ });
26
+ }
27
+ /**
28
+ * Projects a Postgres contract into the expected schema-diff tree: a
29
+ * `PostgresDatabaseSchemaNode` root holding one `PostgresNamespaceSchemaNode`
30
+ * per Postgres namespace, each holding its `PostgresTableSchemaNode`s with
31
+ * their `PostgresPolicySchemaNode`s, plus the database roles on the root.
32
+ *
33
+ * Not a duplicate of the family's `contractToSchemaIR`: that builds a flat,
34
+ * single `{ tables }` map (and throws on cross-namespace name collisions, with
35
+ * no RLS/role concept) for SQLite's single-schema world. This is the
36
+ * Postgres-specific *tree* shape — multi-schema, RLS-policy-aware, role-aware.
37
+ * It reuses the family's per-namespace table conversion (`contractNamespaceToSchemaIR`)
38
+ * for column/FK/index building and only adds the Postgres tree/policy/role shape.
39
+ *
40
+ * Tables are grouped by their owning namespace (resolved DDL schema name) so
41
+ * the tree mirrors Postgres's object hierarchy. The DDL schema name is
42
+ * resolved once per namespace.
43
+ *
44
+ * A policy that references a table absent from its namespace is a malformed
45
+ * contract — the loop throws rather than fabricating a stub table.
46
+ */
47
+ function contractToPostgresDatabaseSchemaNode(contract, options) {
48
+ if (contract === null) return new PostgresDatabaseSchemaNode({
49
+ namespaces: {},
50
+ roles: [],
51
+ existingSchemas: [],
52
+ pgVersion: ""
53
+ });
54
+ const namespaces = {};
55
+ const roles = [];
56
+ const ownedSchemas = [];
57
+ for (const ns of Object.values(contract.storage.namespaces)) {
58
+ if (!isPostgresSchema(ns)) continue;
59
+ for (const role of Object.values(ns.role)) roles.push(new PostgresRoleSchemaNode({
60
+ name: role.name,
61
+ namespaceId: role.namespaceId
62
+ }));
63
+ if (ns.id === UNBOUND_NAMESPACE_ID) {
64
+ if (!Object.entries(ns.entries).some(([entriesKey, slot]) => entriesKey !== "role" && Object.keys(slot).length > 0)) continue;
65
+ }
66
+ const ddlSchema = resolveDdlSchemaForNamespaceStorage(contract.storage, ns.id);
67
+ ownedSchemas.push(ddlSchema);
68
+ const sqlTables = contractNamespaceToSchemaIR(contract.storage, ns.id, options).tables;
69
+ const policiesByTable = /* @__PURE__ */ new Map();
70
+ for (const policy of Object.values(ns.policy)) {
71
+ const list = policiesByTable.get(policy.tableName) ?? [];
72
+ list.push(toPolicyNode(policy, ddlSchema));
73
+ policiesByTable.set(policy.tableName, list);
74
+ }
75
+ const tables = {};
76
+ for (const tableName of Object.keys(ns.table)) {
77
+ const sqlTable = sqlTables[tableName];
78
+ if (sqlTable === void 0) continue;
79
+ const foreignKeys = sqlTable.foreignKeys.map((fk) => new SqlForeignKeyIR({
80
+ columns: fk.columns,
81
+ referencedTable: fk.referencedTable,
82
+ referencedColumns: fk.referencedColumns,
83
+ referencedSchema: fk.referencedSchema ?? UNBOUND_NAMESPACE_ID,
84
+ ...ifDefined("name", fk.name),
85
+ ...ifDefined("onDelete", fk.onDelete),
86
+ ...ifDefined("onUpdate", fk.onUpdate),
87
+ ...ifDefined("annotations", fk.annotations),
88
+ resolvedReferencedNamespace: resolveDdlSchemaForNamespaceStorage(contract.storage, fk.referencedSchema ?? UNBOUND_NAMESPACE_ID)
89
+ }));
90
+ tables[tableName] = new PostgresTableSchemaNode({
91
+ name: sqlTable.name,
92
+ columns: sqlTable.columns,
93
+ foreignKeys,
94
+ uniques: sqlTable.uniques,
95
+ indexes: sqlTable.indexes,
96
+ ...ifDefined("primaryKey", sqlTable.primaryKey),
97
+ ...ifDefined("annotations", sqlTable.annotations),
98
+ ...ifDefined("checks", sqlTable.checks),
99
+ policies: policiesByTable.get(tableName) ?? [],
100
+ rlsEnabled: Object.hasOwn(ns.rls, tableName)
101
+ });
102
+ }
103
+ for (const [tableName, tablePolicies] of policiesByTable) {
104
+ if (!(tableName in tables)) {
105
+ const policyName = tablePolicies[0]?.name ?? "(unknown)";
106
+ throw new Error(`contract-to-postgres-database-schema-node: policy "${policyName}" references table "${tableName}" not present in namespace "${ddlSchema}"`);
107
+ }
108
+ if (!Object.hasOwn(ns.rls, tableName)) {
109
+ const policyPrefix = tablePolicies[0]?.prefix ?? "(unknown)";
110
+ throw new Error(`contract-to-postgres-database-schema-node: policy "${policyPrefix}" targets table "${tableName}" in namespace "${ddlSchema}", which is not RLS-controlled. Mark the model with @@rls (entries.rls["${tableName}"]) or remove the policy.`);
111
+ }
112
+ }
113
+ namespaces[ddlSchema] = new PostgresNamespaceSchemaNode({
114
+ schemaName: ddlSchema,
115
+ tables,
116
+ nativeEnums: Object.values(ns.entries.native_enum ?? {}).map((entity) => new PostgresNativeEnumSchemaNode({
117
+ typeName: entity.typeName,
118
+ namespaceId: ddlSchema,
119
+ members: entity.members,
120
+ ...ifDefined("control", entity.control)
121
+ }))
122
+ });
123
+ }
124
+ return new PostgresDatabaseSchemaNode({
125
+ namespaces,
126
+ roles,
127
+ existingSchemas: ownedSchemas,
128
+ pgVersion: ""
129
+ });
130
+ }
131
+ //#endregion
132
+ //#region src/core/migrations/diff-database-schema.ts
133
+ /**
134
+ * Whether a diff issue's subject node is cluster-scoped — it carries its own
135
+ * `namespaceId` field (only role and policy diff nodes do) and that
136
+ * coordinate is the unbound sentinel, meaning the node is not owned by any
137
+ * schema/namespace. A role node is always cluster-scoped (roles are
138
+ * cluster-level objects); a policy node's `namespaceId` is always its
139
+ * table's resolved DDL schema, never the sentinel. Namespace-ownership
140
+ * scoping (which compares `issue.path[1]` against the set of DDL schemas
141
+ * the contract owns) makes no sense for a cluster-scoped subject — its path
142
+ * segment at that index is the object's own name, not a schema name — so
143
+ * such an issue bypasses that scoping entirely.
144
+ */
145
+ function isClusterScopedIssue(issue) {
146
+ const node = issue.expected ?? issue.actual;
147
+ return node !== void 0 && nodeNamespaceId(node) === UNBOUND_NAMESPACE_ID;
148
+ }
149
+ function nodeNamespaceId(node) {
150
+ if (!Object.hasOwn(node, "namespaceId")) return void 0;
151
+ return blindCast(node).namespaceId;
152
+ }
153
+ function ownedSchemaNames(expected) {
154
+ const policyNamespaces = Object.values(expected.namespaces).flatMap((ns) => Object.values(ns.tables).flatMap((t) => t.policies.map((p) => p.namespaceId)));
155
+ return /* @__PURE__ */ new Set([...policyNamespaces, ...expected.existingSchemas]);
156
+ }
157
+ /**
158
+ * Drops contract namespaces that declare no tables from the verdict-diff
159
+ * expected tree and the relational owned-schema set. The legacy relational
160
+ * walk skipped a table-less namespace (e.g. an enums-only schema) before
161
+ * pairing, so neither its DDL schema's absence nor that schema's live
162
+ * relational contents ever reached the verdict — the pruned tree
163
+ * reproduces that. The prune loses no expected policies: policies attach
164
+ * to tables, so a table-less namespace carries none (the projection
165
+ * throws on a policy referencing an absent table). Live policies in a
166
+ * pruned schema remain governed via the full owned set (see
167
+ * {@link diffPostgresSchema}).
168
+ */
169
+ function pruneTableLessNamespaces(expected) {
170
+ const namespaces = Object.fromEntries(Object.entries(expected.namespaces).filter(([, ns]) => Object.keys(ns.tables).length > 0));
171
+ return new PostgresDatabaseSchemaNode({
172
+ namespaces,
173
+ roles: [...expected.roles],
174
+ existingSchemas: expected.existingSchemas.filter((s) => namespaces[s] !== void 0),
175
+ pgVersion: expected.pgVersion
176
+ });
177
+ }
178
+ /**
179
+ * Resolves a verdict-diff issue's subject's declared control policy directly
180
+ * from the contract, by delegating to the same node-typed resolver
181
+ * ({@link resolvePostgresNodeIssueControlPolicySubject}) the planner uses to
182
+ * gate DDL calls. `undefined` when the issue resolves to no contract subject.
183
+ *
184
+ * A role issue resolves through that same resolver to `external`
185
+ * unconditionally (see its role branch), regardless of the contract's own
186
+ * default policy: a role is referenced by the contract but not owned, and
187
+ * `external`'s existing semantics — a missing declared subject still fails,
188
+ * every extra is suppressed — are exactly the wanted asymmetric grading for
189
+ * a cluster object the framework does not own.
190
+ */
191
+ function resolveControlPolicy(issue, contract) {
192
+ return resolvePostgresNodeIssueControlPolicySubject(blindCast(issue), contract)?.explicitNodeControlPolicy;
193
+ }
194
+ /**
195
+ * The Postgres full-tree node diff for the family verify verdict: derive
196
+ * the expected tree (resolved leaf values, expander threaded, FK schemas
197
+ * resolved, table-less namespaces pruned), run the generic
198
+ * differ over the trees as derived, and scope out `not-expected` findings under namespaces the
199
+ * contract does not own. Ownership scoping bypasses cluster-scoped subjects
200
+ * (roles today), mirroring the legacy decomposition: relational extras check
201
+ * the PRUNED owned set (the legacy
202
+ * per-namespace walk never visited a table-less namespace, so its live
203
+ * relational contents are invisible), while `structural` extras (RLS
204
+ * policies) check the FULL owned set (the legacy policy diff governed
205
+ * every contract schema regardless of tables — RLS governance does not
206
+ * shrink because a namespace declares no tables). The codec `verifyType`
207
+ * hooks run once per contract namespace with tables against that
208
+ * namespace's paired actual node (the hooks read namespace-scoped state
209
+ * such as `nativeEnums`).
210
+ */
211
+ function diffPostgresSchema(input) {
212
+ const postgresContract = blindCast(input.contract);
213
+ PostgresDatabaseSchemaNode.assert(input.schema);
214
+ const actual = input.schema;
215
+ const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, {
216
+ annotationNamespace: "pg",
217
+ ...ifDefined("expandNativeType", buildNativeTypeExpander(input.frameworkComponents))
218
+ });
219
+ const expected = pruneTableLessNamespaces(fullExpected);
220
+ const relationalOwned = ownedSchemaNames(expected);
221
+ const structuralOwned = ownedSchemaNames(fullExpected);
222
+ return {
223
+ issues: diffSchemas(expected, actual).filter((issue) => {
224
+ if (issue.reason !== "not-expected") return true;
225
+ if (isClusterScopedIssue(issue)) return true;
226
+ const granularity = classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity);
227
+ const namespaceSegment = issue.path[1];
228
+ if (namespaceSegment === void 0) return true;
229
+ return (granularity === "structural" ? structuralOwned : relationalOwned).has(namespaceSegment);
230
+ }),
231
+ resolveControlPolicy: (issue) => resolveControlPolicy(issue, postgresContract),
232
+ namespacePairs: Object.values(expected.namespaces).map((ns) => ({ actual: actual.namespaces[ns.schemaName] }))
233
+ };
234
+ }
235
+ /**
236
+ * Adds an empty namespace node to the actual tree for every expected namespace
237
+ * absent from it. The relational plan diff pairs on namespace: a contract
238
+ * namespace whose live schema does not exist yet must surface each of its
239
+ * tables as `not-found` (→ `CREATE TABLE`), NOT as a single namespace
240
+ * `not-found` that subtree-coalescing would collapse (leaving `CREATE SCHEMA`
241
+ * with no tables). Padding makes the namespaces pair, so only table/column/
242
+ * policy drift surfaces; `CREATE SCHEMA` comes separately from the synthesized
243
+ * namespace-presence stitch (`verifyPostgresNamespacePresence`), never from the
244
+ * tree diff — matching the retired per-namespace-paired relational walk, which
245
+ * paired a missing schema against an empty namespace node.
246
+ */
247
+ function padActualNamespaces(expected, actual) {
248
+ const namespaces = { ...actual.namespaces };
249
+ let padded = false;
250
+ for (const schemaName of Object.keys(expected.namespaces)) if (namespaces[schemaName] === void 0) {
251
+ namespaces[schemaName] = new PostgresNamespaceSchemaNode({
252
+ schemaName,
253
+ tables: {}
254
+ });
255
+ padded = true;
256
+ }
257
+ if (!padded) return actual;
258
+ return new PostgresDatabaseSchemaNode({
259
+ namespaces,
260
+ roles: [...actual.roles],
261
+ existingSchemas: [...actual.existingSchemas],
262
+ pgVersion: actual.pgVersion
263
+ });
264
+ }
265
+ /**
266
+ * The Postgres planner's diff input: the SAME tree-building
267
+ * `diffPostgresSchema` uses (expander threaded, FK schemas resolved,
268
+ * table-less namespaces pruned, cluster-scope-aware ownership filter) plus
269
+ * actual namespace padding (so a missing
270
+ * schema's tables surface as `not-found` instead of a swallowed namespace
271
+ * `not-found`). One differ drives both verify and plan; this is the
272
+ * plan-side derivation. The single issue list covers tables / columns /
273
+ * constraints / indexes / defaults AND policies — the caller splits it
274
+ * (relational → `mapNodeIssueToCall`; policy → RLS ops) and stitches in
275
+ * `CREATE SCHEMA` separately.
276
+ */
277
+ function buildPostgresPlanDiff(input) {
278
+ const postgresContract = blindCast(input.contract);
279
+ PostgresDatabaseSchemaNode.assert(input.actualSchema);
280
+ const actual = input.actualSchema;
281
+ const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, {
282
+ annotationNamespace: "pg",
283
+ ...ifDefined("expandNativeType", buildNativeTypeExpander(input.frameworkComponents))
284
+ });
285
+ const expected = pruneTableLessNamespaces(fullExpected);
286
+ const paddedActual = padActualNamespaces(expected, actual);
287
+ const relationalOwned = ownedSchemaNames(expected);
288
+ const structuralOwned = ownedSchemaNames(fullExpected);
289
+ return {
290
+ expected,
291
+ actual: paddedActual,
292
+ issues: blindCast(diffSchemas(expected, paddedActual)).filter((issue) => {
293
+ if (issue.reason !== "not-expected") return true;
294
+ if (isClusterScopedIssue(issue)) return true;
295
+ const granularity = classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity);
296
+ const namespaceSegment = issue.path[1];
297
+ if (namespaceSegment === void 0) return true;
298
+ return (granularity === "structural" ? structuralOwned : relationalOwned).has(namespaceSegment);
299
+ })
300
+ };
301
+ }
302
+ //#endregion
303
+ export { diffPostgresSchema as n, contractToPostgresDatabaseSchemaNode as r, buildPostgresPlanDiff as t };
304
+
305
+ //# sourceMappingURL=diff-database-schema-GncqMuSI.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diff-database-schema-GncqMuSI.mjs","names":[],"sources":["../src/core/migrations/contract-to-postgres-database-schema-node.ts","../src/core/migrations/diff-database-schema.ts"],"sourcesContent":["import type { ContractToSchemaIROptions } from '@prisma-next/family-sql/control';\nimport { contractNamespaceToSchemaIR } from '@prisma-next/family-sql/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport { SqlForeignKeyIR } from '@prisma-next/sql-schema-ir/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresRlsPolicy } from '../postgres-rls-policy';\nimport type { PostgresContract } from '../postgres-schema';\nimport { isPostgresSchema } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport { PostgresNativeEnumSchemaNode } from '../schema-ir/postgres-native-enum-schema-node';\nimport { PostgresPolicySchemaNode } from '../schema-ir/postgres-policy-schema-node';\nimport { PostgresRoleSchemaNode } from '../schema-ir/postgres-role-schema-node';\nimport { PostgresTableSchemaNode } from '../schema-ir/postgres-table-schema-node';\nimport { resolveDdlSchemaForNamespaceStorage } from './resolve-ddl-schema';\n\nfunction toPolicyNode(policy: PostgresRlsPolicy, namespaceId: string): PostgresPolicySchemaNode {\n return new PostgresPolicySchemaNode({\n name: policy.name,\n prefix: policy.prefix,\n tableName: policy.tableName,\n namespaceId,\n operation: policy.operation,\n roles: [...policy.roles],\n ...ifDefined('using', policy.using),\n ...ifDefined('withCheck', policy.withCheck),\n permissive: policy.permissive,\n });\n}\n\n/**\n * Projects a Postgres contract into the expected schema-diff tree: a\n * `PostgresDatabaseSchemaNode` root holding one `PostgresNamespaceSchemaNode`\n * per Postgres namespace, each holding its `PostgresTableSchemaNode`s with\n * their `PostgresPolicySchemaNode`s, plus the database roles on the root.\n *\n * Not a duplicate of the family's `contractToSchemaIR`: that builds a flat,\n * single `{ tables }` map (and throws on cross-namespace name collisions, with\n * no RLS/role concept) for SQLite's single-schema world. This is the\n * Postgres-specific *tree* shape — multi-schema, RLS-policy-aware, role-aware.\n * It reuses the family's per-namespace table conversion (`contractNamespaceToSchemaIR`)\n * for column/FK/index building and only adds the Postgres tree/policy/role shape.\n *\n * Tables are grouped by their owning namespace (resolved DDL schema name) so\n * the tree mirrors Postgres's object hierarchy. The DDL schema name is\n * resolved once per namespace.\n *\n * A policy that references a table absent from its namespace is a malformed\n * contract — the loop throws rather than fabricating a stub table.\n */\nexport function contractToPostgresDatabaseSchemaNode(\n contract: PostgresContract | null,\n options: ContractToSchemaIROptions,\n): PostgresDatabaseSchemaNode {\n if (contract === null) {\n return new PostgresDatabaseSchemaNode({\n namespaces: {},\n roles: [],\n existingSchemas: [],\n pgVersion: '',\n });\n }\n\n const namespaces: Record<string, PostgresNamespaceSchemaNode> = {};\n const roles: PostgresRoleSchemaNode[] = [];\n const ownedSchemas: string[] = [];\n\n for (const ns of Object.values(contract.storage.namespaces)) {\n if (!isPostgresSchema(ns)) continue;\n\n // Role entries are root-level diff subjects: they hoist to the database\n // root from every slot and never count toward whether a namespace\n // materializes a schema node.\n for (const role of Object.values(ns.role)) {\n roles.push(new PostgresRoleSchemaNode({ name: role.name, namespaceId: role.namespaceId }));\n }\n\n // The unbound slot resolves its DDL schema to 'public', so it\n // materializes a schema node exactly when it has non-role content — a\n // late-binding contract keeps today's behavior (the slot carries the\n // tables), while a roles-only unbound slot alongside named namespaces\n // contributes only root roles and no node (which would otherwise be a\n // spurious empty 'public' node, clobbering a real bound 'public'\n // namespace's node keyed by the same resolved schema name).\n if (ns.id === UNBOUND_NAMESPACE_ID) {\n const hasNonRoleContent = Object.entries(ns.entries).some(\n ([entriesKey, slot]) => entriesKey !== 'role' && Object.keys(slot).length > 0,\n );\n if (!hasNonRoleContent) continue;\n }\n\n const ddlSchema = resolveDdlSchemaForNamespaceStorage(contract.storage, ns.id);\n ownedSchemas.push(ddlSchema);\n\n // Convert only THIS namespace's tables (passing the full storage for\n // type/value-set/enum resolution that spans namespaces), so the same table\n // name can exist in two schemas without colliding in a bare-keyed record.\n const sqlTables = contractNamespaceToSchemaIR(contract.storage, ns.id, options).tables;\n\n const policiesByTable = new Map<string, PostgresPolicySchemaNode[]>();\n for (const policy of Object.values(ns.policy)) {\n const list = policiesByTable.get(policy.tableName) ?? [];\n list.push(toPolicyNode(policy, ddlSchema));\n policiesByTable.set(policy.tableName, list);\n }\n\n const tables: Record<string, PostgresTableSchemaNode> = {};\n for (const tableName of Object.keys(ns.table)) {\n const sqlTable = sqlTables[tableName];\n if (sqlTable === undefined) continue;\n // The family conversion stamps `referencedSchema` only for bound FK\n // targets; an absent value means the FK targets the unbound namespace.\n // Postgres restores its own coordinate for that slot (the unbound\n // singleton's id) so the raw coordinate keeps qualifying REFERENCES\n // clauses, and resolves the real live DDL schema — introspected FKs\n // already carry the live schema, so this is what lets an expected FK\n // pair (by diff-node id) with its introspected counterpart.\n const foreignKeys = sqlTable.foreignKeys.map(\n (fk) =>\n new SqlForeignKeyIR({\n columns: fk.columns,\n referencedTable: fk.referencedTable,\n referencedColumns: fk.referencedColumns,\n referencedSchema: fk.referencedSchema ?? UNBOUND_NAMESPACE_ID,\n ...ifDefined('name', fk.name),\n ...ifDefined('onDelete', fk.onDelete),\n ...ifDefined('onUpdate', fk.onUpdate),\n ...ifDefined('annotations', fk.annotations),\n resolvedReferencedNamespace: resolveDdlSchemaForNamespaceStorage(\n contract.storage,\n fk.referencedSchema ?? UNBOUND_NAMESPACE_ID,\n ),\n }),\n );\n tables[tableName] = new PostgresTableSchemaNode({\n name: sqlTable.name,\n columns: sqlTable.columns,\n foreignKeys,\n uniques: sqlTable.uniques,\n indexes: sqlTable.indexes,\n ...ifDefined('primaryKey', sqlTable.primaryKey),\n ...ifDefined('annotations', sqlTable.annotations),\n ...ifDefined('checks', sqlTable.checks),\n policies: policiesByTable.get(tableName) ?? [],\n // Marker-driven, never derived from the policy set: the `rls` entry\n // is the single authored source of enablement.\n rlsEnabled: Object.hasOwn(ns.rls, tableName),\n });\n }\n\n for (const [tableName, tablePolicies] of policiesByTable) {\n if (!(tableName in tables)) {\n const policyName = tablePolicies[0]?.name ?? '(unknown)';\n throw new Error(\n `contract-to-postgres-database-schema-node: policy \"${policyName}\" references table \"${tableName}\" not present in namespace \"${ddlSchema}\"`,\n );\n }\n if (!Object.hasOwn(ns.rls, tableName)) {\n const policyPrefix = tablePolicies[0]?.prefix ?? '(unknown)';\n throw new Error(\n `contract-to-postgres-database-schema-node: policy \"${policyPrefix}\" targets table \"${tableName}\" in namespace \"${ddlSchema}\", which is not RLS-controlled. Mark the model with @@rls (entries.rls[\"${tableName}\"]) or remove the policy.`,\n );\n }\n }\n\n const nativeEnums = Object.values(ns.entries.native_enum ?? {}).map(\n (entity) =>\n new PostgresNativeEnumSchemaNode({\n typeName: entity.typeName,\n namespaceId: ddlSchema,\n members: entity.members,\n ...ifDefined('control', entity.control),\n }),\n );\n\n namespaces[ddlSchema] = new PostgresNamespaceSchemaNode({\n schemaName: ddlSchema,\n tables,\n nativeEnums,\n });\n }\n\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles,\n existingSchemas: ownedSchemas,\n pgVersion: '',\n });\n}\n","import type { Contract, ControlPolicy } from '@prisma-next/contract/types';\nimport type { SqlSchemaDiffResult } from '@prisma-next/family-sql/control';\nimport { buildNativeTypeExpander } from '@prisma-next/family-sql/control';\nimport { classifyDiffSubjectGranularity } from '@prisma-next/family-sql/diff';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { DiffableNode, SchemaDiffIssue } from '@prisma-next/framework-components/control';\nimport { diffSchemas } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIRNode } from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresContract } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport {\n postgresDiffSubjectGranularity,\n type SqlSchemaDiffNode,\n} from '../schema-ir/schema-node-kinds';\nimport { contractToPostgresDatabaseSchemaNode } from './contract-to-postgres-database-schema-node';\nimport { resolvePostgresNodeIssueControlPolicySubject } from './control-policy';\n\n/**\n * Whether a diff issue's subject node is cluster-scoped — it carries its own\n * `namespaceId` field (only role and policy diff nodes do) and that\n * coordinate is the unbound sentinel, meaning the node is not owned by any\n * schema/namespace. A role node is always cluster-scoped (roles are\n * cluster-level objects); a policy node's `namespaceId` is always its\n * table's resolved DDL schema, never the sentinel. Namespace-ownership\n * scoping (which compares `issue.path[1]` against the set of DDL schemas\n * the contract owns) makes no sense for a cluster-scoped subject — its path\n * segment at that index is the object's own name, not a schema name — so\n * such an issue bypasses that scoping entirely.\n */\nfunction isClusterScopedIssue(issue: SchemaDiffIssue): boolean {\n const node = issue.expected ?? issue.actual;\n return node !== undefined && nodeNamespaceId(node) === UNBOUND_NAMESPACE_ID;\n}\n\nfunction nodeNamespaceId(node: DiffableNode): string | undefined {\n if (!Object.hasOwn(node, 'namespaceId')) return undefined;\n return blindCast<\n { namespaceId: string },\n 'presence of an own namespaceId field was just checked via Object.hasOwn'\n >(node).namespaceId;\n}\n\nfunction ownedSchemaNames(expected: PostgresDatabaseSchemaNode): ReadonlySet<string> {\n const policyNamespaces = Object.values(expected.namespaces).flatMap((ns) =>\n Object.values(ns.tables).flatMap((t) => t.policies.map((p) => p.namespaceId)),\n );\n return new Set([...policyNamespaces, ...expected.existingSchemas]);\n}\n\n/**\n * Drops contract namespaces that declare no tables from the verdict-diff\n * expected tree and the relational owned-schema set. The legacy relational\n * walk skipped a table-less namespace (e.g. an enums-only schema) before\n * pairing, so neither its DDL schema's absence nor that schema's live\n * relational contents ever reached the verdict — the pruned tree\n * reproduces that. The prune loses no expected policies: policies attach\n * to tables, so a table-less namespace carries none (the projection\n * throws on a policy referencing an absent table). Live policies in a\n * pruned schema remain governed via the full owned set (see\n * {@link diffPostgresSchema}).\n */\nfunction pruneTableLessNamespaces(\n expected: PostgresDatabaseSchemaNode,\n): PostgresDatabaseSchemaNode {\n const namespaces = Object.fromEntries(\n Object.entries(expected.namespaces).filter(([, ns]) => Object.keys(ns.tables).length > 0),\n );\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles: [...expected.roles],\n existingSchemas: expected.existingSchemas.filter((s) => namespaces[s] !== undefined),\n pgVersion: expected.pgVersion,\n });\n}\n\n/**\n * Resolves a verdict-diff issue's subject's declared control policy directly\n * from the contract, by delegating to the same node-typed resolver\n * ({@link resolvePostgresNodeIssueControlPolicySubject}) the planner uses to\n * gate DDL calls. `undefined` when the issue resolves to no contract subject.\n *\n * A role issue resolves through that same resolver to `external`\n * unconditionally (see its role branch), regardless of the contract's own\n * default policy: a role is referenced by the contract but not owned, and\n * `external`'s existing semantics — a missing declared subject still fails,\n * every extra is suppressed — are exactly the wanted asymmetric grading for\n * a cluster object the framework does not own.\n */\nfunction resolveControlPolicy(\n issue: SchemaDiffIssue,\n contract: Contract<SqlStorage>,\n): ControlPolicy | undefined {\n const nodeIssue = blindCast<\n SchemaDiffIssue<SqlSchemaDiffNode>,\n 'every node in a Postgres schema diff tree is a SqlSchemaDiffNode'\n >(issue);\n return resolvePostgresNodeIssueControlPolicySubject(nodeIssue, contract)\n ?.explicitNodeControlPolicy;\n}\n\n/**\n * The Postgres full-tree node diff for the family verify verdict: derive\n * the expected tree (resolved leaf values, expander threaded, FK schemas\n * resolved, table-less namespaces pruned), run the generic\n * differ over the trees as derived, and scope out `not-expected` findings under namespaces the\n * contract does not own. Ownership scoping bypasses cluster-scoped subjects\n * (roles today), mirroring the legacy decomposition: relational extras check\n * the PRUNED owned set (the legacy\n * per-namespace walk never visited a table-less namespace, so its live\n * relational contents are invisible), while `structural` extras (RLS\n * policies) check the FULL owned set (the legacy policy diff governed\n * every contract schema regardless of tables — RLS governance does not\n * shrink because a namespace declares no tables). The codec `verifyType`\n * hooks run once per contract namespace with tables against that\n * namespace's paired actual node (the hooks read namespace-scoped state\n * such as `nativeEnums`).\n */\nexport function diffPostgresSchema(input: {\n readonly contract: Contract<SqlStorage>;\n readonly schema: SqlSchemaIRNode;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}): SqlSchemaDiffResult {\n const postgresContract = blindCast<\n PostgresContract,\n 'diffPostgresSchema is only called with a postgres contract'\n >(input.contract);\n PostgresDatabaseSchemaNode.assert(input.schema);\n const actual = input.schema;\n const expandNativeType = buildNativeTypeExpander(input.frameworkComponents);\n const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expandNativeType),\n });\n const expected = pruneTableLessNamespaces(fullExpected);\n const relationalOwned = ownedSchemaNames(expected);\n const structuralOwned = ownedSchemaNames(fullExpected);\n const issues = diffSchemas(expected, actual).filter((issue) => {\n if (issue.reason !== 'not-expected') return true;\n if (isClusterScopedIssue(issue)) return true;\n const granularity = classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity);\n const namespaceSegment = issue.path[1];\n if (namespaceSegment === undefined) return true;\n const owned = granularity === 'structural' ? structuralOwned : relationalOwned;\n return owned.has(namespaceSegment);\n });\n const namespacePairs = Object.values(expected.namespaces).map((ns) => ({\n actual: actual.namespaces[ns.schemaName],\n }));\n return {\n issues,\n resolveControlPolicy: (issue) => resolveControlPolicy(issue, postgresContract),\n namespacePairs,\n };\n}\n\n/**\n * Adds an empty namespace node to the actual tree for every expected namespace\n * absent from it. The relational plan diff pairs on namespace: a contract\n * namespace whose live schema does not exist yet must surface each of its\n * tables as `not-found` (→ `CREATE TABLE`), NOT as a single namespace\n * `not-found` that subtree-coalescing would collapse (leaving `CREATE SCHEMA`\n * with no tables). Padding makes the namespaces pair, so only table/column/\n * policy drift surfaces; `CREATE SCHEMA` comes separately from the synthesized\n * namespace-presence stitch (`verifyPostgresNamespacePresence`), never from the\n * tree diff — matching the retired per-namespace-paired relational walk, which\n * paired a missing schema against an empty namespace node.\n */\nfunction padActualNamespaces(\n expected: PostgresDatabaseSchemaNode,\n actual: PostgresDatabaseSchemaNode,\n): PostgresDatabaseSchemaNode {\n const namespaces: Record<string, PostgresNamespaceSchemaNode> = { ...actual.namespaces };\n let padded = false;\n for (const schemaName of Object.keys(expected.namespaces)) {\n if (namespaces[schemaName] === undefined) {\n namespaces[schemaName] = new PostgresNamespaceSchemaNode({\n schemaName,\n tables: {},\n });\n padded = true;\n }\n }\n if (!padded) return actual;\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles: [...actual.roles],\n existingSchemas: [...actual.existingSchemas],\n pgVersion: actual.pgVersion,\n });\n}\n\nexport interface PostgresPlanDiff {\n /** The desired (\"end\") tree — resolved leaf values (incl. `codecRef`) on every column, table-less namespaces pruned. */\n readonly expected: PostgresDatabaseSchemaNode;\n /** The live (\"start\") tree, padded with empty namespaces so a missing schema's tables pair. */\n readonly actual: PostgresDatabaseSchemaNode;\n /** The one node diff over the two trees: relational + policy drift, cluster-scope-aware ownership filtered. */\n readonly issues: readonly SchemaDiffIssue<SqlSchemaDiffNode>[];\n}\n\n/**\n * The Postgres planner's diff input: the SAME tree-building\n * `diffPostgresSchema` uses (expander threaded, FK schemas resolved,\n * table-less namespaces pruned, cluster-scope-aware ownership filter) plus\n * actual namespace padding (so a missing\n * schema's tables surface as `not-found` instead of a swallowed namespace\n * `not-found`). One differ drives both verify and plan; this is the\n * plan-side derivation. The single issue list covers tables / columns /\n * constraints / indexes / defaults AND policies — the caller splits it\n * (relational → `mapNodeIssueToCall`; policy → RLS ops) and stitches in\n * `CREATE SCHEMA` separately.\n */\nexport function buildPostgresPlanDiff(input: {\n readonly contract: Contract<SqlStorage>;\n readonly actualSchema: SqlSchemaIRNode;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}): PostgresPlanDiff {\n const postgresContract = blindCast<\n PostgresContract,\n 'buildPostgresPlanDiff is only called with a postgres contract'\n >(input.contract);\n PostgresDatabaseSchemaNode.assert(input.actualSchema);\n const actual = input.actualSchema;\n const expandNativeType = buildNativeTypeExpander(input.frameworkComponents);\n const projectionOptions = {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expandNativeType),\n };\n const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, projectionOptions);\n const expected = pruneTableLessNamespaces(fullExpected);\n const paddedActual = padActualNamespaces(expected, actual);\n const relationalOwned = ownedSchemaNames(expected);\n const structuralOwned = ownedSchemaNames(fullExpected);\n const issues = blindCast<\n readonly SchemaDiffIssue<SqlSchemaDiffNode>[],\n 'both trees are PostgresDatabaseSchemaNodes, so every diff-issue node is a SqlSchemaDiffNode'\n >(diffSchemas(expected, paddedActual)).filter((issue) => {\n if (issue.reason !== 'not-expected') return true;\n if (isClusterScopedIssue(issue)) return true;\n const granularity = classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity);\n const namespaceSegment = issue.path[1];\n if (namespaceSegment === undefined) return true;\n const owned = granularity === 'structural' ? structuralOwned : relationalOwned;\n return owned.has(namespaceSegment);\n });\n return { expected, actual: paddedActual, issues };\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,SAAS,aAAa,QAA2B,aAA+C;CAC9F,OAAO,IAAI,yBAAyB;EAClC,MAAM,OAAO;EACb,QAAQ,OAAO;EACf,WAAW,OAAO;EAClB;EACA,WAAW,OAAO;EAClB,OAAO,CAAC,GAAG,OAAO,KAAK;EACvB,GAAG,UAAU,SAAS,OAAO,KAAK;EAClC,GAAG,UAAU,aAAa,OAAO,SAAS;EAC1C,YAAY,OAAO;CACrB,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,qCACd,UACA,SAC4B;CAC5B,IAAI,aAAa,MACf,OAAO,IAAI,2BAA2B;EACpC,YAAY,CAAC;EACb,OAAO,CAAC;EACR,iBAAiB,CAAC;EAClB,WAAW;CACb,CAAC;CAGH,MAAM,aAA0D,CAAC;CACjE,MAAM,QAAkC,CAAC;CACzC,MAAM,eAAyB,CAAC;CAEhC,KAAK,MAAM,MAAM,OAAO,OAAO,SAAS,QAAQ,UAAU,GAAG;EAC3D,IAAI,CAAC,iBAAiB,EAAE,GAAG;EAK3B,KAAK,MAAM,QAAQ,OAAO,OAAO,GAAG,IAAI,GACtC,MAAM,KAAK,IAAI,uBAAuB;GAAE,MAAM,KAAK;GAAM,aAAa,KAAK;EAAY,CAAC,CAAC;EAU3F,IAAI,GAAG,OAAO;OAIR,CAHsB,OAAO,QAAQ,GAAG,OAAO,CAAC,CAAC,MAClD,CAAC,YAAY,UAAU,eAAe,UAAU,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,CAEzD,GAAG;EAAA;EAG1B,MAAM,YAAY,oCAAoC,SAAS,SAAS,GAAG,EAAE;EAC7E,aAA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,IAAI,gBAAgB;EACnC,CAC8C;CAAE;AAClD"}
@@ -0,0 +1,46 @@
1
+ import { t as PostgresDatabaseSchemaNode } from "./postgres-database-schema-node-CJv5bfbs.mjs";
2
+ import { SqlStorage } from "@prisma-next/sql-contract/types";
3
+ import { SqlSchemaIRNode } from "@prisma-next/sql-schema-ir/types";
4
+ import { DiffableNode, SchemaDiffIssue } from "@prisma-next/framework-components/control";
5
+ import { Contract } from "@prisma-next/contract/types";
6
+ import { TargetBoundComponentDescriptor } from "@prisma-next/framework-components/components";
7
+
8
+ //#region src/core/schema-ir/schema-node-kinds.d.ts
9
+ /**
10
+ * A Postgres schema-diff-tree node: a `SqlSchemaIRNode` that also implements
11
+ * `DiffableNode` (the five `Postgres*SchemaNode` classes). `SqlSchemaIRNode`
12
+ * alone is not a `DiffableNode` — its relational subclasses (`SqlColumnIR`, …)
13
+ * carry no `id`/`isEqualTo`/`children` — so this intersection is the honest node
14
+ * type the differ produces and the planner consumes (`SchemaDiff<SqlSchemaDiffNode>`).
15
+ */
16
+ type SqlSchemaDiffNode = SqlSchemaIRNode & DiffableNode;
17
+ //#endregion
18
+ //#region src/core/migrations/diff-database-schema.d.ts
19
+ interface PostgresPlanDiff {
20
+ /** The desired ("end") tree — resolved leaf values (incl. `codecRef`) on every column, table-less namespaces pruned. */
21
+ readonly expected: PostgresDatabaseSchemaNode;
22
+ /** The live ("start") tree, padded with empty namespaces so a missing schema's tables pair. */
23
+ readonly actual: PostgresDatabaseSchemaNode;
24
+ /** The one node diff over the two trees: relational + policy drift, cluster-scope-aware ownership filtered. */
25
+ readonly issues: readonly SchemaDiffIssue<SqlSchemaDiffNode>[];
26
+ }
27
+ /**
28
+ * The Postgres planner's diff input: the SAME tree-building
29
+ * `diffPostgresSchema` uses (expander threaded, FK schemas resolved,
30
+ * table-less namespaces pruned, cluster-scope-aware ownership filter) plus
31
+ * actual namespace padding (so a missing
32
+ * schema's tables surface as `not-found` instead of a swallowed namespace
33
+ * `not-found`). One differ drives both verify and plan; this is the
34
+ * plan-side derivation. The single issue list covers tables / columns /
35
+ * constraints / indexes / defaults AND policies — the caller splits it
36
+ * (relational → `mapNodeIssueToCall`; policy → RLS ops) and stitches in
37
+ * `CREATE SCHEMA` separately.
38
+ */
39
+ declare function buildPostgresPlanDiff(input: {
40
+ readonly contract: Contract<SqlStorage>;
41
+ readonly actualSchema: SqlSchemaIRNode;
42
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
43
+ }): PostgresPlanDiff;
44
+ //#endregion
45
+ export { buildPostgresPlanDiff };
46
+ //# sourceMappingURL=diff-database-schema.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diff-database-schema.d.mts","names":[],"sources":["../src/core/schema-ir/schema-node-kinds.ts","../src/core/migrations/diff-database-schema.ts"],"mappings":";;;;;;;;;;;;;;;KAiBY,iBAAA,GAAoB,eAAA,GAAkB,YAAY;;;UCmL7C,gBAAA;EAMW;EAAA,SAJjB,QAAA,EAAU,0BAAA;EAIwC;EAAA,SAFlD,MAAA,EAAQ,0BAAA;EAiBH;EAAA,SAfL,MAAA,WAAiB,eAAA,CAAgB,iBAAA;AAAA;;;;;;;;;;;;;iBAe5B,qBAAA,CAAsB,KAAA;EAAA,SAC3B,QAAA,EAAU,QAAA,CAAS,UAAA;EAAA,SACnB,YAAA,EAAc,eAAA;EAAA,SACd,mBAAA,EAAqB,aAAA,CAAc,8BAAA;AAAA,IAC1C,gBAAA"}
@@ -0,0 +1,2 @@
1
+ import { t as buildPostgresPlanDiff } from "./diff-database-schema-GncqMuSI.mjs";
2
+ export { buildPostgresPlanDiff };
@@ -0,0 +1,35 @@
1
+ import { CliStructuredError } from "@prisma-next/errors/control";
2
+ //#region src/core/errors.ts
3
+ /**
4
+ * A `PostgresMigration` operation that needs the materialized control adapter
5
+ * — named by `operation` (e.g. `createTable`, `dropColumn`, `dataTransform`) —
6
+ * was invoked, but the migration was constructed without a `ControlStack`.
7
+ * Concrete authoring usage always goes through the migration CLI entrypoint,
8
+ * which assembles a stack from the loaded `prisma-next.config.ts`; reaching this
9
+ * error means a test fixture or ad-hoc consumer instantiated `PostgresMigration`
10
+ * with the no-arg form (legal for `operations` / `describe` introspection only).
11
+ *
12
+ * The `operation` argument is required so every throw site names the operation
13
+ * that actually failed; a new operation cannot inherit a misattributed message.
14
+ *
15
+ * Distinct from `PN-MIG-2001` (placeholder not filled) and `PN-MIG-2005`
16
+ * (data-transform query plan against wrong contract) because the missing
17
+ * input is the stack itself, not the per-operation contract.
18
+ *
19
+ * Lives in `@prisma-next/target-postgres/errors` rather than the shared
20
+ * framework migration errors module because the failure is target-specific:
21
+ * the contract it talks about (`PostgresMigration`, the Postgres control
22
+ * adapter, the Postgres-target stack) only exists in this package.
23
+ */
24
+ function errorPostgresMigrationStackMissing(operation) {
25
+ return new CliStructuredError("2007", `PostgresMigration.${operation} requires a control adapter`, {
26
+ domain: "MIG",
27
+ why: `PostgresMigration.${operation} was invoked on an instance constructed without a ControlStack, so the stored controlAdapter is undefined and the operation cannot lower its plan.`,
28
+ fix: "Construct the migration via the migration CLI entrypoint (which assembles a ControlStack from the loaded prisma-next.config.ts), or pass a ControlStack containing a Postgres adapter to the migration constructor in test fixtures.",
29
+ meta: { operation }
30
+ });
31
+ }
32
+ //#endregion
33
+ export { errorPostgresMigrationStackMissing as t };
34
+
35
+ //# sourceMappingURL=errors-DO-w0EUS.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-DO-w0EUS.mjs","names":[],"sources":["../src/core/errors.ts"],"sourcesContent":["import { CliStructuredError } from '@prisma-next/errors/control';\n\n/**\n * A `PostgresMigration` operation that needs the materialized control adapter\n * — named by `operation` (e.g. `createTable`, `dropColumn`, `dataTransform`) —\n * was invoked, but the migration was constructed without a `ControlStack`.\n * Concrete authoring usage always goes through the migration CLI entrypoint,\n * which assembles a stack from the loaded `prisma-next.config.ts`; reaching this\n * error means a test fixture or ad-hoc consumer instantiated `PostgresMigration`\n * with the no-arg form (legal for `operations` / `describe` introspection only).\n *\n * The `operation` argument is required so every throw site names the operation\n * that actually failed; a new operation cannot inherit a misattributed message.\n *\n * Distinct from `PN-MIG-2001` (placeholder not filled) and `PN-MIG-2005`\n * (data-transform query plan against wrong contract) because the missing\n * input is the stack itself, not the per-operation contract.\n *\n * Lives in `@prisma-next/target-postgres/errors` rather than the shared\n * framework migration errors module because the failure is target-specific:\n * the contract it talks about (`PostgresMigration`, the Postgres control\n * adapter, the Postgres-target stack) only exists in this package.\n */\nexport function errorPostgresMigrationStackMissing(operation: string): CliStructuredError {\n return new CliStructuredError(\n '2007',\n `PostgresMigration.${operation} requires a control adapter`,\n {\n domain: 'MIG',\n why: `PostgresMigration.${operation} was invoked on an instance constructed without a ControlStack, so the stored controlAdapter is undefined and the operation cannot lower its plan.`,\n fix: 'Construct the migration via the migration CLI entrypoint (which assembles a ControlStack from the loaded prisma-next.config.ts), or pass a ControlStack containing a Postgres adapter to the migration constructor in test fixtures.',\n meta: { operation },\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,mCAAmC,WAAuC;CACxF,OAAO,IAAI,mBACT,QACA,qBAAqB,UAAU,8BAC/B;EACE,QAAQ;EACR,KAAK,qBAAqB,UAAU;EACpC,KAAK;EACL,MAAM,EAAE,UAAU;CACpB,CACF;AACF"}
package/dist/errors.d.mts CHANGED
@@ -2,14 +2,16 @@ import { CliStructuredError } from "@prisma-next/errors/control";
2
2
 
3
3
  //#region src/core/errors.d.ts
4
4
  /**
5
- * A `PostgresMigration` instance method that needs the materialized control
6
- * adapter (currently only `this.dataTransform(...)`) was invoked, but the
7
- * migration was constructed without a `ControlStack`. Concrete authoring
8
- * usage always goes through the migration CLI entrypoint, which assembles
9
- * a stack from the loaded `prisma-next.config.ts`; reaching this error
10
- * means a test fixture or ad-hoc consumer instantiated `PostgresMigration`
11
- * with the no-arg form (legal for `operations` / `describe` introspection
12
- * only).
5
+ * A `PostgresMigration` operation that needs the materialized control adapter
6
+ * named by `operation` (e.g. `createTable`, `dropColumn`, `dataTransform`)
7
+ * was invoked, but the migration was constructed without a `ControlStack`.
8
+ * Concrete authoring usage always goes through the migration CLI entrypoint,
9
+ * which assembles a stack from the loaded `prisma-next.config.ts`; reaching this
10
+ * error means a test fixture or ad-hoc consumer instantiated `PostgresMigration`
11
+ * with the no-arg form (legal for `operations` / `describe` introspection only).
12
+ *
13
+ * The `operation` argument is required so every throw site names the operation
14
+ * that actually failed; a new operation cannot inherit a misattributed message.
13
15
  *
14
16
  * Distinct from `PN-MIG-2001` (placeholder not filled) and `PN-MIG-2005`
15
17
  * (data-transform query plan against wrong contract) because the missing
@@ -20,7 +22,7 @@ import { CliStructuredError } from "@prisma-next/errors/control";
20
22
  * the contract it talks about (`PostgresMigration`, the Postgres control
21
23
  * adapter, the Postgres-target stack) only exists in this package.
22
24
  */
23
- declare function errorPostgresMigrationStackMissing(): CliStructuredError;
25
+ declare function errorPostgresMigrationStackMissing(operation: string): CliStructuredError;
24
26
  //#endregion
25
27
  export { errorPostgresMigrationStackMissing };
26
28
  //# sourceMappingURL=errors.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.mts","names":[],"sources":["../src/core/errors.ts"],"mappings":";;;;;AAqBA;;;;AAAwE;;;;;;;;;;;;;iBAAxD,kCAAA,IAAsC,kBAAkB"}
1
+ {"version":3,"file":"errors.d.mts","names":[],"sources":["../src/core/errors.ts"],"mappings":";;;;;AAuBA;;;;AAAyF;;;;;;;;;;;;;;;iBAAzE,kCAAA,CAAmC,SAAA,WAAoB,kBAAkB"}
package/dist/errors.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { t as errorPostgresMigrationStackMissing } from "./errors-CUk87ByX.mjs";
1
+ import { t as errorPostgresMigrationStackMissing } from "./errors-DO-w0EUS.mjs";
2
2
  export { errorPostgresMigrationStackMissing };
@@ -1,11 +1,11 @@
1
- import { b as PostgresOpFactoryCall } from "./op-factory-call-DmQEc3XV.mjs";
1
+ import { w as PostgresOpFactoryCall } from "./op-factory-call-Bn9zDx4_.mjs";
2
+ import { SqlStorage, StorageTable, StorageTypeInstance } from "@prisma-next/sql-contract/types";
2
3
  import { CodecControlHooks, MigrationOperationPolicy, SqlPlannerConflict } from "@prisma-next/family-sql/control";
4
+ import { SqlColumnIR, SqlSchemaIR, SqlSchemaIRNode } from "@prisma-next/sql-schema-ir/types";
5
+ import { DiffableNode, SchemaDiffIssue } from "@prisma-next/framework-components/control";
3
6
  import { Result } from "@prisma-next/utils/result";
4
- import { SqlStorage, StorageTable, StorageTypeInstance } from "@prisma-next/sql-contract/types";
5
- import { SchemaIssue } from "@prisma-next/framework-components/control";
6
7
  import { Contract } from "@prisma-next/contract/types";
7
8
  import { TargetBoundComponentDescriptor } from "@prisma-next/framework-components/components";
8
- import { SqlSchemaIR } from "@prisma-next/sql-schema-ir/types";
9
9
 
10
10
  //#region src/core/migrations/planner-strategies.d.ts
11
11
  /**
@@ -27,9 +27,16 @@ interface StrategyContext {
27
27
  readonly policy: MigrationOperationPolicy;
28
28
  readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
29
29
  }
30
- type CallMigrationStrategy = (issues: readonly SchemaIssue[], context: StrategyContext) => {
30
+ /**
31
+ * Consumes node-typed diff issues (`SchemaDiffIssue`, from the one differ —
32
+ * `buildPostgresPlanDiff`), reading the issue's node pair for structural
33
+ * decisions and resolving column DDL from the node's `codecRef`. The
34
+ * retained subsystems (codec type-operations, the NOT-NULL temp-default
35
+ * backfill) keep reading the contract via `StrategyContext`.
36
+ */
37
+ type CallMigrationStrategy = (issues: readonly SchemaDiffIssue[], context: StrategyContext) => {
31
38
  kind: 'match';
32
- issues: readonly SchemaIssue[];
39
+ issues: readonly SchemaDiffIssue[];
33
40
  calls: readonly PostgresOpFactoryCall[];
34
41
  /**
35
42
  * `true` for strategies that emit cohesive sequential recipes whose
@@ -44,8 +51,21 @@ type CallMigrationStrategy = (issues: readonly SchemaIssue[], context: StrategyC
44
51
  };
45
52
  //#endregion
46
53
  //#region src/core/migrations/issue-planner.d.ts
54
+ interface IssuePlannerValue {
55
+ readonly calls: readonly PostgresOpFactoryCall[];
56
+ }
57
+ /**
58
+ * The generic differ is total: a missing/extra table (or column) emits an
59
+ * issue for itself AND for every node in its subtree. `CreateTable`/`DropTable`
60
+ * and `AddColumn`/`DropColumn` already account for the whole subtree, so the
61
+ * nested issues are redundant — coalescing drops any issue whose path is a
62
+ * strict descendant of a `not-found`/`not-expected` issue's path. Run over the
63
+ * relational subset ONLY (policy issues and synthesized namespace issues are
64
+ * handled on their own paths, never coalesced against tables).
65
+ */
66
+ declare function coalesceSubtreeIssues<TNode extends DiffableNode = DiffableNode>(issues: readonly SchemaDiffIssue<TNode>[]): readonly SchemaDiffIssue<TNode>[];
47
67
  interface IssuePlannerOptions {
48
- readonly issues: readonly SchemaIssue[];
68
+ readonly issues: readonly SchemaDiffIssue[];
49
69
  readonly toContract: Contract<SqlStorage>;
50
70
  readonly fromContract: Contract<SqlStorage> | null;
51
71
  readonly schemaName: string;
@@ -72,10 +92,14 @@ interface IssuePlannerOptions {
72
92
  readonly frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
73
93
  readonly strategies?: readonly CallMigrationStrategy[];
74
94
  }
75
- interface IssuePlannerValue {
76
- readonly calls: readonly PostgresOpFactoryCall[];
77
- }
95
+ /**
96
+ * Runs the ordered strategy list over the node-typed diff issues, maps
97
+ * leftover issues via {@link mapNodeIssueToCall}, applies operation-class
98
+ * policy gating, and buckets calls into the fixed DDL emission order (dep →
99
+ * drop → table → column → recipe → alter → primaryKey → unique → index →
100
+ * foreignKey).
101
+ */
78
102
  declare function planIssues(options: IssuePlannerOptions): Result<IssuePlannerValue, readonly SqlPlannerConflict[]>;
79
103
  //#endregion
80
- export { planIssues };
104
+ export { coalesceSubtreeIssues, planIssues };
81
105
  //# sourceMappingURL=issue-planner.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"issue-planner.d.mts","names":[],"sources":["../src/core/migrations/planner-strategies.ts","../src/core/migrations/issue-planner.ts"],"mappings":";;;;;;;;;;;;;;;;;;;UA8HiB,eAAA;EAAA,SACN,UAAA,EAAY,QAAA,CAAS,UAAA;EAAA,SACrB,YAAA,EAAc,QAAA,CAAS,UAAA;EAAA,SACvB,UAAA;EAAA,SACA,UAAA,EAAY,WAAA,SAAoB,iBAAA;EAAA,SAChC,YAAA,EAAc,QAAA,CAAS,MAAA,SAAe,mBAAA;EAAA,SACtC,MAAA,EAAQ,WAAA;EAAA,SACR,MAAA,EAAQ,wBAAA;EAAA,SACR,mBAAA,EAAqB,aAAA,CAAc,8BAAA;AAAA;AAAA,KAOlC,qBAAA,IACV,MAAA,WAAiB,WAAA,IACjB,OAAA,EAAS,eAAA;EAGL,IAAA;EACA,MAAA,WAAiB,WAAA;EACjB,KAAA,WAAgB,qBAAA;ECEG;;;;;;;EDMnB,MAAA;AAAA;EAEA,IAAA;AAAA;;;UCXW,mBAAA;EAAA,SACN,MAAA,WAAiB,WAAA;EAAA,SACjB,UAAA,EAAY,QAAA,CAAS,UAAA;EAAA,SACrB,YAAA,EAAc,QAAA,CAAS,UAAA;EAAA,SACvB,UAAA;EAAA,SACA,UAAA,EAAY,WAAA,SAAoB,iBAAA;EAAA,SAChC,YAAA,EAAc,QAAA,CAAS,MAAA,SAAe,mBAAA;EDnBJ;;;;;;;EAAA,SC2BlC,MAAA,GAAS,WAAA;EDhCT;;;;;EAAA,SCsCA,MAAA,GAAS,wBAAA;EDpCc;;;;EAAA,SCyCvB,mBAAA,GAAsB,aAAA,CAAc,8BAAA;EAAA,SACpC,UAAA,YAAsB,qBAAA;AAAA;AAAA,UAGhB,iBAAA;EAAA,SACN,KAAA,WAAgB,qBAAqB;AAAA;AAAA,iBA2pBhC,UAAA,CACd,OAAA,EAAS,mBAAA,GACR,MAAA,CAAO,iBAAA,WAA4B,kBAAA"}
1
+ {"version":3,"file":"issue-planner.d.mts","names":[],"s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B,qBAAA;AAAA;;;;;;;;iBAUjB,UAAA,CACd,OAAA,EAAS,mBAAA,GACR,MAAA,CAAO,iBAAA,WAA4B,kBAAA"}
@@ -1,2 +1,2 @@
1
- import { t as planIssues } from "./issue-planner-DL6g3CmE.mjs";
2
- export { planIssues };
1
+ import { l as planIssues, o as coalesceSubtreeIssues } from "./control-policy-DtbkLLGv.mjs";
2
+ export { coalesceSubtreeIssues, planIssues };
@@ -1,7 +1,7 @@
1
- import { n as DataTransformOptions, r as dataTransform, t as DataTransformClosure } from "./data-transform-DDgWdB5o.mjs";
2
- import { T as Op } from "./op-factory-call-DmQEc3XV.mjs";
3
- import { t as PostgresMigration } from "./postgres-migration-Y4YBJqkS.mjs";
4
- import { col, fn, foreignKey, lit, primaryKey, unique } from "@prisma-next/sql-relational-core/contract-free";
1
+ import { n as DataTransformOptions, r as dataTransform, t as DataTransformClosure } from "./data-transform-DPzwBMhW.mjs";
2
+ import { k as Op } from "./op-factory-call-Bn9zDx4_.mjs";
3
+ import { t as PostgresMigration } from "./postgres-migration-DbckK1su.mjs";
4
+ import { checkExpression, col, fn, foreignKey, lit, primaryKey, unique } from "@prisma-next/sql-relational-core/contract-free";
5
5
  import { placeholder } from "@prisma-next/errors/migration";
6
6
  import { MigrationCLI } from "@prisma-next/cli/migration-cli";
7
7
  import { ExecuteRequestLowerer } from "@prisma-next/family-sql/control-adapter";
@@ -22,5 +22,5 @@ declare function createExtension(extensionName: string): Op;
22
22
  */
23
23
  declare function rawSql(op: Op): Op;
24
24
  //#endregion
25
- export { type DataTransformClosure, type DataTransformOptions, PostgresMigration as Migration, MigrationCLI, col, createExtension, dataTransform, fn, foreignKey, lit, placeholder, primaryKey, rawSql, unique };
25
+ export { type DataTransformClosure, type DataTransformOptions, PostgresMigration as Migration, MigrationCLI, checkExpression, col, createExtension, dataTransform, fn, foreignKey, lit, placeholder, primaryKey, rawSql, unique };
26
26
  //# sourceMappingURL=migration.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"migration.d.mts","names":[],"sources":["../src/core/migrations/operations/dependencies.ts","../src/core/migrations/operations/raw.ts"],"mappings":";;;;;;;;;iBAKgB,eAAA,CAAgB,aAAA,WAAwB,EAAE;;;;;;;;;;;AAA1D;;iBCOgB,MAAA,CAAO,EAAA,EAAI,EAAA,GAAK,EAAE"}
1
+ {"version":3,"file":"migration.d.mts","names":[],"sources":["../src/core/migrations/operations/dependencies.ts","../src/core/migrations/operations/raw.ts"],"mappings":";;;;;;;;;iBAMgB,eAAA,CAAgB,aAAA,WAAwB,EAAE;;;;;;;;;;;AAA1D;;iBCMgB,MAAA,CAAO,EAAA,EAAI,EAAA,GAAK,EAAE"}