@prisma-next/target-postgres 0.14.0-dev.5 → 0.14.0-dev.51

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 (238) hide show
  1. package/dist/authoring-DzHOdWTl.mjs +364 -0
  2. package/dist/authoring-DzHOdWTl.mjs.map +1 -0
  3. package/dist/canonicalize-Bn3BM1Cn.mjs +46 -0
  4. package/dist/canonicalize-Bn3BM1Cn.mjs.map +1 -0
  5. package/dist/canonicalize-CAbXtVtB.d.mts +37 -0
  6. package/dist/canonicalize-CAbXtVtB.d.mts.map +1 -0
  7. package/dist/{codec-ids-CnXu9Qy3.d.mts → codec-ids-BzrFF-I4.d.mts} +3 -2
  8. package/dist/codec-ids-BzrFF-I4.d.mts.map +1 -0
  9. package/dist/{codec-ids-BvytN2P8.mjs → codec-ids-C_-Hj6bL.mjs} +3 -2
  10. package/dist/codec-ids-C_-Hj6bL.mjs.map +1 -0
  11. package/dist/codec-ids.d.mts +2 -2
  12. package/dist/codec-ids.mjs +2 -2
  13. package/dist/{codec-types-DHCkwPKE.d.mts → codec-types-BDVmvKAW.d.mts} +3 -2
  14. package/dist/codec-types-BDVmvKAW.d.mts.map +1 -0
  15. package/dist/codec-types.d.mts +1 -1
  16. package/dist/{codecs--0A5_4Bq.d.mts → codecs-Dk2sxGLv.d.mts} +77 -4
  17. package/dist/codecs-Dk2sxGLv.d.mts.map +1 -0
  18. package/dist/codecs.d.mts +1 -1
  19. package/dist/codecs.mjs +117 -2
  20. package/dist/codecs.mjs.map +1 -1
  21. package/dist/contract-free.d.mts +8 -3
  22. package/dist/contract-free.d.mts.map +1 -1
  23. package/dist/contract-free.mjs +4 -4
  24. package/dist/control-policy-DUFgy9jO.mjs +1103 -0
  25. package/dist/control-policy-DUFgy9jO.mjs.map +1 -0
  26. package/dist/control.d.mts +2 -2
  27. package/dist/control.d.mts.map +1 -1
  28. package/dist/control.mjs +757 -35
  29. package/dist/control.mjs.map +1 -1
  30. package/dist/data-transform-BOWpliq8.mjs.map +1 -1
  31. package/dist/{data-transform-DDgWdB5o.d.mts → data-transform-DPzwBMhW.d.mts} +3 -3
  32. package/dist/{data-transform-DDgWdB5o.d.mts.map → data-transform-DPzwBMhW.d.mts.map} +1 -1
  33. package/dist/data-transform.d.mts +1 -1
  34. package/dist/{ddl-QDyOSeLc.mjs → ddl-ujxH2A7r.mjs} +63 -6
  35. package/dist/ddl-ujxH2A7r.mjs.map +1 -0
  36. package/dist/ddl.d.mts +3 -2
  37. package/dist/ddl.mjs +2 -2
  38. package/dist/default-normalizer.d.mts +1 -1
  39. package/dist/default-normalizer.d.mts.map +1 -1
  40. package/dist/default-normalizer.mjs +247 -1
  41. package/dist/default-normalizer.mjs.map +1 -0
  42. package/dist/descriptor-meta-CuGDsrG4.mjs +19 -0
  43. package/dist/descriptor-meta-CuGDsrG4.mjs.map +1 -0
  44. package/dist/descriptor-meta-runtime-UwYdV8fD.mjs +12 -0
  45. package/dist/descriptor-meta-runtime-UwYdV8fD.mjs.map +1 -0
  46. package/dist/diff-database-schema-BmSmWcaY.mjs +313 -0
  47. package/dist/diff-database-schema-BmSmWcaY.mjs.map +1 -0
  48. package/dist/diff-database-schema.d.mts +46 -0
  49. package/dist/diff-database-schema.d.mts.map +1 -0
  50. package/dist/diff-database-schema.mjs +2 -0
  51. package/dist/issue-planner.d.mts +35 -11
  52. package/dist/issue-planner.d.mts.map +1 -1
  53. package/dist/issue-planner.mjs +2 -2
  54. package/dist/migration.d.mts +5 -5
  55. package/dist/migration.d.mts.map +1 -1
  56. package/dist/migration.mjs +4 -4
  57. package/dist/namespace-ids-xtp_ZY86.mjs +7 -0
  58. package/dist/namespace-ids-xtp_ZY86.mjs.map +1 -0
  59. package/dist/native-type-normalizer.mjs +37 -1
  60. package/dist/native-type-normalizer.mjs.map +1 -0
  61. package/dist/nodes-CSkPX3rI.d.mts +120 -0
  62. package/dist/nodes-CSkPX3rI.d.mts.map +1 -0
  63. package/dist/{nodes-Bbhs2rwj.mjs → nodes-Dh__NS58.mjs} +56 -2
  64. package/dist/nodes-Dh__NS58.mjs.map +1 -0
  65. package/dist/{op-factory-call-D_p5vxwt.mjs → op-factory-call-BKRnMgrB.mjs} +205 -31
  66. package/dist/op-factory-call-BKRnMgrB.mjs.map +1 -0
  67. package/dist/{op-factory-call-DmQEc3XV.d.mts → op-factory-call-Dt-Jx5JS.d.mts} +46 -15
  68. package/dist/op-factory-call-Dt-Jx5JS.d.mts.map +1 -0
  69. package/dist/op-factory-call.d.mts +2 -2
  70. package/dist/op-factory-call.mjs +2 -2
  71. package/dist/pack.d.mts +115 -3
  72. package/dist/pack.d.mts.map +1 -1
  73. package/dist/pack.mjs +1 -1
  74. package/dist/planner-BMBRPzsv.mjs +367 -0
  75. package/dist/planner-BMBRPzsv.mjs.map +1 -0
  76. package/dist/{planner-ddl-builders-B2wOwLqI.mjs → planner-ddl-builders-B8Nn6nHN.mjs} +12 -27
  77. package/dist/planner-ddl-builders-B8Nn6nHN.mjs.map +1 -0
  78. package/dist/planner-ddl-builders.d.mts +4 -6
  79. package/dist/planner-ddl-builders.d.mts.map +1 -1
  80. package/dist/planner-ddl-builders.mjs +2 -2
  81. package/dist/planner-identity-values-CJPha2Sz.mjs.map +1 -1
  82. package/dist/planner-identity-values.d.mts +8 -2
  83. package/dist/planner-identity-values.d.mts.map +1 -1
  84. package/dist/planner-identity-values.mjs +2 -2
  85. package/dist/{planner-produced-postgres-migration-QqHa2C2l.d.mts → planner-produced-postgres-migration-C0a7I1-e.d.mts} +4 -4
  86. package/dist/{planner-produced-postgres-migration-QqHa2C2l.d.mts.map → planner-produced-postgres-migration-C0a7I1-e.d.mts.map} +1 -1
  87. package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs → planner-produced-postgres-migration-Dp6IO_gj.mjs} +3 -3
  88. package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs.map → planner-produced-postgres-migration-Dp6IO_gj.mjs.map} +1 -1
  89. package/dist/planner-produced-postgres-migration.d.mts +1 -1
  90. package/dist/planner-produced-postgres-migration.mjs +1 -1
  91. package/dist/{planner-sql-checks-jqUUGyQR.mjs → planner-sql-checks-Cze3vMfe.mjs} +2 -2
  92. package/dist/{planner-sql-checks-jqUUGyQR.mjs.map → planner-sql-checks-Cze3vMfe.mjs.map} +1 -1
  93. package/dist/planner-sql-checks.d.mts +2 -2
  94. package/dist/planner-sql-checks.d.mts.map +1 -1
  95. package/dist/planner-sql-checks.mjs +1 -1
  96. package/dist/{planner-target-details-CIY6tLeo.d.mts → planner-target-details-HkP4RrRO.d.mts} +2 -2
  97. package/dist/planner-target-details-HkP4RrRO.d.mts.map +1 -0
  98. package/dist/planner-target-details.d.mts +1 -1
  99. package/dist/planner.d.mts +55 -17
  100. package/dist/planner.d.mts.map +1 -1
  101. package/dist/planner.mjs +3 -2
  102. package/dist/{postgres-contract-serializer-k3TAcPMY.mjs → postgres-contract-view-3xfUgjnC.mjs} +44 -41
  103. package/dist/postgres-contract-view-3xfUgjnC.mjs.map +1 -0
  104. package/dist/postgres-contract-view-C9j5cqP0.d.mts +34 -0
  105. package/dist/postgres-contract-view-C9j5cqP0.d.mts.map +1 -0
  106. package/dist/postgres-database-schema-node-C9bTuMrd.d.mts +190 -0
  107. package/dist/postgres-database-schema-node-C9bTuMrd.d.mts.map +1 -0
  108. package/dist/{postgres-migration-B5jKrXv3.mjs → postgres-migration-D0jwzYDT.mjs} +21 -2
  109. package/dist/postgres-migration-D0jwzYDT.mjs.map +1 -0
  110. package/dist/{postgres-migration-Y4YBJqkS.d.mts → postgres-migration-DFaxuRyI.d.mts} +20 -7
  111. package/dist/postgres-migration-DFaxuRyI.d.mts.map +1 -0
  112. package/dist/postgres-native-enum-xdiqmBf_.mjs +41 -0
  113. package/dist/postgres-native-enum-xdiqmBf_.mjs.map +1 -0
  114. package/dist/postgres-rls-policy--CSddvMR.d.mts +52 -0
  115. package/dist/postgres-rls-policy--CSddvMR.d.mts.map +1 -0
  116. package/dist/{postgres-schema-COGZ1ark.mjs → postgres-schema-CajYAwny.mjs} +135 -7
  117. package/dist/postgres-schema-CajYAwny.mjs.map +1 -0
  118. package/dist/postgres-schema-DqnhQRvR.d.mts +226 -0
  119. package/dist/postgres-schema-DqnhQRvR.d.mts.map +1 -0
  120. package/dist/postgres-table-schema-node-BgaSrxYN.mjs +249 -0
  121. package/dist/postgres-table-schema-node-BgaSrxYN.mjs.map +1 -0
  122. package/dist/render-ops.d.mts +1 -1
  123. package/dist/{render-typescript-KMgosran.mjs → render-typescript-7yqILcwr.mjs} +45 -16
  124. package/dist/render-typescript-7yqILcwr.mjs.map +1 -0
  125. package/dist/render-typescript.mjs +1 -1
  126. package/dist/resolve-ddl-schema-Bv1ZvjX8.mjs +22 -0
  127. package/dist/resolve-ddl-schema-Bv1ZvjX8.mjs.map +1 -0
  128. package/dist/rls-canonicalize.d.mts +2 -0
  129. package/dist/rls-canonicalize.mjs +2 -0
  130. package/dist/runtime.d.mts +6 -8
  131. package/dist/runtime.d.mts.map +1 -1
  132. package/dist/runtime.mjs +3 -3
  133. package/dist/runtime.mjs.map +1 -1
  134. package/dist/schema-ir-annotations.d.mts +15 -0
  135. package/dist/schema-ir-annotations.d.mts.map +1 -0
  136. package/dist/schema-ir-annotations.mjs +2 -0
  137. package/dist/schema-node-kinds-ClScchhi.mjs +76 -0
  138. package/dist/schema-node-kinds-ClScchhi.mjs.map +1 -0
  139. package/dist/types.d.mts +4 -140
  140. package/dist/types.mjs +3 -2
  141. package/package.json +23 -17
  142. package/src/contract-free/checks.ts +73 -0
  143. package/src/contract-free/ddl.ts +45 -1
  144. package/src/core/authoring.ts +287 -2
  145. package/src/core/codec-ids.ts +1 -0
  146. package/src/core/codec-type-map.ts +2 -0
  147. package/src/core/codecs.ts +141 -1
  148. package/src/core/ddl/nodes.ts +94 -2
  149. package/src/core/default-normalizer.ts +122 -2
  150. package/src/core/descriptor-meta.ts +6 -1
  151. package/src/core/entity-kinds.ts +30 -0
  152. package/src/core/migrations/bound-schema.ts +10 -0
  153. package/src/core/migrations/column-ddl-rendering.ts +117 -0
  154. package/src/core/migrations/contract-to-postgres-database-schema-node.ts +149 -0
  155. package/src/core/migrations/control-policy.ts +70 -47
  156. package/src/core/migrations/diff-database-schema.ts +280 -0
  157. package/src/core/migrations/issue-planner.ts +647 -652
  158. package/src/core/migrations/op-factory-call.ts +109 -21
  159. package/src/core/migrations/operations/columns.ts +24 -12
  160. package/src/core/migrations/operations/constraints.ts +1 -1
  161. package/src/core/migrations/operations/data-transform.ts +6 -0
  162. package/src/core/migrations/operations/dependencies.ts +2 -1
  163. package/src/core/migrations/operations/rls.ts +106 -0
  164. package/src/core/migrations/operations/shared.ts +0 -30
  165. package/src/core/migrations/planner-ddl-builders.ts +20 -58
  166. package/src/core/migrations/planner-identity-values.ts +1 -1
  167. package/src/core/migrations/planner-recipes.ts +31 -13
  168. package/src/core/migrations/planner-sql-checks.ts +1 -1
  169. package/src/core/migrations/planner-strategies.ts +248 -216
  170. package/src/core/migrations/planner-target-details.ts +3 -1
  171. package/src/core/migrations/planner.ts +297 -59
  172. package/src/core/migrations/postgres-migration.ts +34 -4
  173. package/src/core/migrations/render-typescript.ts +42 -15
  174. package/src/core/migrations/resolve-ddl-schema.ts +26 -0
  175. package/src/core/migrations/runner.ts +10 -16
  176. package/src/core/migrations/verify-postgres-namespaces.ts +47 -30
  177. package/src/core/namespace-ids.ts +3 -0
  178. package/src/core/postgres-contract-serializer.ts +41 -71
  179. package/src/core/postgres-contract-view.ts +48 -0
  180. package/src/core/postgres-native-enum.ts +51 -0
  181. package/src/core/postgres-rls-policy.ts +64 -0
  182. package/src/core/postgres-role.ts +37 -0
  183. package/src/core/postgres-schema-verifier.ts +10 -7
  184. package/src/core/postgres-schema.ts +62 -14
  185. package/src/core/postgres-validators.ts +27 -0
  186. package/src/core/psl-infer/infer-psl-contract.ts +1068 -0
  187. package/src/core/psl-infer/postgres-default-mapping.ts +16 -0
  188. package/src/core/psl-infer/postgres-type-map.ts +157 -0
  189. package/src/core/rls/canonicalize.ts +48 -0
  190. package/src/core/schema-ir/postgres-database-schema-node.ts +60 -0
  191. package/src/core/schema-ir/postgres-namespace-schema-node.ts +60 -0
  192. package/src/core/schema-ir/postgres-policy-schema-node.ts +90 -0
  193. package/src/core/schema-ir/postgres-role-schema-node.ts +63 -0
  194. package/src/core/schema-ir/postgres-table-schema-node.ts +118 -0
  195. package/src/core/schema-ir/schema-node-kinds.ts +106 -0
  196. package/src/exports/contract-free.ts +7 -1
  197. package/src/exports/control.ts +27 -33
  198. package/src/exports/ddl.ts +4 -0
  199. package/src/exports/diff-database-schema.ts +7 -0
  200. package/src/exports/issue-planner.ts +1 -1
  201. package/src/exports/migration.ts +1 -0
  202. package/src/exports/op-factory-call.ts +1 -0
  203. package/src/exports/planner-ddl-builders.ts +0 -2
  204. package/src/exports/planner-identity-values.ts +4 -1
  205. package/src/exports/planner.ts +1 -0
  206. package/src/exports/rls-canonicalize.ts +6 -0
  207. package/src/exports/runtime.ts +1 -0
  208. package/src/exports/schema-ir-annotations.ts +1 -0
  209. package/src/exports/types.ts +28 -0
  210. package/dist/codec-ids-BvytN2P8.mjs.map +0 -1
  211. package/dist/codec-ids-CnXu9Qy3.d.mts.map +0 -1
  212. package/dist/codec-types-DHCkwPKE.d.mts.map +0 -1
  213. package/dist/codecs--0A5_4Bq.d.mts.map +0 -1
  214. package/dist/ddl-QDyOSeLc.mjs.map +0 -1
  215. package/dist/default-normalizer-DyyCHQWs.mjs +0 -131
  216. package/dist/default-normalizer-DyyCHQWs.mjs.map +0 -1
  217. package/dist/descriptor-meta-CpGygXpI.mjs +0 -140
  218. package/dist/descriptor-meta-CpGygXpI.mjs.map +0 -1
  219. package/dist/issue-planner-DL6g3CmE.mjs +0 -824
  220. package/dist/issue-planner-DL6g3CmE.mjs.map +0 -1
  221. package/dist/native-type-normalizer-Bc9XJzWC.mjs +0 -38
  222. package/dist/native-type-normalizer-Bc9XJzWC.mjs.map +0 -1
  223. package/dist/nodes-Bbhs2rwj.mjs.map +0 -1
  224. package/dist/nodes-pLeLgdis.d.mts +0 -67
  225. package/dist/nodes-pLeLgdis.d.mts.map +0 -1
  226. package/dist/op-factory-call-D_p5vxwt.mjs.map +0 -1
  227. package/dist/op-factory-call-DmQEc3XV.d.mts.map +0 -1
  228. package/dist/planner-Bs_baQax.mjs +0 -324
  229. package/dist/planner-Bs_baQax.mjs.map +0 -1
  230. package/dist/planner-ddl-builders-B2wOwLqI.mjs.map +0 -1
  231. package/dist/planner-target-details-CIY6tLeo.d.mts.map +0 -1
  232. package/dist/postgres-contract-serializer-k3TAcPMY.mjs.map +0 -1
  233. package/dist/postgres-migration-B5jKrXv3.mjs.map +0 -1
  234. package/dist/postgres-migration-Y4YBJqkS.d.mts.map +0 -1
  235. package/dist/postgres-schema-COGZ1ark.mjs.map +0 -1
  236. package/dist/render-typescript-KMgosran.mjs.map +0 -1
  237. package/dist/types.d.mts.map +0 -1
  238. package/src/core/postgres-enum-type-schema.ts +0 -17
