@prisma-next/target-postgres 0.14.0-dev.8 → 0.14.0-dev.80

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-Bi9aa8zG.mjs +574 -0
  2. package/dist/authoring-Bi9aa8zG.mjs.map +1 -0
  3. package/dist/canonicalize-CAbXtVtB.d.mts +37 -0
  4. package/dist/canonicalize-CAbXtVtB.d.mts.map +1 -0
  5. package/dist/{codec-ids-CnXu9Qy3.d.mts → codec-ids-BzrFF-I4.d.mts} +3 -2
  6. package/dist/codec-ids-BzrFF-I4.d.mts.map +1 -0
  7. package/dist/{codec-ids-BvytN2P8.mjs → codec-ids-C_-Hj6bL.mjs} +3 -2
  8. package/dist/codec-ids-C_-Hj6bL.mjs.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-BiIWziRO.d.mts} +3 -2
  12. package/dist/codec-types-BiIWziRO.d.mts.map +1 -0
  13. package/dist/codec-types.d.mts +1 -1
  14. package/dist/codecs-BemGS69L.mjs +927 -0
  15. package/dist/codecs-BemGS69L.mjs.map +1 -0
  16. package/dist/{codecs--0A5_4Bq.d.mts → codecs-Cm-nS4mQ.d.mts} +111 -4
  17. package/dist/codecs-Cm-nS4mQ.d.mts.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-5LE2kwfb.mjs +1285 -0
  26. package/dist/control-policy-5LE2kwfb.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 +866 -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-BQzITB_e.mjs} +128 -6
  36. package/dist/ddl-BQzITB_e.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-DzL6vXAz.mjs +22 -0
  44. package/dist/descriptor-meta-DzL6vXAz.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-DULhiCNM.mjs +305 -0
  48. package/dist/diff-database-schema-DULhiCNM.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-Bc2N3tMy.d.mts +170 -0
  68. package/dist/nodes-Bc2N3tMy.d.mts.map +1 -0
  69. package/dist/nodes-DJC5B8Id.mjs +192 -0
  70. package/dist/nodes-DJC5B8Id.mjs.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-D6yu-PlS.mjs} +469 -32
  74. package/dist/op-factory-call-D6yu-PlS.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 +300 -3
  78. package/dist/pack.d.mts.map +1 -1
  79. package/dist/pack.mjs +1 -1
  80. package/dist/planner-DwDxdYxi.mjs +390 -0
  81. package/dist/planner-DwDxdYxi.mjs.map +1 -0
  82. package/dist/{planner-ddl-builders-B2wOwLqI.mjs → planner-ddl-builders-BKlmGDJl.mjs} +17 -28
  83. package/dist/planner-ddl-builders-BKlmGDJl.mjs.map +1 -0
  84. package/dist/planner-ddl-builders.d.mts +4 -6
  85. package/dist/planner-ddl-builders.d.mts.map +1 -1
  86. package/dist/planner-ddl-builders.mjs +2 -2
  87. package/dist/planner-identity-values-CJPha2Sz.mjs.map +1 -1
  88. package/dist/planner-identity-values.d.mts +8 -2
  89. package/dist/planner-identity-values.d.mts.map +1 -1
  90. package/dist/planner-identity-values.mjs +2 -2
  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-BGPpq56_.mjs} +3 -3
  94. package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs.map → planner-produced-postgres-migration-BGPpq56_.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-CDXn2uaS.mjs} +5 -5
  98. package/dist/{planner-sql-checks-jqUUGyQR.mjs.map → planner-sql-checks-CDXn2uaS.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-serializer-k3TAcPMY.mjs → postgres-contract-view-C3LPCLP_.mjs} +45 -41
  109. package/dist/postgres-contract-view-C3LPCLP_.mjs.map +1 -0
  110. package/dist/postgres-contract-view-C9j5cqP0.d.mts +34 -0
  111. package/dist/postgres-contract-view-C9j5cqP0.d.mts.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-et1td40f.mjs} +78 -45
  117. package/dist/postgres-migration-et1td40f.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-DKq6s1P3.d.mts +269 -0
  125. package/dist/postgres-schema-DKq6s1P3.d.mts.map +1 -0
  126. package/dist/{postgres-schema-COGZ1ark.mjs → postgres-schema-DYATroNx.mjs} +200 -11
  127. package/dist/postgres-schema-DYATroNx.mjs.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-DpGte50u.mjs +22 -0
  135. package/dist/resolve-ddl-schema-DpGte50u.mjs.map +1 -0
  136. package/dist/rls-canonicalize.d.mts +20 -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-rHHtr1h0.mjs +75 -0
  154. package/dist/wire-name-rHHtr1h0.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 +509 -2
  160. package/src/core/codec-helpers.ts +33 -7
  161. package/src/core/codec-ids.ts +1 -0
  162. package/src/core/codec-type-map.ts +2 -0
  163. package/src/core/codecs.ts +193 -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 +10 -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 +1273 -0
  206. package/src/core/psl-infer/postgres-default-mapping.ts +16 -0
  207. package/src/core/psl-infer/postgres-type-map.ts +128 -0
  208. package/src/core/rls/canonicalize.ts +48 -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 +3 -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 +7 -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