package/dist/ddl.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { a as PostgresDdlNode, i as PostgresCreateTable, n as PostgresAlterTable, r as PostgresCreateSchema, t as AddColumnAction } from "./nodes-Bbhs2rwj.mjs";
2
- export { AddColumnAction, PostgresAlterTable, PostgresCreateSchema, PostgresCreateTable, PostgresDdlNode };
1
+ import { a as PostgresCreateSchema, c as PostgresDropPolicy, i as PostgresCreatePolicy, n as DropDefaultAction, o as PostgresCreateTable, r as PostgresAlterTable, s as PostgresDdlNode, t as AddColumnAction } from "./nodes-Dh__NS58.mjs";
2
+ export { AddColumnAction, DropDefaultAction, PostgresAlterTable, PostgresCreatePolicy, PostgresCreateSchema, PostgresCreateTable, PostgresDdlNode, PostgresDropPolicy };
@@ -9,7 +9,7 @@ import { ColumnDefault } from "@prisma-next/contract/types";
9
9
  * keeping the introspection layer focused on faithful data capture.
10
10
  *
11
11
  * @param rawDefault - Raw default expression from information_schema.columns.column_default
12
- * @param nativeType - Native column type, used for type-aware parsing (bigint tagging, JSON detection)
12
+ * @param nativeType - Native column type, used for type-aware parsing (array, bigint, JSON)
13
13
  * @returns Normalized ColumnDefault or undefined if the expression cannot be parsed
14
14
  */
15
15
  declare function parsePostgresDefault(rawDefault: string, nativeType?: string): ColumnDefault | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"default-normalizer.d.mts","names":[],"sources":["../src/core/default-normalizer.ts"],"mappings":";;;;;AAgEA;;;;;;;;AAGgB;iBAHA,oBAAA,CACd,UAAA,UACA,UAAA,YACC,aAAa"}
1
+ {"version":3,"file":"default-normalizer.d.mts","names":[],"sources":["../src/core/default-normalizer.ts"],"mappings":";;;;;AA6KA;;;;;;;;AAGgB;iBAHA,oBAAA,CACd,UAAA,UACA,UAAA,YACC,aAAa"}
@@ -1,2 +1,248 @@
1
- import { t as parsePostgresDefault } from "./default-normalizer-DyyCHQWs.mjs";
1
+ //#region src/core/default-normalizer.ts
2
+ /**
3
+ * Pre-compiled regex patterns for performance.
4
+ * These are compiled once at module load time rather than on each function call.
5
+ */
6
+ const NEXTVAL_PATTERN = /^nextval\s*\(/i;
7
+ const NOW_FUNCTION_PATTERN = /^(now\s*\(\s*\)|CURRENT_TIMESTAMP)$/i;
8
+ const CLOCK_TIMESTAMP_PATTERN = /^clock_timestamp\s*\(\s*\)$/i;
9
+ const TIMESTAMP_CAST_SUFFIX = /::timestamp(?:tz|\s+(?:with|without)\s+time\s+zone)?$/i;
10
+ const TEXT_CAST_SUFFIX = /::text$/i;
11
+ const NOW_LITERAL_PATTERN = /^'now'$/i;
12
+ const UUID_PATTERN = /^gen_random_uuid\s*\(\s*\)$/i;
13
+ const UUID_OSSP_PATTERN = /^uuid_generate_v4\s*\(\s*\)$/i;
14
+ const NULL_PATTERN = /^NULL(?:::.+)?$/i;
15
+ const TRUE_PATTERN = /^true$/i;
16
+ const FALSE_PATTERN = /^false$/i;
17
+ const NUMERIC_PATTERN = /^-?\d+(\.\d+)?$/;
18
+ const STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:"[^"]+"|[\w\s]+)(?:\(\d+\))?)?$/;
19
+ /**
20
+ * Matches a Postgres array literal default of the form `'{...}'::elemtype[]`.
21
+ * The literal body is captured in group 1; the cast (including `[]`) is optional.
22
+ * Examples: `'{}'::text[]`, `'{1,2}'::integer[]`, `'{}'`
23
+ */
24
+ const ARRAY_LITERAL_PATTERN = /^'(\{.*\})'(?:::.+\[\])?$/;
25
+ /**
26
+ * Returns the canonical expression for a timestamp default function, or undefined
27
+ * if the expression is not a recognized timestamp default.
28
+ *
29
+ * Keeps now()/CURRENT_TIMESTAMP and clock_timestamp() distinct:
30
+ * - now(), CURRENT_TIMESTAMP, ('now'::text)::timestamp... → 'now()'
31
+ * - clock_timestamp(), clock_timestamp()::timestamptz → 'clock_timestamp()'
32
+ *
33
+ * These are semantically different in Postgres: now() returns the transaction
34
+ * start time (constant within a transaction), while clock_timestamp() returns
35
+ * the actual wall-clock time (can differ across rows in a single INSERT).
36
+ */
37
+ function canonicalizeTimestampDefault(expr) {
38
+ if (NOW_FUNCTION_PATTERN.test(expr)) return "now()";
39
+ if (CLOCK_TIMESTAMP_PATTERN.test(expr)) return "clock_timestamp()";
40
+ if (!TIMESTAMP_CAST_SUFFIX.test(expr)) return void 0;
41
+ let inner = expr.replace(TIMESTAMP_CAST_SUFFIX, "").trim();
42
+ if (inner.startsWith("(") && inner.endsWith(")")) inner = inner.slice(1, -1).trim();
43
+ if (NOW_FUNCTION_PATTERN.test(inner)) return "now()";
44
+ if (CLOCK_TIMESTAMP_PATTERN.test(inner)) return "clock_timestamp()";
45
+ inner = inner.replace(TEXT_CAST_SUFFIX, "").trim();
46
+ if (NOW_LITERAL_PATTERN.test(inner)) return "now()";
47
+ }
48
+ /**
49
+ * Splits a Postgres array literal body (without the enclosing braces) into its
50
+ * element tokens, honouring quoting. A comma only separates elements when it is
51
+ * outside double quotes; inside a quoted element a doubled quote (`""`) or a
52
+ * backslash-escaped quote (`\"`) is a literal quote, and a backslash escapes the
53
+ * next character. Returns undefined if the body is malformed (e.g. an unbalanced
54
+ * quote).
55
+ */
56
+ function splitArrayElements(inner) {
57
+ const tokens = [];
58
+ let current = "";
59
+ let inQuotes = false;
60
+ let quoted = false;
61
+ for (let i = 0; i < inner.length; i++) {
62
+ const char = inner[i];
63
+ if (inQuotes) {
64
+ if (char === "\\") {
65
+ const next = inner[i + 1];
66
+ if (next === void 0) return void 0;
67
+ current += next;
68
+ i++;
69
+ continue;
70
+ }
71
+ if (char === "\"") {
72
+ if (inner[i + 1] === "\"") {
73
+ current += "\"";
74
+ i++;
75
+ continue;
76
+ }
77
+ inQuotes = false;
78
+ continue;
79
+ }
80
+ current += char;
81
+ continue;
82
+ }
83
+ if (char === "\"") {
84
+ inQuotes = true;
85
+ quoted = true;
86
+ continue;
87
+ }
88
+ if (char === ",") {
89
+ tokens.push({
90
+ value: current,
91
+ quoted
92
+ });
93
+ current = "";
94
+ quoted = false;
95
+ continue;
96
+ }
97
+ current += char;
98
+ }
99
+ if (inQuotes) return void 0;
100
+ tokens.push({
101
+ value: current,
102
+ quoted
103
+ });
104
+ return tokens;
105
+ }
106
+ /**
107
+ * Parses a Postgres array literal body (`{...}`) into a JS array of primitives.
108
+ * Returns undefined if the body cannot be reliably parsed.
109
+ *
110
+ * Handles:
111
+ * - `{}` → `[]`
112
+ * - `{elem1,elem2,...}` → `[elem1, elem2, ...]` with numeric and string element coercion
113
+ * - quoted elements that contain commas, doubled/escaped quotes, and the literal
114
+ * strings `NULL`/`true`/`false` (a quoted token is always a string)
115
+ */
116
+ function parseArrayLiteralBody(body) {
117
+ const inner = body.slice(1, -1).trim();
118
+ if (inner === "") return [];
119
+ const tokens = splitArrayElements(inner);
120
+ if (tokens === void 0) return void 0;
121
+ const result = [];
122
+ for (const token of tokens) {
123
+ if (token.quoted) {
124
+ result.push(token.value);
125
+ continue;
126
+ }
127
+ const el = token.value.trim();
128
+ if (el.toUpperCase() === "NULL") {
129
+ result.push(null);
130
+ continue;
131
+ }
132
+ if (el === "true") {
133
+ result.push(true);
134
+ continue;
135
+ }
136
+ if (el === "false") {
137
+ result.push(false);
138
+ continue;
139
+ }
140
+ if (NUMERIC_PATTERN.test(el)) {
141
+ result.push(Number(el));
142
+ continue;
143
+ }
144
+ return;
145
+ }
146
+ return result;
147
+ }
148
+ /**
149
+ * Parses a raw Postgres column default expression into a normalized ColumnDefault.
150
+ * This enables semantic comparison between contract defaults and introspected schema defaults.
151
+ *
152
+ * Used by the migration diff layer to normalize raw database defaults during comparison,
153
+ * keeping the introspection layer focused on faithful data capture.
154
+ *
155
+ * @param rawDefault - Raw default expression from information_schema.columns.column_default
156
+ * @param nativeType - Native column type, used for type-aware parsing (array, bigint, JSON)
157
+ * @returns Normalized ColumnDefault or undefined if the expression cannot be parsed
158
+ */
159
+ function parsePostgresDefault(rawDefault, nativeType) {
160
+ const trimmed = rawDefault.trim();
161
+ const normalizedType = nativeType?.toLowerCase();
162
+ const isBigInt = normalizedType === "bigint" || normalizedType === "int8";
163
+ const isArrayType = normalizedType?.endsWith("[]") ?? false;
164
+ if (NEXTVAL_PATTERN.test(trimmed)) return {
165
+ kind: "function",
166
+ expression: "autoincrement()"
167
+ };
168
+ if (isArrayType) {
169
+ const arrayMatch = trimmed.match(ARRAY_LITERAL_PATTERN);
170
+ if (arrayMatch?.[1] !== void 0) {
171
+ const parsed = parseArrayLiteralBody(arrayMatch[1]);
172
+ if (parsed !== void 0) return {
173
+ kind: "literal",
174
+ value: parsed
175
+ };
176
+ }
177
+ }
178
+ const canonicalTimestamp = canonicalizeTimestampDefault(trimmed);
179
+ if (canonicalTimestamp) return {
180
+ kind: "function",
181
+ expression: canonicalTimestamp
182
+ };
183
+ if (UUID_PATTERN.test(trimmed)) return {
184
+ kind: "function",
185
+ expression: "gen_random_uuid()"
186
+ };
187
+ if (UUID_OSSP_PATTERN.test(trimmed)) return {
188
+ kind: "function",
189
+ expression: "gen_random_uuid()"
190
+ };
191
+ if (NULL_PATTERN.test(trimmed)) return {
192
+ kind: "literal",
193
+ value: null
194
+ };
195
+ if (TRUE_PATTERN.test(trimmed)) return {
196
+ kind: "literal",
197
+ value: true
198
+ };
199
+ if (FALSE_PATTERN.test(trimmed)) return {
200
+ kind: "literal",
201
+ value: false
202
+ };
203
+ if (NUMERIC_PATTERN.test(trimmed)) {
204
+ const num = Number(trimmed);
205
+ if (!Number.isFinite(num)) return void 0;
206
+ if (isBigInt && !Number.isSafeInteger(num)) return {
207
+ kind: "literal",
208
+ value: trimmed
209
+ };
210
+ return {
211
+ kind: "literal",
212
+ value: num
213
+ };
214
+ }
215
+ const stringMatch = trimmed.match(STRING_LITERAL_PATTERN);
216
+ if (stringMatch?.[1] !== void 0) {
217
+ const unescaped = stringMatch[1].replace(/''/g, "'");
218
+ if (normalizedType === "json" || normalizedType === "jsonb") try {
219
+ return {
220
+ kind: "literal",
221
+ value: JSON.parse(unescaped)
222
+ };
223
+ } catch {}
224
+ if (isBigInt && NUMERIC_PATTERN.test(unescaped)) {
225
+ const num = Number(unescaped);
226
+ if (Number.isSafeInteger(num)) return {
227
+ kind: "literal",
228
+ value: num
229
+ };
230
+ return {
231
+ kind: "literal",
232
+ value: unescaped
233
+ };
234
+ }
235
+ return {
236
+ kind: "literal",
237
+ value: unescaped
238
+ };
239
+ }
240
+ return {
241
+ kind: "function",
242
+ expression: trimmed
243
+ };
244
+ }
245
+ //#endregion
2
246
  export { parsePostgresDefault };