@@ -1,10 +1,22 @@
1
- import type { Contract } from '@prisma-next/contract/types';
2
- import type { ControlPolicySubject } from '@prisma-next/family-sql/control';
3
- import type { SchemaIssue } from '@prisma-next/framework-components/control';
1
+ import type { Contract, ControlPolicy } from '@prisma-next/contract/types';
2
+ import type {
3
+ ControlPolicySubject,
4
+ SqlPlannerConflict,
5
+ SuppressionRecord,
6
+ } from '@prisma-next/family-sql/control';
7
+ import type { SchemaDiffIssue } from '@prisma-next/framework-components/control';
4
8
  import { entityAt, UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';
5
9
  import type { SqlStorage, StorageTable } from '@prisma-next/sql-contract/types';
10
+ import { blindCast } from '@prisma-next/utils/casts';
6
11
  import { ifDefined } from '@prisma-next/utils/defined';
12
+ import { type PostgresRole, ROLE_DEFAULT_CONTROL_POLICY } from '../postgres-role';
7
13
  import { isPostgresSchema } from '../postgres-schema';
14
+ import { postgresNodeStorageCoordinate } from '../schema-ir/node-storage-coordinate';
15
+ import type { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';
16
+ import { PostgresTableSchemaNode } from '../schema-ir/postgres-table-schema-node';
17
+ import type { SqlSchemaDiffNode } from '../schema-ir/schema-node-kinds';
18
+ import { PostgresSchemaNodeKind } from '../schema-ir/schema-node-kinds';
19
+ import { issueColumnName } from './issue-planner';
8
20
  import type { PostgresOpFactoryCall } from './op-factory-call';
9
21
 
10
22
  /**
@@ -17,11 +29,16 @@ import type { PostgresOpFactoryCall } from './op-factory-call';
17
29
  * and is fail-closed. Any call not listed here — including future or
18
30
  * extension-contributed factories — is treated as NOT object-creation, so it
19
31
  * is suppressed under `tolerated` rather than permissively emitted.
32
+ *
33
+ * Lists the creation factories that actually reach the call-side resolver
34
+ * (`resolvePostgresCallControlPolicySubject`) — today only RLS policy
35
+ * creation, from `planPostgresSchemaDiff`. Every other whole-object create
36
+ * (table, schema, native enum, and RLS enablement) is constructed inside
37
+ * `planIssues` and graded on the node side by
38
+ * `resolvePostgresNodeIssueCreationFactoryName`, so none of them are listed
39
+ * here.
20
40
  */
21
- const OBJECT_CREATION_FACTORIES: ReadonlySet<string> = new Set<string>([
22
- 'createTable',
23
- 'createSchema',
24
- ]);
41
+ const OBJECT_CREATION_FACTORIES: ReadonlySet<string> = new Set<string>(['createRlsPolicy']);
25
42
 
26
43
  function createsNewTopLevelObject(call: PostgresOpFactoryCall): boolean {
27
44
  return OBJECT_CREATION_FACTORIES.has(call.factoryName);
@@ -32,18 +49,25 @@ function ddlSchemaNameForNamespace(contract: Contract<SqlStorage>, namespaceId:
32
49
  return isPostgresSchema(namespace) ? namespace.ddlSchemaName(contract.storage) : namespaceId;
33
50
  }
34
51
 
35
- function resolveNamespaceIdForTable(
52
+ /**
53
+ * Resolve the namespace a declared storage entity lives in by walking every
54
+ * namespace for one whose `entries` map actually contains the coordinate —
55
+ * a table by its name, a native enum by its physical type name (see
56
+ * {@link postgresNodeStorageCoordinate}). When `ddlSchemaName` is given, the
57
+ * match must also land in that DDL schema (disambiguates same-named entities
58
+ * declared under different namespaces); when omitted, the first namespace
59
+ * that declares the entity wins. Falls back to {@link UNBOUND_NAMESPACE_ID}
60
+ * when no namespace declares it — e.g. an extra/dropped entity the contract
61
+ * doesn't claim at all.
62
+ */
63
+ function resolveNamespaceIdForEntity(
36
64
  contract: Contract<SqlStorage>,
37
- tableName: string,
65
+ coordinate: { readonly entityKind: string; readonly entityName: string },
38
66
  ddlSchemaName: string | undefined,
39
67
  ): string {
40
68
  for (const namespaceId of Object.keys(contract.storage.namespaces)) {
41
- const table = entityAt<StorageTable>(contract.storage, {
42
- namespaceId,
43
- entityKind: 'table',
44
- entityName: tableName,
45
- });
46
- if (!table) continue;
69
+ const entity = entityAt(contract.storage, { namespaceId, ...coordinate });
70
+ if (!entity) continue;
47
71
  if (
48
72
  ddlSchemaName === undefined ||
49
73
  ddlSchemaNameForNamespace(contract, namespaceId) === ddlSchemaName
@@ -54,7 +78,19 @@ function resolveNamespaceIdForTable(
54
78
  return UNBOUND_NAMESPACE_ID;
55
79
  }
56
80
 
57
- function resolveNamespaceIdForDdlSchema(
81
+ function resolveNamespaceIdForTable(
82
+ contract: Contract<SqlStorage>,
83
+ tableName: string,
84
+ ddlSchemaName: string | undefined,
85
+ ): string {
86
+ return resolveNamespaceIdForEntity(
87
+ contract,
88
+ { entityKind: 'table', entityName: tableName },
89
+ ddlSchemaName,
90
+ );
91
+ }
92
+
93
+ export function resolveNamespaceIdForDdlSchema(
58
94
  contract: Contract<SqlStorage>,
59
95
  ddlSchemaName: string,
60
96
  ): string {
@@ -84,16 +120,60 @@ function postgresCallFields(call: PostgresOpFactoryCall): PostgresCallFields {
84
120
  };
85
121
  }
86
122
 
87
- export function formatPostgresControlPolicySubjectLabel(
88
- factoryName: string,
123
+ function formatSuppressionSubjectLabel(
89
124
  subject: ControlPolicySubject | undefined,
90
125
  contract: Contract<SqlStorage>,
91
126
  ): string {
92
- if (subject?.table) {
93
- const ddlSchema = ddlSchemaNameForNamespace(contract, subject.namespaceId);
94
- return `${factoryName}(${ddlSchema}.${subject.table})`;
127
+ if (subject === undefined) return 'unknown';
128
+ const ddlSchema = ddlSchemaNameForNamespace(contract, subject.namespaceId);
129
+ if (subject.entityKind !== undefined && subject.entityName !== undefined) {
130
+ return `${subject.entityKind} "${ddlSchema}.${subject.entityName}"`;
131
+ }
132
+ return `namespace "${ddlSchema}"`;
133
+ }
134
+
135
+ function postgresSuppressionSummary(
136
+ subjectLabel: string,
137
+ subject: ControlPolicySubject | undefined,
138
+ policy: string,
139
+ ): string {
140
+ const namespace = subject?.namespaceId ?? 'unknown';
141
+ const declared = subject?.explicitNodeControlPolicy;
142
+ if (policy === 'external' && declared === 'managed') {
143
+ return `control policy suppressed: ${subjectLabel} — namespace '${namespace}' has effective control 'external' but declared 'managed'`;
95
144
  }
96
- return factoryName;
145
+ const declaredSuffix = declared ? ` but declared '${declared}'` : '';
146
+ return `control policy suppressed: ${subjectLabel} — namespace '${namespace}' has effective control '${policy}'${declaredSuffix}`;
147
+ }
148
+
149
+ /**
150
+ * Render one family {@link SuppressionRecord} into a target `SqlPlannerConflict`.
151
+ * The family decides *that* a subject is suppressed and hands over the raw
152
+ * coordinate + policy; the label, message, and location are rendered here,
153
+ * driven entirely by the subject's own `(entityKind, entityName)` coordinate
154
+ * — no target-owned table-vs-enum vocabulary.
155
+ */
156
+ export function renderPostgresSuppression(
157
+ record: SuppressionRecord,
158
+ contract: Contract<SqlStorage>,
159
+ ): SqlPlannerConflict {
160
+ const subject = record.subject;
161
+ const subjectLabel = formatSuppressionSubjectLabel(subject, contract);
162
+ return {
163
+ kind: 'controlPolicySuppressedCall',
164
+ summary: postgresSuppressionSummary(subjectLabel, subject, record.policy),
165
+ location: {
166
+ ...ifDefined('namespaceId', subject?.namespaceId),
167
+ ...ifDefined('entityKind', subject?.entityKind),
168
+ ...ifDefined('entityName', subject?.entityName),
169
+ ...ifDefined('column', subject?.column),
170
+ },
171
+ meta: {
172
+ controlPolicy: record.policy,
173
+ ...ifDefined('factoryName', record.factoryName),
174
+ ...ifDefined('declaredControlPolicy', subject?.explicitNodeControlPolicy),
175
+ },
176
+ };
97
177
  }
98
178
 
99
179
  export function resolvePostgresCallControlPolicySubject(
@@ -123,9 +203,10 @@ export function resolvePostgresCallControlPolicySubject(
123
203
  })?.control;
124
204
  return {
125
205
  namespaceId,
126
- ...ifDefined('explicitNodeControlPolicy', tableControlPolicy),
127
- table: callFields.tableName,
206
+ entityKind: 'table',
207
+ entityName: callFields.tableName,
128
208
  ...ifDefined('column', callFields.columnName),
209
+ ...ifDefined('explicitNodeControlPolicy', tableControlPolicy),
129
210
  createsNewObject,
130
211
  };
131
212
  }
@@ -141,64 +222,135 @@ export function resolvePostgresCallControlPolicySubject(
141
222
  }
142
223
 
143
224
  /**
144
- * Issue kinds that describe the absence of a whole, top-level Postgres
145
- * object the same kinds `createsNewTopLevelObject` recognises for calls.
146
- * Used by {@link resolvePostgresIssueCreationFactoryName} to decide whether
147
- * a `tolerated` subject permits the issue to flow into the planner
225
+ * Node kinds whose *absence* is the creation of a whole, top-level Postgres
226
+ * object: a namespace, a table, or a native enum. Used by
227
+ * {@link resolvePostgresNodeIssueCreationFactoryName} to decide whether a
228
+ * `tolerated` subject permits the issue to flow into the planner
148
229
  * (create-if-absent) and to seed the suppressed-subject warning's
149
- * `factoryName` when the planner is skipped.
230
+ * `factoryName` when the planner is skipped. RLS policy creation is not
231
+ * listed here — policy issues never reach this issue-based partition (they
232
+ * are routed to `planPostgresSchemaDiff` and gated via the call-based
233
+ * {@link resolvePostgresCallControlPolicySubject} instead).
150
234
  */
151
- const POSTGRES_ISSUE_CREATION_FACTORY: Readonly<Record<string, string>> = Object.freeze({
152
- missing_schema: 'createSchema',
153
- missing_table: 'createTable',
235
+ const POSTGRES_NODE_CREATION_FACTORY: Readonly<Record<string, string>> = Object.freeze({
236
+ [PostgresSchemaNodeKind.namespace]: 'createSchema',
237
+ [PostgresSchemaNodeKind.table]: 'createTable',
238
+ [PostgresSchemaNodeKind.nativeEnum]: 'createNativeEnumType',
154
239
  });
155
240
 
156
- export function resolvePostgresIssueCreationFactoryName(issue: SchemaIssue): string | undefined {
157
- return POSTGRES_ISSUE_CREATION_FACTORY[issue.kind];
241
+ /**
242
+ * A table `not-equal` issue whose `rlsEnabled` flips OFF→ON (expected on,
243
+ * actual off) is enablement toward `ENABLE ROW LEVEL SECURITY`. It is
244
+ * creation-class on the node side because `isEnablementCreationIssue` and
245
+ * {@link resolvePostgresNodeIssueCreationFactoryName} treat this OFF→ON delta
246
+ * as a creation: enabling RLS establishes the fail-closed guard the declared
247
+ * policy set attaches to, the same grant `tolerated` extends to creating the
248
+ * policies themselves. The opposite direction (`DISABLE`) is a modification
249
+ * and stays managed-only. Keying on the actual delta (not just the expected
250
+ * bit) keeps this correct if a second table attribute ever joins
251
+ * `isEqualTo`: a not-equal with no `rlsEnabled` delta is not enablement, so
252
+ * it is not admitted as creation-class here.
253
+ */
254
+ function isEnablementCreationIssue(issue: SchemaDiffIssue<SqlSchemaDiffNode>): boolean {
255
+ if (issue.reason !== 'not-equal') return false;
256
+ const { expected, actual } = issue;
257
+ return (
258
+ expected !== undefined &&
259
+ actual !== undefined &&
260
+ PostgresTableSchemaNode.is(expected) &&
261
+ PostgresTableSchemaNode.is(actual) &&
262
+ expected.rlsEnabled === true &&
263
+ actual.rlsEnabled === false
264
+ );
265
+ }
266
+
267
+ export function resolvePostgresNodeIssueCreationFactoryName(
268
+ issue: SchemaDiffIssue<SqlSchemaDiffNode>,
269
+ ): string | undefined {
270
+ if (isEnablementCreationIssue(issue)) {
271
+ return 'enableRowLevelSecurity';
272
+ }
273
+ if (issue.reason !== 'not-found') return undefined;
274
+ const node = issue.expected ?? issue.actual;
275
+ if (node === undefined) return undefined;
276
+ return POSTGRES_NODE_CREATION_FACTORY[node.nodeKind];
158
277
  }
159
278
 
160
279
  /**
161
- * Resolve the control-policy subject coordinate for a single
162
- * {@link SchemaIssue}. Mirrors the resolution `resolvePostgresCallControlPolicySubject`
163
- * performs for a generated DDL call, but works *off the issue* — so the
164
- * planner can partition issues by effective policy before the diff engine
165
- * runs. `createsNewObject` is derived from the issue's kind: schema/table/
166
- * type-missing issues describe a brand-new top-level object; everything else
167
- * touches an existing object.
168
- *
169
- * An `extra_table` issue carries no contract namespace coordinate (the table
170
- * isn't in any contract namespace), so the subject's `namespaceId` falls
171
- * back to {@link UNBOUND_NAMESPACE_ID}; the call-side resolver does the same
172
- * for the `DropTableCall` it produces.
280
+ * Resolves the control-policy subject for a node-typed {@link SchemaDiffIssue}
281
+ * (the issue-side mirror of `resolvePostgresCallControlPolicySubject`).
282
+ * Storage entities resolve off their node coordinate; a sub-entity issue
283
+ * resolves off the enclosing table read from the issue path; an unclaimed
284
+ * extra falls back to the unbound coordinate. A role always resolves
285
+ * `'external'` roles are referenced, never owned.
173
286
  */
174
- export function resolvePostgresIssueControlPolicySubject(
175
- issue: SchemaIssue,
287
+ export function resolvePostgresNodeIssueControlPolicySubject(
288
+ issue: SchemaDiffIssue<SqlSchemaDiffNode>,
176
289
  contract: Contract<SqlStorage>,
177
290
  ): ControlPolicySubject | undefined {
178
- const createsNewObject = POSTGRES_ISSUE_CREATION_FACTORY[issue.kind] !== undefined;
291
+ const node = issue.expected ?? issue.actual;
292
+ if (node === undefined) return undefined;
293
+
294
+ if (node.nodeKind === PostgresSchemaNodeKind.namespace) {
295
+ const namespaceNode = blindCast<
296
+ PostgresNamespaceSchemaNode,
297
+ 'a postgres-namespace diff node is always a PostgresNamespaceSchemaNode'
298
+ >(node);
299
+ return {
300
+ namespaceId: resolveNamespaceIdForDdlSchema(contract, namespaceNode.schemaName),
301
+ createsNewObject: issue.reason === 'not-found',
302
+ };
303
+ }
179
304
 
180
- if (issue.kind === 'missing_schema' && issue.namespaceId) {
181
- return { namespaceId: issue.namespaceId, createsNewObject };
305
+ if (node.nodeKind === PostgresSchemaNodeKind.role) {
306
+ const roleName = issue.path[1];
307
+ const roleEntity =
308
+ roleName === undefined
309
+ ? undefined
310
+ : entityAt<PostgresRole>(contract.storage, {
311
+ namespaceId: UNBOUND_NAMESPACE_ID,
312
+ entityKind: 'role',
313
+ entityName: roleName,
314
+ });
315
+ return {
316
+ namespaceId: UNBOUND_NAMESPACE_ID,
317
+ explicitNodeControlPolicy: roleEntity?.control ?? ROLE_DEFAULT_CONTROL_POLICY,
318
+ createsNewObject: false,
319
+ };
182
320
  }
183
321
 
184
- if ('table' in issue && issue.table) {
185
- const namespaceId =
186
- 'namespaceId' in issue && issue.namespaceId
187
- ? issue.namespaceId
188
- : resolveNamespaceIdForTable(contract, issue.table, undefined);
189
- const table = entityAt<StorageTable>(contract.storage, {
322
+ const coordinate = postgresNodeStorageCoordinate(node);
323
+ if (coordinate !== undefined) {
324
+ const namespaceId = resolveNamespaceIdForEntity(contract, coordinate, issue.path[1]);
325
+ const entityControl = entityAt<{ readonly control?: ControlPolicy }>(contract.storage, {
190
326
  namespaceId,
191
- entityKind: 'table',
192
- entityName: issue.table,
193
- });
327
+ ...coordinate,
328
+ })?.control;
194
329
  return {
195
330
  namespaceId,
196
- ...ifDefined('explicitNodeControlPolicy', table?.control),
197
- table: issue.table,
198
- ...ifDefined('column', 'column' in issue ? issue.column : undefined),
199
- createsNewObject,
331
+ ...coordinate,
332
+ ...ifDefined('column', issueColumnName(issue)),
333
+ ...ifDefined('explicitNodeControlPolicy', entityControl),
334
+ createsNewObject: resolvePostgresNodeIssueCreationFactoryName(issue) !== undefined,
200
335
  };
201
336
  }
202
337
 
203
- return undefined;
338
+ const tableName = issue.path[2];
339
+ if (tableName === undefined) return undefined;
340
+ const ddlSchemaName = issue.path[1];
341
+ const namespaceId = resolveNamespaceIdForTable(contract, tableName, ddlSchemaName);
342
+ const table = entityAt<StorageTable>(contract.storage, {
343
+ namespaceId,
344
+ entityKind: 'table',
345
+ entityName: tableName,
346
+ });
347
+
348
+ return {
349
+ namespaceId,
350
+ entityKind: 'table',
351
+ entityName: tableName,
352
+ ...ifDefined('column', issueColumnName(issue)),
353
+ ...ifDefined('explicitNodeControlPolicy', table?.control),
354
+ createsNewObject: resolvePostgresNodeIssueCreationFactoryName(issue) !== undefined,
355
+ };
204
356
  }
@@ -0,0 +1,252 @@
1
+ import type { Contract, ControlPolicy } from '@prisma-next/contract/types';
2
+ import type { SqlSchemaDiffResult } from '@prisma-next/family-sql/control';
3
+ import { buildNativeTypeExpander } from '@prisma-next/family-sql/control';
4
+ import { classifyDiffSubjectGranularity } from '@prisma-next/family-sql/diff';
5
+ import type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';
6
+ import type { DiffableNode, SchemaDiffIssue } from '@prisma-next/framework-components/control';
7
+ import { diffSchemas } from '@prisma-next/framework-components/control';
8
+ import { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';
9
+ import type { SqlStorage } from '@prisma-next/sql-contract/types';
10
+ import type { SqlSchemaIRNode } from '@prisma-next/sql-schema-ir/types';
11
+ import { blindCast } from '@prisma-next/utils/casts';
12
+ import { ifDefined } from '@prisma-next/utils/defined';
13
+ import type { PostgresContract } from '../postgres-schema';
14
+ import { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';
15
+ import { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';
16
+ import {
17
+ postgresDiffSubjectGranularity,
18
+ type SqlSchemaDiffNode,
19
+ } from '../schema-ir/schema-node-kinds';
20
+ import { contractToPostgresDatabaseSchemaNode } from './contract-to-postgres-database-schema-node';
21
+ import { resolvePostgresNodeIssueControlPolicySubject } from './control-policy';
22
+
23
+ /**
24
+ * Whether a diff issue's subject node is cluster-scoped — it carries its own
25
+ * `namespaceId` field (only role and policy diff nodes do) and that
26
+ * coordinate is the unbound sentinel, meaning the node is not owned by any
27
+ * schema/namespace. A role node is always cluster-scoped (roles are
28
+ * cluster-level objects); a policy node's `namespaceId` is always its
29
+ * table's resolved DDL schema, never the sentinel. Namespace-ownership
30
+ * scoping (which compares `issue.path[1]` against the set of DDL schemas
31
+ * the contract owns) makes no sense for a cluster-scoped subject — its path
32
+ * segment at that index is the object's own name, not a schema name — so
33
+ * such an issue bypasses that scoping entirely.
34
+ */
35
+ function isClusterScopedIssue(issue: SchemaDiffIssue): boolean {
36
+ const node = issue.expected ?? issue.actual;
37
+ return node !== undefined && nodeNamespaceId(node) === UNBOUND_NAMESPACE_ID;
38
+ }
39
+
40
+ function nodeNamespaceId(node: DiffableNode): string | undefined {
41
+ if (!Object.hasOwn(node, 'namespaceId')) return undefined;
42
+ return blindCast<
43
+ { namespaceId: string },
44
+ 'presence of an own namespaceId field was just checked via Object.hasOwn'
45
+ >(node).namespaceId;
46
+ }
47
+
48
+ function ownedSchemaNames(expected: PostgresDatabaseSchemaNode): ReadonlySet<string> {
49
+ const policyNamespaces = Object.values(expected.namespaces).flatMap((ns) =>
50
+ Object.values(ns.tables).flatMap((t) => t.policies.map((p) => p.namespaceId)),
51
+ );
52
+ return new Set([...policyNamespaces, ...expected.existingSchemas]);
53
+ }
54
+
55
+ /**
56
+ * Drops contract namespaces that declare no tables from the verdict-diff
57
+ * expected tree and the relational owned-schema set. The legacy relational
58
+ * walk skipped a table-less namespace (e.g. an enums-only schema) before
59
+ * pairing, so neither its DDL schema's absence nor that schema's live
60
+ * relational contents ever reached the verdict — the pruned tree
61
+ * reproduces that. The prune loses no expected policies: policies attach
62
+ * to tables, so a table-less namespace carries none (the projection
63
+ * throws on a policy referencing an absent table). Live policies in a
64
+ * pruned schema remain governed via the full owned set (see
65
+ * {@link diffPostgresSchema}).
66
+ */
67
+ function pruneTableLessNamespaces(
68
+ expected: PostgresDatabaseSchemaNode,
69
+ ): PostgresDatabaseSchemaNode {
70
+ const namespaces = Object.fromEntries(
71
+ Object.entries(expected.namespaces).filter(([, ns]) => Object.keys(ns.tables).length > 0),
72
+ );
73
+ return new PostgresDatabaseSchemaNode({
74
+ namespaces,
75
+ roles: [...expected.roles],
76
+ existingSchemas: expected.existingSchemas.filter((s) => namespaces[s] !== undefined),
77
+ pgVersion: expected.pgVersion,
78
+ });
79
+ }
80
+
81
+ /**
82
+ * Resolves a verdict-diff issue's subject's declared control policy directly
83
+ * from the contract, by delegating to the same node-typed resolver
84
+ * ({@link resolvePostgresNodeIssueControlPolicySubject}) the planner uses to
85
+ * gate DDL calls. `undefined` when the issue resolves to no contract subject.
86
+ *
87
+ * A role issue resolves through that same resolver to `external`
88
+ * unconditionally (see its role branch), regardless of the contract's own
89
+ * default policy: a role is referenced by the contract but not owned, and
90
+ * `external`'s existing semantics — a missing declared subject still fails,
91
+ * every extra is suppressed — are exactly the wanted asymmetric grading for
92
+ * a cluster object the framework does not own.
93
+ */
94
+ function resolveControlPolicy(
95
+ issue: SchemaDiffIssue,
96
+ contract: Contract<SqlStorage>,
97
+ ): ControlPolicy | undefined {
98
+ const nodeIssue = blindCast<
99
+ SchemaDiffIssue<SqlSchemaDiffNode>,
100
+ 'every node in a Postgres schema diff tree is a SqlSchemaDiffNode'
101
+ >(issue);
102
+ return resolvePostgresNodeIssueControlPolicySubject(nodeIssue, contract)
103
+ ?.explicitNodeControlPolicy;
104
+ }
105
+
106
+ /**
107
+ * The Postgres full-tree node diff for the family verify verdict: derive
108
+ * the expected tree (resolved leaf values, expander threaded, FK schemas
109
+ * resolved, table-less namespaces pruned), run the generic
110
+ * differ over the trees as derived, and scope out `not-expected` findings under namespaces the
111
+ * contract does not own. Ownership scoping bypasses cluster-scoped subjects
112
+ * (roles today), mirroring the legacy decomposition: relational extras check
113
+ * the PRUNED owned set (the legacy
114
+ * per-namespace walk never visited a table-less namespace, so its live
115
+ * relational contents are invisible), while `structural` extras (RLS
116
+ * policies) check the FULL owned set (the legacy policy diff governed
117
+ * every contract schema regardless of tables — RLS governance does not
118
+ * shrink because a namespace declares no tables). The codec `verifyType`
119
+ * hooks run once per contract namespace with tables against that
120
+ * namespace's paired actual node (the hooks read namespace-scoped state
121
+ * such as `nativeEnums`).
122
+ */
123
+ export function diffPostgresSchema(input: {
124
+ readonly contract: Contract<SqlStorage>;
125
+ readonly schema: SqlSchemaIRNode;
126
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
127
+ }): SqlSchemaDiffResult {
128
+ const postgresContract = blindCast<
129
+ PostgresContract,
130
+ 'diffPostgresSchema is only called with a postgres contract'
131
+ >(input.contract);
132
+ PostgresDatabaseSchemaNode.assert(input.schema);
133
+ const actual = input.schema;
134
+ const expandNativeType = buildNativeTypeExpander(input.frameworkComponents);
135
+ const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, {
136
+ annotationNamespace: 'pg',
137
+ ...ifDefined('expandNativeType', expandNativeType),
138
+ });
139
+ const expected = pruneTableLessNamespaces(fullExpected);
140
+ const relationalOwned = ownedSchemaNames(expected);
141
+ const structuralOwned = ownedSchemaNames(fullExpected);
142
+ const issues = diffSchemas(expected, actual).filter((issue) => {
143
+ if (issue.reason !== 'not-expected') return true;
144
+ if (isClusterScopedIssue(issue)) return true;
145
+ const granularity = classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity);
146
+ const namespaceSegment = issue.path[1];
147
+ if (namespaceSegment === undefined) return true;
148
+ const owned = granularity === 'structural' ? structuralOwned : relationalOwned;
149
+ return owned.has(namespaceSegment);
150
+ });
151
+ const namespacePairs = Object.values(expected.namespaces).map((ns) => ({
152
+ actual: actual.namespaces[ns.schemaName],
153
+ }));
154
+ return {
155
+ issues,
156
+ resolveControlPolicy: (issue) => resolveControlPolicy(issue, postgresContract),
157
+ namespacePairs,
158
+ };
159
+ }
160
+
161
+ /**
162
+ * Adds an empty namespace node to the actual tree for every expected namespace
163
+ * absent from it. The relational plan diff pairs on namespace: a contract
164
+ * namespace whose live schema does not exist yet must surface each of its
165
+ * tables as `not-found` (→ `CREATE TABLE`), NOT as a single namespace
166
+ * `not-found` that subtree-coalescing would collapse (leaving `CREATE SCHEMA`
167
+ * with no tables). Padding makes the namespaces pair, so only table/column/
168
+ * policy drift surfaces; `CREATE SCHEMA` comes separately from the synthesized
169
+ * namespace-presence stitch (`verifyPostgresNamespacePresence`), never from the
170
+ * tree diff — matching the retired per-namespace-paired relational walk, which
171
+ * paired a missing schema against an empty namespace node.
172
+ */
173
+ function padActualNamespaces(
174
+ expected: PostgresDatabaseSchemaNode,
175
+ actual: PostgresDatabaseSchemaNode,
176
+ ): PostgresDatabaseSchemaNode {
177
+ const namespaces: Record<string, PostgresNamespaceSchemaNode> = { ...actual.namespaces };
178
+ let padded = false;
179
+ for (const schemaName of Object.keys(expected.namespaces)) {
180
+ if (namespaces[schemaName] === undefined) {
181
+ namespaces[schemaName] = new PostgresNamespaceSchemaNode({
182
+ schemaName,
183
+ tables: {},
184
+ });
185
+ padded = true;
186
+ }
187
+ }
188
+ if (!padded) return actual;
189
+ return new PostgresDatabaseSchemaNode({
190
+ namespaces,
191
+ roles: [...actual.roles],
192
+ existingSchemas: [...actual.existingSchemas],
193
+ pgVersion: actual.pgVersion,
194
+ });
195
+ }
196
+
197
+ export interface PostgresPlanDiff {
198
+ /** The desired ("end") tree — resolved leaf values (incl. `codecRef`) on every column, table-less namespaces pruned. */
199
+ readonly expected: PostgresDatabaseSchemaNode;
200
+ /** The live ("start") tree, padded with empty namespaces so a missing schema's tables pair. */
201
+ readonly actual: PostgresDatabaseSchemaNode;
202
+ /** The one node diff over the two trees: relational + policy drift, cluster-scope-aware ownership filtered. */
203
+ readonly issues: readonly SchemaDiffIssue<SqlSchemaDiffNode>[];
204
+ }
205
+
206
+ /**
207
+ * The Postgres planner's diff input: the SAME tree-building
208
+ * `diffPostgresSchema` uses (expander threaded, FK schemas resolved,
209
+ * table-less namespaces pruned, cluster-scope-aware ownership filter) plus
210
+ * actual namespace padding (so a missing
211
+ * schema's tables surface as `not-found` instead of a swallowed namespace
212
+ * `not-found`). One differ drives both verify and plan; this is the
213
+ * plan-side derivation. The single issue list covers tables / columns /
214
+ * constraints / indexes / defaults AND policies — the caller splits it
215
+ * (relational → `mapNodeIssueToCall`; policy → RLS ops) and stitches in
216
+ * `CREATE SCHEMA` separately.
217
+ */
218
+ export function buildPostgresPlanDiff(input: {
219
+ readonly contract: Contract<SqlStorage>;
220
+ readonly actualSchema: SqlSchemaIRNode;
221
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
222
+ }): PostgresPlanDiff {
223
+ const postgresContract = blindCast<
224
+ PostgresContract,
225
+ 'buildPostgresPlanDiff is only called with a postgres contract'
226
+ >(input.contract);
227
+ PostgresDatabaseSchemaNode.assert(input.actualSchema);
228
+ const actual = input.actualSchema;
229
+ const expandNativeType = buildNativeTypeExpander(input.frameworkComponents);
230
+ const projectionOptions = {
231
+ annotationNamespace: 'pg',
232
+ ...ifDefined('expandNativeType', expandNativeType),
233
+ };
234
+ const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, projectionOptions);
235
+ const expected = pruneTableLessNamespaces(fullExpected);
236
+ const paddedActual = padActualNamespaces(expected, actual);
237
+ const relationalOwned = ownedSchemaNames(expected);
238
+ const structuralOwned = ownedSchemaNames(fullExpected);
239
+ const issues = blindCast<
240
+ readonly SchemaDiffIssue<SqlSchemaDiffNode>[],
241
+ 'both trees are PostgresDatabaseSchemaNodes, so every diff-issue node is a SqlSchemaDiffNode'
242
+ >(diffSchemas(expected, paddedActual)).filter((issue) => {
243
+ if (issue.reason !== 'not-expected') return true;
244
+ if (isClusterScopedIssue(issue)) return true;
245
+ const granularity = classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity);
246
+ const namespaceSegment = issue.path[1];
247
+ if (namespaceSegment === undefined) return true;
248
+ const owned = granularity === 'structural' ? structuralOwned : relationalOwned;
249
+ return owned.has(namespaceSegment);
250
+ });
251
+ return { expected, actual: paddedActual, issues };
252
+ }