247
+
248
+ //# sourceMappingURL=default-normalizer.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"default-normalizer.mjs","names":[],"sources":["../src/core/default-normalizer.ts"],"sourcesContent":["import type { ColumnDefault, JsonValue } from '@prisma-next/contract/types';\n\n/**\n * Pre-compiled regex patterns for performance.\n * These are compiled once at module load time rather than on each function call.\n */\nconst NEXTVAL_PATTERN = /^nextval\\s*\\(/i;\nconst NOW_FUNCTION_PATTERN = /^(now\\s*\\(\\s*\\)|CURRENT_TIMESTAMP)$/i;\nconst CLOCK_TIMESTAMP_PATTERN = /^clock_timestamp\\s*\\(\\s*\\)$/i;\nconst TIMESTAMP_CAST_SUFFIX = /::timestamp(?:tz|\\s+(?:with|without)\\s+time\\s+zone)?$/i;\nconst TEXT_CAST_SUFFIX = /::text$/i;\nconst NOW_LITERAL_PATTERN = /^'now'$/i;\nconst UUID_PATTERN = /^gen_random_uuid\\s*\\(\\s*\\)$/i;\nconst UUID_OSSP_PATTERN = /^uuid_generate_v4\\s*\\(\\s*\\)$/i;\nconst NULL_PATTERN = /^NULL(?:::.+)?$/i;\nconst TRUE_PATTERN = /^true$/i;\nconst FALSE_PATTERN = /^false$/i;\nconst NUMERIC_PATTERN = /^-?\\d+(\\.\\d+)?$/;\nconst STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:\"[^\"]+\"|[\\w\\s]+)(?:\\(\\d+\\))?)?$/;\n\n/**\n * Matches a Postgres array literal default of the form `'{...}'::elemtype[]`.\n * The literal body is captured in group 1; the cast (including `[]`) is optional.\n * Examples: `'{}'::text[]`, `'{1,2}'::integer[]`, `'{}'`\n */\nconst ARRAY_LITERAL_PATTERN = /^'(\\{.*\\})'(?:::.+\\[\\])?$/;\n\n/**\n * Returns the canonical expression for a timestamp default function, or undefined\n * if the expression is not a recognized timestamp default.\n *\n * Keeps now()/CURRENT_TIMESTAMP and clock_timestamp() distinct:\n * - now(), CURRENT_TIMESTAMP, ('now'::text)::timestamp... → 'now()'\n * - clock_timestamp(), clock_timestamp()::timestamptz → 'clock_timestamp()'\n *\n * These are semantically different in Postgres: now() returns the transaction\n * start time (constant within a transaction), while clock_timestamp() returns\n * the actual wall-clock time (can differ across rows in a single INSERT).\n */\nfunction canonicalizeTimestampDefault(expr: string): string | undefined {\n if (NOW_FUNCTION_PATTERN.test(expr)) return 'now()';\n if (CLOCK_TIMESTAMP_PATTERN.test(expr)) return 'clock_timestamp()';\n\n if (!TIMESTAMP_CAST_SUFFIX.test(expr)) return undefined;\n\n let inner = expr.replace(TIMESTAMP_CAST_SUFFIX, '').trim();\n\n if (inner.startsWith('(') && inner.endsWith(')')) {\n inner = inner.slice(1, -1).trim();\n }\n\n if (NOW_FUNCTION_PATTERN.test(inner)) return 'now()';\n if (CLOCK_TIMESTAMP_PATTERN.test(inner)) return 'clock_timestamp()';\n\n inner = inner.replace(TEXT_CAST_SUFFIX, '').trim();\n if (NOW_LITERAL_PATTERN.test(inner)) return 'now()';\n\n return undefined;\n}\n\ntype ArrayElementToken = { readonly value: string; readonly quoted: boolean };\n\n/**\n * Splits a Postgres array literal body (without the enclosing braces) into its\n * element tokens, honouring quoting. A comma only separates elements when it is\n * outside double quotes; inside a quoted element a doubled quote (`\"\"`) or a\n * backslash-escaped quote (`\\\"`) is a literal quote, and a backslash escapes the\n * next character. Returns undefined if the body is malformed (e.g. an unbalanced\n * quote).\n */\nfunction splitArrayElements(inner: string): readonly ArrayElementToken[] | undefined {\n const tokens: ArrayElementToken[] = [];\n let current = '';\n let inQuotes = false;\n let quoted = false;\n\n for (let i = 0; i < inner.length; i++) {\n const char = inner[i];\n if (inQuotes) {\n if (char === '\\\\') {\n const next = inner[i + 1];\n if (next === undefined) return undefined;\n current += next;\n i++;\n continue;\n }\n if (char === '\"') {\n if (inner[i + 1] === '\"') {\n current += '\"';\n i++;\n continue;\n }\n inQuotes = false;\n continue;\n }\n current += char;\n continue;\n }\n if (char === '\"') {\n inQuotes = true;\n quoted = true;\n continue;\n }\n if (char === ',') {\n tokens.push({ value: current, quoted });\n current = '';\n quoted = false;\n continue;\n }\n current += char;\n }\n\n if (inQuotes) return undefined;\n tokens.push({ value: current, quoted });\n return tokens;\n}\n\n/**\n * Parses a Postgres array literal body (`{...}`) into a JS array of primitives.\n * Returns undefined if the body cannot be reliably parsed.\n *\n * Handles:\n * - `{}` → `[]`\n * - `{elem1,elem2,...}` → `[elem1, elem2, ...]` with numeric and string element coercion\n * - quoted elements that contain commas, doubled/escaped quotes, and the literal\n * strings `NULL`/`true`/`false` (a quoted token is always a string)\n */\nfunction parseArrayLiteralBody(body: string): readonly JsonValue[] | undefined {\n const inner = body.slice(1, -1).trim();\n if (inner === '') return [];\n const tokens = splitArrayElements(inner);\n if (tokens === undefined) return undefined;\n const result: JsonValue[] = [];\n for (const token of tokens) {\n if (token.quoted) {\n // A quoted token is always a string — `\"NULL\"`, `\"true\"`, `\"1\"` are the\n // literal text, never the keyword/number.\n result.push(token.value);\n continue;\n }\n const el = token.value.trim();\n if (el.toUpperCase() === 'NULL') {\n result.push(null);\n continue;\n }\n if (el === 'true') {\n result.push(true);\n continue;\n }\n if (el === 'false') {\n result.push(false);\n continue;\n }\n if (NUMERIC_PATTERN.test(el)) {\n result.push(Number(el));\n continue;\n }\n return undefined;\n }\n return result;\n}\n\n/**\n * Parses a raw Postgres column default expression into a normalized ColumnDefault.\n * This enables semantic comparison between contract defaults and introspected schema defaults.\n *\n * Used by the migration diff layer to normalize raw database defaults during comparison,\n * keeping the introspection layer focused on faithful data capture.\n *\n * @param rawDefault - Raw default expression from information_schema.columns.column_default\n * @param nativeType - Native column type, used for type-aware parsing (array, bigint, JSON)\n * @returns Normalized ColumnDefault or undefined if the expression cannot be parsed\n */\nexport function parsePostgresDefault(\n rawDefault: string,\n nativeType?: string,\n): ColumnDefault | undefined {\n const trimmed = rawDefault.trim();\n const normalizedType = nativeType?.toLowerCase();\n const isBigInt = normalizedType === 'bigint' || normalizedType === 'int8';\n const isArrayType = normalizedType?.endsWith('[]') ?? false;\n\n if (NEXTVAL_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'autoincrement()' };\n }\n\n if (isArrayType) {\n const arrayMatch = trimmed.match(ARRAY_LITERAL_PATTERN);\n if (arrayMatch?.[1] !== undefined) {\n const parsed = parseArrayLiteralBody(arrayMatch[1]);\n if (parsed !== undefined) {\n return { kind: 'literal', value: parsed };\n }\n }\n }\n\n const canonicalTimestamp = canonicalizeTimestampDefault(trimmed);\n if (canonicalTimestamp) {\n return { kind: 'function', expression: canonicalTimestamp };\n }\n\n if (UUID_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'gen_random_uuid()' };\n }\n\n if (UUID_OSSP_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'gen_random_uuid()' };\n }\n\n if (NULL_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: null };\n }\n\n if (TRUE_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: true };\n }\n if (FALSE_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: false };\n }\n\n if (NUMERIC_PATTERN.test(trimmed)) {\n const num = Number(trimmed);\n if (!Number.isFinite(num)) return undefined;\n if (isBigInt && !Number.isSafeInteger(num)) {\n return { kind: 'literal', value: trimmed };\n }\n return { kind: 'literal', value: num };\n }\n\n const stringMatch = trimmed.match(STRING_LITERAL_PATTERN);\n if (stringMatch?.[1] !== undefined) {\n const unescaped = stringMatch[1].replace(/''/g, \"'\");\n if (normalizedType === 'json' || normalizedType === 'jsonb') {\n try {\n return { kind: 'literal', value: JSON.parse(unescaped) };\n } catch {\n // Keep legacy behavior for malformed/non-JSON string content.\n }\n }\n if (isBigInt && NUMERIC_PATTERN.test(unescaped)) {\n const num = Number(unescaped);\n if (Number.isSafeInteger(num)) {\n return { kind: 'literal', value: num };\n }\n return { kind: 'literal', value: unescaped };\n }\n return { kind: 'literal', value: unescaped };\n }\n\n return { kind: 'function', expression: trimmed };\n}\n"],"mappings":";;;;;AAMA,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;AAC7B,MAAM,0BAA0B;AAChC,MAAM,wBAAwB;AAC9B,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAC5B,MAAM,eAAe;AACrB,MAAM,oBAAoB;AAC1B,MAAM,eAAe;AACrB,MAAM,eAAe;AACrB,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;AACxB,MAAM,yBAAyB;;;;;;AAO/B,MAAM,wBAAwB;;;;;;;;;;;;;AAc9B,SAAS,6BAA6B,MAAkC;CACtE,IAAI,qBAAqB,KAAK,IAAI,GAAG,OAA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T_NAMESPACE_ID } from "./namespace-ids-xtp_ZY86.mjs";
2
+ import { i as postgresCreateNamespace } from "./postgres-schema-CajYAwny.mjs";
3
+ import { i as postgresAuthoringTypes, n as postgresAuthoringFieldPresets, r as postgresAuthoringPslBlockDescriptors, t as postgresAuthoringEntityTypes } from "./authoring-DzHOdWTl.mjs";
4
+ import { t as postgresTargetDescriptorMetaRuntime } from "./descriptor-meta-runtime-UwYdV8fD.mjs";
5
+ const postgresTargetDescriptorMeta = {
6
+ ...postgresTargetDescriptorMetaRuntime,
7
+ defaultNamespaceId: DEFAULT_NAMESPACE_ID,
8
+ authoring: {
9
+ type: postgresAuthoringTypes,
10
+ field: postgresAuthoringFieldPresets,
11
+ entityTypes: postgresAuthoringEntityTypes,
12
+ pslBlockDescriptors: postgresAuthoringPslBlockDescriptors,
13
+ createNamespace: postgresCreateNamespace
14
+ }
15
+ };
16
+ //#endregion
17
+ export { postgresTargetDescriptorMeta as t };
18
+
19
+ //# sourceMappingURL=descriptor-meta-CuGDsrG4.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"descriptor-meta-CuGDsrG4.mjs","names":[],"sources":["../src/core/descriptor-meta.ts"],"sourcesContent":["import type { CodecTypes } from '../exports/codec-types';\nimport {\n postgresAuthoringEntityTypes,\n postgresAuthoringFieldPresets,\n postgresAuthoringPslBlockDescriptors,\n postgresAuthoringTypes,\n} from './authoring';\nimport { postgresTargetDescriptorMetaRuntime } from './descriptor-meta-runtime';\nimport { DEFAULT_NAMESPACE_ID } from './namespace-ids';\nimport { postgresCreateNamespace } from './postgres-schema';\n\nconst postgresTargetDescriptorMetaBase = {\n ...postgresTargetDescriptorMetaRuntime,\n defaultNamespaceId: DEFAULT_NAMESPACE_ID,\n authoring: {\n type: postgresAuthoringTypes,\n field: postgresAuthoringFieldPresets,\n entityTypes: postgresAuthoringEntityTypes,\n pslBlockDescriptors: postgresAuthoringPslBlockDescriptors,\n createNamespace: postgresCreateNamespace,\n },\n} as const;\n\nexport const postgresTargetDescriptorMeta: typeof postgresTargetDescriptorMetaBase & {\n readonly __codecTypes?: CodecTypes;\n} = postgresTargetDescriptorMetaBase;\n"],"mappings":";;;;AAuBA,MAAa,+BAET;CAbF,GAAG;CACH,oBAAoB;CACpB,WAAW;EACT,MAAM;EACN,OAAO;EACP,aAAa;EACb,qBAAqB;EACrB,iBAAiB;CACnB;AAKE"}
@@ -0,0 +1,12 @@
1
+ const postgresTargetDescriptorMetaRuntime = {
2
+ kind: "target",
3
+ familyId: "sql",
4
+ targetId: "postgres",
5
+ id: "postgres",
6
+ version: "0.0.1",
7
+ capabilities: {}
8
+ };
9
+ //#endregion
10
+ export { postgresTargetDescriptorMetaRuntime as t };
11
+
12
+ //# sourceMappingURL=descriptor-meta-runtime-UwYdV8fD.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"descriptor-meta-runtime-UwYdV8fD.mjs","names":[],"sources":["../src/core/descriptor-meta-runtime.ts"],"sourcesContent":["// Runtime-safe slice of the postgres target descriptor metadata.\n//\n// This file exists separately from ./descriptor-meta on purpose: the runtime\n// plane reads only `kind/familyId/targetId/id/version/capabilities` (plus the\n// `__codecTypes` phantom). The `authoring` slot lives on the pack/control\n// descriptor only, because authoring contributions are consumed at\n// contract-construction time by `assembleAuthoringContributions` (control\n// plane) and the PSL interpreter — never at runtime.\n//\n// Keeping the runtime closure free of the `./authoring` import is what lets\n// the bundler tree-shake `@prisma-next/family-sql/control` (and its\n// transitive `verify-sql-schema` chunk) out of the runtime entry. Do not\n// add an `authoring` field here — if you need to, the pack/control meta in\n// `./descriptor-meta` is the right place. See TML-2766 for context.\nimport type { CodecTypes } from '../exports/codec-types';\n\nconst postgresTargetDescriptorMetaRuntimeBase = {\n kind: 'target',\n familyId: 'sql',\n targetId: 'postgres',\n id: 'postgres',\n version: '0.0.1',\n capabilities: {},\n} as const;\n\nexport const postgresTargetDescriptorMetaRuntime: typeof postgresTargetDescriptorMetaRuntimeBase & {\n readonly __codecTypes?: CodecTypes;\n} = postgresTargetDescriptorMetaRuntimeBase;\n"],"mappings":"AAyBA,MAAa,sCAET;CAVF,MAAM;CACN,UAAU;CACV,UAAU;CACV,IAAI;CACJ,SAAS;CACT,cAAc,CAAC;AAKb"}
@@ -0,0 +1,313 @@
1
+ import { r as isPostgresSchema } from "./postgres-schema-CajYAwny.mjs";
2
+ import { r as postgresDiffSubjectGranularity } from "./schema-node-kinds-ClScchhi.mjs";
3
+ import { a as PostgresDatabaseSchemaNode, i as PostgresNamespaceSchemaNode, n as PostgresRoleSchemaNode, r as PostgresPolicySchemaNode, t as PostgresTableSchemaNode } from "./postgres-table-schema-node-BgaSrxYN.mjs";
4
+ import { t as resolveDdlSchemaForNamespaceStorage } from "./resolve-ddl-schema-Bv1ZvjX8.mjs";
5
+ import { i as resolvePostgresNodeIssueControlPolicySubject } from "./control-policy-DUFgy9jO.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, resolveSemanticSatisfaction } 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
+ const ddlSchema = resolveDdlSchemaForNamespaceStorage(contract.storage, ns.id);
60
+ ownedSchemas.push(ddlSchema);
61
+ const sqlTables = contractNamespaceToSchemaIR(contract.storage, ns.id, options).tables;
62
+ const policiesByTable = /* @__PURE__ */ new Map();
63
+ for (const policy of Object.values(ns.policy)) {
64
+ const list = policiesByTable.get(policy.tableName) ?? [];
65
+ list.push(toPolicyNode(policy, ddlSchema));
66
+ policiesByTable.set(policy.tableName, list);
67
+ }
68
+ const tables = {};
69
+ for (const tableName of Object.keys(ns.table)) {
70
+ const sqlTable = sqlTables[tableName];
71
+ if (sqlTable === void 0) continue;
72
+ const foreignKeys = sqlTable.foreignKeys.map((fk) => new SqlForeignKeyIR({
73
+ columns: fk.columns,
74
+ referencedTable: fk.referencedTable,
75
+ referencedColumns: fk.referencedColumns,
76
+ ...ifDefined("referencedSchema", fk.referencedSchema),
77
+ ...ifDefined("name", fk.name),
78
+ ...ifDefined("onDelete", fk.onDelete),
79
+ ...ifDefined("onUpdate", fk.onUpdate),
80
+ ...ifDefined("annotations", fk.annotations),
81
+ resolvedReferencedNamespace: resolveDdlSchemaForNamespaceStorage(contract.storage, fk.referencedSchema ?? UNBOUND_NAMESPACE_ID)
82
+ }));
83
+ tables[tableName] = new PostgresTableSchemaNode({
84
+ name: sqlTable.name,
85
+ columns: sqlTable.columns,
86
+ foreignKeys,
87
+ uniques: sqlTable.uniques,
88
+ indexes: sqlTable.indexes,
89
+ ...ifDefined("primaryKey", sqlTable.primaryKey),
90
+ ...ifDefined("annotations", sqlTable.annotations),
91
+ ...ifDefined("checks", sqlTable.checks),
92
+ policies: policiesByTable.get(tableName) ?? []
93
+ });
94
+ }
95
+ for (const [tableName, tablePolicies] of policiesByTable) if (!(tableName in tables)) {
96
+ const policyName = tablePolicies[0]?.name ?? "(unknown)";
97
+ throw new Error(`contract-to-postgres-database-schema-node: policy "${policyName}" references table "${tableName}" not present in namespace "${ddlSchema}"`);
98
+ }
99
+ namespaces[ddlSchema] = new PostgresNamespaceSchemaNode({
100
+ schemaName: ddlSchema,
101
+ tables,
102
+ nativeEnumTypeNames: []
103
+ });
104
+ for (const role of Object.values(ns.role)) roles.push(new PostgresRoleSchemaNode({
105
+ name: role.name,
106
+ namespaceId: role.namespaceId
107
+ }));
108
+ }
109
+ return new PostgresDatabaseSchemaNode({
110
+ namespaces,
111
+ roles,
112
+ existingSchemas: ownedSchemas,
113
+ pgVersion: ""
114
+ });
115
+ }
116
+ //#endregion
117
+ //#region src/core/migrations/diff-database-schema.ts
118
+ function ownedSchemaNames(expected) {
119
+ const policyNamespaces = Object.values(expected.namespaces).flatMap((ns) => Object.values(ns.tables).flatMap((t) => t.policies.map((p) => p.namespaceId)));
120
+ return new Set([...policyNamespaces, ...expected.existingSchemas]);
121
+ }
122
+ /**
123
+ * Applies the family's semantic-satisfaction normalization across a Postgres
124
+ * tree pair: every actual table with an expected counterpart (paired by
125
+ * namespace id, then table id) gets its unique/index child lists adjusted;
126
+ * everything else passes through untouched.
127
+ */
128
+ function normalizePostgresActualForDiff(expected, actual) {
129
+ const namespaces = {};
130
+ for (const [nsId, actualNs] of Object.entries(actual.namespaces)) {
131
+ const expectedNs = expected.namespaces[nsId];
132
+ if (expectedNs === void 0) {
133
+ namespaces[nsId] = actualNs;
134
+ continue;
135
+ }
136
+ const tables = {};
137
+ for (const [tableName, actualTable] of Object.entries(actualNs.tables)) {
138
+ const expectedTable = expectedNs.tables[tableName];
139
+ if (expectedTable === void 0) {
140
+ tables[tableName] = actualTable;
141
+ continue;
142
+ }
143
+ const adjusted = resolveSemanticSatisfaction({
144
+ expectedUniques: expectedTable.uniques,
145
+ expectedIndexes: expectedTable.indexes,
146
+ actualUniques: actualTable.uniques,
147
+ actualIndexes: actualTable.indexes
148
+ });
149
+ tables[tableName] = new PostgresTableSchemaNode({
150
+ name: actualTable.name,
151
+ columns: actualTable.columns,
152
+ foreignKeys: actualTable.foreignKeys,
153
+ uniques: adjusted.actualUniques,
154
+ indexes: adjusted.actualIndexes,
155
+ ...ifDefined("primaryKey", actualTable.primaryKey),
156
+ ...ifDefined("annotations", actualTable.annotations),
157
+ ...ifDefined("checks", actualTable.checks),
158
+ policies: [...actualTable.policies]
159
+ });
160
+ }
161
+ namespaces[nsId] = new PostgresNamespaceSchemaNode({
162
+ schemaName: actualNs.schemaName,
163
+ tables,
164
+ nativeEnumTypeNames: actualNs.nativeEnumTypeNames
165
+ });
166
+ }
167
+ return new PostgresDatabaseSchemaNode({
168
+ namespaces,
169
+ roles: [...actual.roles],
170
+ existingSchemas: [...actual.existingSchemas],
171
+ pgVersion: actual.pgVersion
172
+ });
173
+ }
174
+ /**
175
+ * Drops contract namespaces that declare no tables from the verdict-diff
176
+ * expected tree and the relational owned-schema set. The legacy relational
177
+ * walk skipped a table-less namespace (e.g. an enums-only schema) before
178
+ * pairing, so neither its DDL schema's absence nor that schema's live
179
+ * relational contents ever reached the verdict — the pruned tree
180
+ * reproduces that. The prune loses no expected policies: policies attach
181
+ * to tables, so a table-less namespace carries none (the projection
182
+ * throws on a policy referencing an absent table). Live policies in a
183
+ * pruned schema remain governed via the full owned set (see
184
+ * {@link diffPostgresSchema}).
185
+ */
186
+ function pruneTableLessNamespaces(expected) {
187
+ const namespaces = Object.fromEntries(Object.entries(expected.namespaces).filter(([, ns]) => Object.keys(ns.tables).length > 0));
188
+ return new PostgresDatabaseSchemaNode({
189
+ namespaces,
190
+ roles: [...expected.roles],
191
+ existingSchemas: expected.existingSchemas.filter((s) => namespaces[s] !== void 0),
192
+ pgVersion: expected.pgVersion
193
+ });
194
+ }
195
+ /**
196
+ * Resolves a verdict-diff issue's subject table's declared control policy
197
+ * directly from the contract, by delegating to the same node-typed resolver
198
+ * ({@link resolvePostgresNodeIssueControlPolicySubject}) the planner uses to
199
+ * gate DDL calls. `undefined` when the issue resolves to no contract table.
200
+ */
201
+ function resolveControlPolicy(issue, contract) {
202
+ return resolvePostgresNodeIssueControlPolicySubject(blindCast(issue), contract)?.explicitNodeControlPolicy;
203
+ }
204
+ /**
205
+ * The Postgres full-tree node diff for the family verify verdict: derive
206
+ * the expected tree (resolved leaf values, expander threaded, FK schemas
207
+ * resolved, table-less namespaces pruned), normalize the actual tree for
208
+ * semantic satisfaction, run the generic
209
+ * differ, and scope out `not-expected` findings under namespaces the
210
+ * contract does not own. Ownership is role-aware, mirroring the legacy
211
+ * decomposition: relational extras check the PRUNED owned set (the legacy
212
+ * per-namespace walk never visited a table-less namespace, so its live
213
+ * relational contents are invisible), while `structural` extras (RLS
214
+ * policies) check the FULL owned set (the legacy policy diff governed
215
+ * every contract schema regardless of tables — RLS governance does not
216
+ * shrink because a namespace declares no tables). The codec `verifyType`
217
+ * hooks run once per contract namespace with tables against that
218
+ * namespace's paired actual node (the hooks read namespace-scoped state
219
+ * such as `nativeEnumTypeNames`).
220
+ */
221
+ function diffPostgresSchema(input) {
222
+ const postgresContract = blindCast(input.contract);
223
+ PostgresDatabaseSchemaNode.assert(input.schema);
224
+ const actual = input.schema;
225
+ const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, {
226
+ annotationNamespace: "pg",
227
+ ...ifDefined("expandNativeType", buildNativeTypeExpander(input.frameworkComponents))
228
+ });
229
+ const expected = pruneTableLessNamespaces(fullExpected);
230
+ const normalizedActual = normalizePostgresActualForDiff(expected, actual);
231
+ const relationalOwned = ownedSchemaNames(expected);
232
+ const structuralOwned = ownedSchemaNames(fullExpected);
233
+ return {
234
+ issues: diffSchemas(expected, normalizedActual).filter((issue) => {
235
+ if (issue.reason !== "not-expected") return true;
236
+ const namespaceSegment = issue.path[1];
237
+ if (namespaceSegment === void 0) return true;
238
+ return (classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity) === "structural" ? structuralOwned : relationalOwned).has(namespaceSegment);
239
+ }),
240
+ resolveControlPolicy: (issue) => resolveControlPolicy(issue, postgresContract),
241
+ namespacePairs: Object.values(expected.namespaces).map((ns) => ({ actual: actual.namespaces[ns.schemaName] }))
242
+ };
243
+ }
244
+ /**
245
+ * Adds an empty namespace node to the actual tree for every expected namespace
246
+ * absent from it. The relational plan diff pairs on namespace: a contract
247
+ * namespace whose live schema does not exist yet must surface each of its
248
+ * tables as `not-found` (→ `CREATE TABLE`), NOT as a single namespace
249
+ * `not-found` that subtree-coalescing would collapse (leaving `CREATE SCHEMA`
250
+ * with no tables). Padding makes the namespaces pair, so only table/column/
251
+ * policy drift surfaces; `CREATE SCHEMA` comes separately from the synthesized
252
+ * namespace-presence stitch (`verifyPostgresNamespacePresence`), never from the
253
+ * tree diff — matching the retired per-namespace-paired relational walk, which
254
+ * paired a missing schema against an empty namespace node.
255
+ */
256
+ function padActualNamespaces(expected, actual) {
257
+ const namespaces = { ...actual.namespaces };
258
+ let padded = false;
259
+ for (const schemaName of Object.keys(expected.namespaces)) if (namespaces[schemaName] === void 0) {
260
+ namespaces[schemaName] = new PostgresNamespaceSchemaNode({
261
+ schemaName,
262
+ tables: {},
263
+ nativeEnumTypeNames: []
264
+ });
265
+ padded = true;
266
+ }
267
+ if (!padded) return actual;
268
+ return new PostgresDatabaseSchemaNode({
269
+ namespaces,
270
+ roles: [...actual.roles],
271
+ existingSchemas: [...actual.existingSchemas],
272
+ pgVersion: actual.pgVersion
273
+ });
274
+ }
275
+ /**
276
+ * The Postgres planner's diff input: the SAME tree-building
277
+ * `diffPostgresSchema` uses (expander threaded, FK schemas resolved,
278
+ * table-less namespaces pruned, actual normalized for semantic satisfaction,
279
+ * role-aware ownership filter) plus actual namespace padding (so a missing
280
+ * schema's tables surface as `not-found` instead of a swallowed namespace
281
+ * `not-found`). One differ drives both verify and plan; this is the
282
+ * plan-side derivation. The single issue list covers tables / columns /
283
+ * constraints / indexes / defaults AND policies — the caller splits it
284
+ * (relational → `mapNodeIssueToCall`; policy → RLS ops) and stitches in
285
+ * `CREATE SCHEMA` separately.
286
+ */
287
+ function buildPostgresPlanDiff(input) {
288
+ const postgresContract = blindCast(input.contract);
289
+ PostgresDatabaseSchemaNode.assert(input.actualSchema);
290
+ const actual = input.actualSchema;
291
+ const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, {
292
+ annotationNamespace: "pg",
293
+ ...ifDefined("expandNativeType", buildNativeTypeExpander(input.frameworkComponents))
294
+ });
295
+ const expected = pruneTableLessNamespaces(fullExpected);
296
+ const normalizedActual = normalizePostgresActualForDiff(expected, padActualNamespaces(expected, actual));
297
+ const relationalOwned = ownedSchemaNames(expected);
298
+ const structuralOwned = ownedSchemaNames(fullExpected);
299
+ return {
300
+ expected,
301
+ actual: normalizedActual,
302
+ issues: blindCast(diffSchemas(expected, normalizedActual)).filter((issue) => {
303
+ if (issue.reason !== "not-expected") return true;
304
+ const namespaceSegment = issue.path[1];
305
+ if (namespaceSegment === void 0) return true;
306
+ return (classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity) === "structural" ? structuralOwned : relationalOwned).has(namespaceSegment);
307
+ })
308
+ };
309
+ }
310
+ //#endregion
311
+ export { diffPostgresSchema as n, contractToPostgresDatabaseSchemaNode as r, buildPostgresPlanDiff as t };
312
+
313
+ //# sourceMappingURL=diff-database-schema-BmSmWcaY.mjs.map