@prisma-next/target-postgres 0.14.0-dev.7 → 0.14.0-dev.71

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 (265) 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-Cl_hQHg-.mjs +913 -0
  15. package/dist/codecs-Cl_hQHg-.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-CuUhjWnn.mjs +1258 -0
  26. package/dist/control-policy-CuUhjWnn.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-Dqgs-bDc.mjs} +93 -6
  36. package/dist/ddl-Dqgs-bDc.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-UugzVM-U.mjs +22 -0
  44. package/dist/descriptor-meta-UugzVM-U.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-ClN3bkRS.mjs +305 -0
  48. package/dist/diff-database-schema-ClN3bkRS.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-CSIg5XDu.d.mts} +91 -15
  72. package/dist/op-factory-call-CSIg5XDu.d.mts.map +1 -0
  73. package/dist/{op-factory-call-D_p5vxwt.mjs → op-factory-call-DtVSP_7Y.mjs} +400 -32
  74. package/dist/op-factory-call-DtVSP_7Y.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-ChVasl04.mjs +390 -0
  81. package/dist/planner-ChVasl04.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-CXue-6M9.d.mts} +4 -4
  92. package/dist/{planner-produced-postgres-migration-QqHa2C2l.d.mts.map → planner-produced-postgres-migration-CXue-6M9.d.mts.map} +1 -1
  93. package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs → planner-produced-postgres-migration-qpU05c__.mjs} +3 -3
  94. package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs.map → planner-produced-postgres-migration-qpU05c__.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-DkmgGNcv.d.mts} +47 -9
  115. package/dist/postgres-migration-DkmgGNcv.d.mts.map +1 -0
  116. package/dist/{postgres-migration-B5jKrXv3.mjs → postgres-migration-fndp3Mbm.mjs} +69 -45
  117. package/dist/postgres-migration-fndp3Mbm.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 +73 -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-ids.ts +1 -0
  161. package/src/core/codec-type-map.ts +2 -0
  162. package/src/core/codecs.ts +180 -1
  163. package/src/core/ddl/nodes.ts +185 -2
  164. package/src/core/default-normalizer.ts +122 -2
  165. package/src/core/descriptor-meta.ts +10 -1
  166. package/src/core/entity-kinds.ts +41 -0
  167. package/src/core/errors.ts +14 -12
  168. package/src/core/migrations/bound-schema.ts +10 -0
  169. package/src/core/migrations/column-ddl-rendering.ts +117 -0
  170. package/src/core/migrations/contract-to-postgres-database-schema-node.ts +189 -0
  171. package/src/core/migrations/control-policy.ts +217 -65
  172. package/src/core/migrations/diff-database-schema.ts +252 -0
  173. package/src/core/migrations/issue-planner.ts +769 -656
  174. package/src/core/migrations/op-factory-call.ts +273 -21
  175. package/src/core/migrations/operations/columns.ts +24 -12
  176. package/src/core/migrations/operations/constraints.ts +1 -1
  177. package/src/core/migrations/operations/data-transform.ts +6 -0
  178. package/src/core/migrations/operations/dependencies.ts +2 -1
  179. package/src/core/migrations/operations/native-enum-types.ts +62 -0
  180. package/src/core/migrations/operations/rls.ts +187 -0
  181. package/src/core/migrations/operations/shared.ts +0 -30
  182. package/src/core/migrations/planner-ddl-builders.ts +31 -59
  183. package/src/core/migrations/planner-identity-values.ts +1 -1
  184. package/src/core/migrations/planner-recipes.ts +31 -13
  185. package/src/core/migrations/planner-sql-checks.ts +1 -1
  186. package/src/core/migrations/planner-strategies.ts +248 -216
  187. package/src/core/migrations/planner-target-details.ts +3 -1
  188. package/src/core/migrations/planner.ts +357 -67
  189. package/src/core/migrations/postgres-migration.ts +101 -86
  190. package/src/core/migrations/render-typescript.ts +42 -15
  191. package/src/core/migrations/resolve-ddl-schema.ts +26 -0
  192. package/src/core/migrations/runner.ts +11 -16
  193. package/src/core/migrations/verify-postgres-namespaces.ts +46 -31
  194. package/src/core/namespace-ids.ts +3 -0
  195. package/src/core/postgres-contract-serializer.ts +46 -71
  196. package/src/core/postgres-contract-view.ts +48 -0
  197. package/src/core/postgres-native-enum.ts +61 -0
  198. package/src/core/postgres-rls-enablement.ts +34 -0
  199. package/src/core/postgres-rls-policy.ts +64 -0
  200. package/src/core/postgres-role.ts +59 -0
  201. package/src/core/postgres-schema-verifier.ts +10 -7
  202. package/src/core/postgres-schema.ts +85 -15
  203. package/src/core/postgres-validators.ts +34 -0
  204. package/src/core/psl-infer/infer-psl-contract.ts +1273 -0
  205. package/src/core/psl-infer/postgres-default-mapping.ts +16 -0
  206. package/src/core/psl-infer/postgres-type-map.ts +128 -0
  207. package/src/core/rls/canonicalize.ts +48 -0
  208. package/src/core/rls/wire-name.ts +33 -0
  209. package/src/core/schema-ir/node-storage-coordinate.ts +26 -0
  210. package/src/core/schema-ir/postgres-database-schema-node.ts +61 -0
  211. package/src/core/schema-ir/postgres-namespace-schema-node.ts +70 -0
  212. package/src/core/schema-ir/postgres-native-enum-schema-node.ts +83 -0
  213. package/src/core/schema-ir/postgres-policy-schema-node.ts +90 -0
  214. package/src/core/schema-ir/postgres-role-schema-node.ts +65 -0
  215. package/src/core/schema-ir/postgres-table-schema-node.ts +140 -0
  216. package/src/core/schema-ir/schema-node-kinds.ts +122 -0
  217. package/src/core/sql-utils.ts +15 -2
  218. package/src/exports/codecs.ts +3 -0
  219. package/src/exports/contract-free.ts +11 -1
  220. package/src/exports/control.ts +27 -33
  221. package/src/exports/ddl.ts +8 -0
  222. package/src/exports/diff-database-schema.ts +7 -0
  223. package/src/exports/issue-planner.ts +1 -1
  224. package/src/exports/migration.ts +1 -0
  225. package/src/exports/op-factory-call.ts +3 -0
  226. package/src/exports/planner-ddl-builders.ts +0 -2
  227. package/src/exports/planner-identity-values.ts +4 -1
  228. package/src/exports/planner.ts +1 -0
  229. package/src/exports/rls-canonicalize.ts +7 -0
  230. package/src/exports/runtime.ts +1 -0
  231. package/src/exports/schema-ir-annotations.ts +1 -0
  232. package/src/exports/sql-utils.ts +1 -0
  233. package/src/exports/types.ts +37 -0
  234. package/dist/codec-ids-BvytN2P8.mjs.map +0 -1
  235. package/dist/codec-ids-CnXu9Qy3.d.mts.map +0 -1
  236. package/dist/codec-types-DHCkwPKE.d.mts.map +0 -1
  237. package/dist/codecs--0A5_4Bq.d.mts.map +0 -1
  238. package/dist/ddl-QDyOSeLc.mjs.map +0 -1
  239. package/dist/default-normalizer-DyyCHQWs.mjs +0 -131
  240. package/dist/default-normalizer-DyyCHQWs.mjs.map +0 -1
  241. package/dist/descriptor-meta-CpGygXpI.mjs +0 -140
  242. package/dist/descriptor-meta-CpGygXpI.mjs.map +0 -1
  243. package/dist/errors-CUk87ByX.mjs +0 -33
  244. package/dist/errors-CUk87ByX.mjs.map +0 -1
  245. package/dist/issue-planner-DL6g3CmE.mjs +0 -824
  246. package/dist/issue-planner-DL6g3CmE.mjs.map +0 -1
  247. package/dist/native-type-normalizer-Bc9XJzWC.mjs +0 -38
  248. package/dist/native-type-normalizer-Bc9XJzWC.mjs.map +0 -1
  249. package/dist/nodes-Bbhs2rwj.mjs +0 -76
  250. package/dist/nodes-Bbhs2rwj.mjs.map +0 -1
  251. package/dist/nodes-pLeLgdis.d.mts +0 -67
  252. package/dist/nodes-pLeLgdis.d.mts.map +0 -1
  253. package/dist/op-factory-call-D_p5vxwt.mjs.map +0 -1
  254. package/dist/op-factory-call-DmQEc3XV.d.mts.map +0 -1
  255. package/dist/planner-Bs_baQax.mjs +0 -324
  256. package/dist/planner-Bs_baQax.mjs.map +0 -1
  257. package/dist/planner-ddl-builders-B2wOwLqI.mjs.map +0 -1
  258. package/dist/planner-target-details-CIY6tLeo.d.mts.map +0 -1
  259. package/dist/postgres-contract-serializer-k3TAcPMY.mjs.map +0 -1
  260. package/dist/postgres-migration-B5jKrXv3.mjs.map +0 -1
  261. package/dist/postgres-migration-Y4YBJqkS.d.mts.map +0 -1
  262. package/dist/postgres-schema-COGZ1ark.mjs.map +0 -1
  263. package/dist/render-typescript-KMgosran.mjs.map +0 -1
  264. package/dist/types.d.mts.map +0 -1
  265. package/src/core/postgres-enum-type-schema.ts +0 -17
package/dist/control.mjs CHANGED
@@ -1,18 +1,21 @@
1
- import { t as postgresTargetDescriptorMeta } from "./descriptor-meta-CpGygXpI.mjs";
2
- import { t as parsePostgresDefault } from "./default-normalizer-DyyCHQWs.mjs";
3
- import { t as normalizeSchemaNativeType } from "./native-type-normalizer-Bc9XJzWC.mjs";
4
- import { t as createPostgresMigrationPlanner } from "./planner-Bs_baQax.mjs";
5
- import { a as renderDefaultLiteral } from "./planner-ddl-builders-B2wOwLqI.mjs";
6
- import { t as PostgresContractSerializer } from "./postgres-contract-serializer-k3TAcPMY.mjs";
1
+ import { t as postgresTargetDescriptorMeta } from "./descriptor-meta-UugzVM-U.mjs";
2
+ import { a as postgresDiffSubjectGranularity, i as postgresDiffSubjectEntityKind } from "./postgres-table-schema-node-D6LvInCe.mjs";
3
+ import { i as PostgresDatabaseSchemaNode } from "./postgres-role-schema-node-Cm-j0ZGM.mjs";
4
+ import { n as diffPostgresSchema, r as contractToPostgresDatabaseSchemaNode } from "./diff-database-schema-ClN3bkRS.mjs";
5
+ import { r as renderDefaultLiteral } from "./planner-ddl-builders-BKlmGDJl.mjs";
6
+ import { n as PostgresContractSerializer } from "./postgres-contract-view-C3LPCLP_.mjs";
7
+ import { t as createPostgresMigrationPlanner } from "./planner-ChVasl04.mjs";
8
+ import { UNBOUND_NAMESPACE_ID, coordinateKey, elementCoordinates } from "@prisma-next/framework-components/ir";
7
9
  import { blindCast } from "@prisma-next/utils/casts";
8
- import { contractToSchemaIR, extractCodecControlHooks, runnerFailure, runnerSuccess } from "@prisma-next/family-sql/control";
10
+ import { buildNativeTypeExpander, runnerFailure, runnerSuccess } from "@prisma-next/family-sql/control";
9
11
  import { ifDefined } from "@prisma-next/utils/defined";
10
- import { verifySqlSchema } from "@prisma-next/family-sql/schema-verify";
11
- import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
12
- import { notOk, ok, okVoid } from "@prisma-next/utils/result";
12
+ import { SqlSchemaIR, SqlTableIR } from "@prisma-next/sql-schema-ir/types";
13
13
  import { APP_SPACE_ID } from "@prisma-next/framework-components/control";
14
- import { SqlQueryError } from "@prisma-next/sql-errors";
14
+ import { notOk, ok, okVoid } from "@prisma-next/utils/result";
15
15
  import { SqlSchemaVerifierBase } from "@prisma-next/family-sql/ir";
16
+ import { SqlQueryError } from "@prisma-next/sql-errors";
17
+ import { buildChildRelationField, deriveRelationFieldName, inferRelations, mapDefault, parseRawDefault, toEnumMemberName, toEnumName, toFieldName, toModelName, toNamedTypeName } from "@prisma-next/family-sql/psl-infer";
18
+ import { UNSPECIFIED_PSL_NAMESPACE_ID, makePslNamespace, makePslNamespaceEntries } from "@prisma-next/framework-components/psl-ast";
16
19
  //#region src/core/migrations/runner.ts
17
20
  const LOCK_DOMAIN = "prisma_next.contract.marker";
18
21
  /**
@@ -74,19 +77,15 @@ var PostgresMigrationRunner = class {
74
77
  applyValue = applyResult.value;
75
78
  }
76
79
  if (space === APP_SPACE_ID) {
77
- const schemaIR = await this.family.introspect({
80
+ const schemaNode = await this.family.introspect({
78
81
  driver,
79
82
  contract: options.destinationContract
80
83
  });
81
- const schemaVerifyResult = verifySqlSchema({
84
+ const schemaVerifyResult = this.family.verifySchema({
82
85
  contract: options.destinationContract,
83
- schema: schemaIR,
86
+ schema: schemaNode,
84
87
  strict: options.strictVerification ?? true,
85
- context: options.context ?? {},
86
- typeMetadataRegistry: this.family.typeMetadataRegistry,
87
- frameworkComponents: options.frameworkComponents,
88
- normalizeDefault: parsePostgresDefault,
89
- normalizeNativeType: normalizeSchemaNativeType
88
+ frameworkComponents: options.frameworkComponents
90
89
  });
91
90
  if (!schemaVerifyResult.ok) return runnerFailure("SCHEMA_VERIFY_FAILED", schemaVerifyResult.summary, {
92
91
  why: "The resulting database schema does not satisfy the destination contract.",
@@ -361,7 +360,8 @@ var PostgresMigrationRunner = class {
361
360
  to: edge.to,
362
361
  migrationName: edge.dirName,
363
362
  migrationHash: edge.migrationHash,
364
- operations: edgeOps
363
+ operations: edgeOps,
364
+ ...ifDefined("destinationContractJson", edge.destinationContractJson)
365
365
  }
366
366
  });
367
367
  }
@@ -387,10 +387,10 @@ var PostgresMigrationRunner = class {
387
387
  /**
388
388
  * Postgres target `SchemaVerifier` concretion. Plugs into the
389
389
  * SQL-shared verification surface; production verification today still
390
- * routes through the legacy `verifySqlSchema` entry point, which
391
- * carries options (codec hooks, normalizers, framework components)
392
- * that the framework-level `SchemaVerifyOptions` shape does not yet
393
- * surface.
390
+ * routes through the family verify verdict (`verifySqlSchemaByDiff` over
391
+ * `diffPostgresSchema`), which carries options (codec hooks,
392
+ * normalizers, framework components) that the framework-level
393
+ * `SchemaVerifyOptions` shape does not yet surface.
394
394
  *
395
395
  * The hooks return the empty list pending the call-site migration that
396
396
  * routes the existing verifier behaviour through the SPI — at that
@@ -408,18 +408,838 @@ var PostgresSchemaVerifier = class extends SqlSchemaVerifierBase {
408
408
  }
409
409
  };
410
410
  //#endregion
411
- //#region src/exports/control.ts
412
- function buildNativeTypeExpander(frameworkComponents) {
413
- if (!frameworkComponents) return;
414
- const codecHooks = extractCodecControlHooks(frameworkComponents);
415
- return (input) => {
416
- if (!input.typeParams) return input.nativeType;
417
- if (!input.codecId) return input.nativeType;
418
- const hooks = codecHooks.get(input.codecId);
419
- if (!hooks?.expandNativeType) return input.nativeType;
420
- return hooks.expandNativeType(input);
411
+ //#region src/core/psl-infer/postgres-default-mapping.ts
412
+ const POSTGRES_FUNCTION_ATTRIBUTES = { "gen_random_uuid()": "@default(dbgenerated(\"gen_random_uuid()\"))" };
413
+ function formatDbGeneratedAttribute(expression) {
414
+ return `@default(dbgenerated(${JSON.stringify(expression)}))`;
415
+ }
416
+ function createPostgresDefaultMapping() {
417
+ return {
418
+ functionAttributes: POSTGRES_FUNCTION_ATTRIBUTES,
419
+ fallbackFunctionAttribute: formatDbGeneratedAttribute
421
420
  };
422
421
  }
422
+ //#endregion
423
+ //#region src/core/psl-infer/postgres-type-map.ts
424
+ const POSTGRES_TO_PSL = {
425
+ text: "String",
426
+ bool: "Boolean",
427
+ boolean: "Boolean",
428
+ int4: "Int",
429
+ integer: "Int",
430
+ int8: "BigInt",
431
+ bigint: "BigInt",
432
+ float8: "Float",
433
+ "double precision": "Float",
434
+ numeric: "Decimal",
435
+ decimal: "Decimal",
436
+ timestamptz: "DateTime",
437
+ "timestamp with time zone": "DateTime",
438
+ jsonb: "Json",
439
+ bytea: "Bytes"
440
+ };
441
+ const PRESERVED_NATIVE_TYPES = {
442
+ "character varying": {
443
+ pslType: "String",
444
+ attributeName: "db.VarChar"
445
+ },
446
+ character: {
447
+ pslType: "String",
448
+ attributeName: "db.Char"
449
+ },
450
+ char: {
451
+ pslType: "String",
452
+ attributeName: "db.Char"
453
+ },
454
+ varchar: {
455
+ pslType: "String",
456
+ attributeName: "db.VarChar"
457
+ },
458
+ uuid: {
459
+ pslType: "String",
460
+ attributeName: "db.Uuid"
461
+ },
462
+ int2: {
463
+ pslType: "Int",
464
+ attributeName: "db.SmallInt"
465
+ },
466
+ smallint: {
467
+ pslType: "Int",
468
+ attributeName: "db.SmallInt"
469
+ },
470
+ float4: {
471
+ pslType: "Float",
472
+ attributeName: "db.Real"
473
+ },
474
+ real: {
475
+ pslType: "Float",
476
+ attributeName: "db.Real"
477
+ },
478
+ timestamp: {
479
+ pslType: "DateTime",
480
+ attributeName: "db.Timestamp"
481
+ },
482
+ "timestamp without time zone": {
483
+ pslType: "DateTime",
484
+ attributeName: "db.Timestamp"
485
+ },
486
+ date: {
487
+ pslType: "DateTime",
488
+ attributeName: "db.Date"
489
+ },
490
+ time: {
491
+ pslType: "DateTime",
492
+ attributeName: "db.Time"
493
+ },
494
+ "time without time zone": {
495
+ pslType: "DateTime",
496
+ attributeName: "db.Time"
497
+ },
498
+ timetz: {
499
+ pslType: "DateTime",
500
+ attributeName: "db.Timetz"
501
+ },
502
+ "time with time zone": {
503
+ pslType: "DateTime",
504
+ attributeName: "db.Timetz"
505
+ },
506
+ json: {
507
+ pslType: "Json",
508
+ attributeName: "db.Json"
509
+ }
510
+ };
511
+ const PARAMETERIZED_NATIVE_TYPES = {
512
+ "character varying": {
513
+ pslType: "String",
514
+ attributeName: "db.VarChar"
515
+ },
516
+ character: {
517
+ pslType: "String",
518
+ attributeName: "db.Char"
519
+ },
520
+ char: {
521
+ pslType: "String",
522
+ attributeName: "db.Char"
523
+ },
524
+ varchar: {
525
+ pslType: "String",
526
+ attributeName: "db.VarChar"
527
+ },
528
+ numeric: {
529
+ pslType: "Decimal",
530
+ attributeName: "db.Numeric"
531
+ },
532
+ timestamp: {
533
+ pslType: "DateTime",
534
+ attributeName: "db.Timestamp"
535
+ },
536
+ timestamptz: {
537
+ pslType: "DateTime",
538
+ attributeName: "db.Timestamptz"
539
+ },
540
+ time: {
541
+ pslType: "DateTime",
542
+ attributeName: "db.Time"
543
+ },
544
+ timetz: {
545
+ pslType: "DateTime",
546
+ attributeName: "db.Timetz"
547
+ }
548
+ };
549
+ const PARAMETERIZED_TYPE_PATTERN = /^(.+?)\((.+)\)$/;
550
+ function getOwnMappingValue(map, key) {
551
+ return Object.hasOwn(map, key) ? map[key] : void 0;
552
+ }
553
+ function getOwnRecordValue(map, key) {
554
+ return Object.hasOwn(map, key) ? map[key] : void 0;
555
+ }
556
+ function createNativeTypeAttribute(name, args) {
557
+ return args && args.length > 0 ? {
558
+ name,
559
+ args
560
+ } : { name };
561
+ }
562
+ function splitTypeParameterList(params) {
563
+ return params.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
564
+ }
565
+ function createPostgresTypeMap(enumTypeNames) {
566
+ return { resolve(nativeType) {
567
+ if (enumTypeNames?.has(nativeType)) return {
568
+ pslType: nativeType,
569
+ nativeType
570
+ };
571
+ const paramMatch = nativeType.match(PARAMETERIZED_TYPE_PATTERN);
572
+ if (paramMatch) {
573
+ const [, baseType = nativeType, params = ""] = paramMatch;
574
+ const template = getOwnRecordValue(PARAMETERIZED_NATIVE_TYPES, baseType);
575
+ if (template) return {
576
+ pslType: template.pslType,
577
+ nativeType,
578
+ typeParams: {
579
+ baseType,
580
+ params
581
+ },
582
+ nativeTypeAttribute: createNativeTypeAttribute(template.attributeName, splitTypeParameterList(params))
583
+ };
584
+ }
585
+ const preservedType = getOwnRecordValue(PRESERVED_NATIVE_TYPES, nativeType);
586
+ if (preservedType) return {
587
+ pslType: preservedType.pslType,
588
+ nativeType,
589
+ nativeTypeAttribute: createNativeTypeAttribute(preservedType.attributeName)
590
+ };
591
+ const pslType = getOwnMappingValue(POSTGRES_TO_PSL, nativeType);
592
+ if (pslType) return {
593
+ pslType,
594
+ nativeType
595
+ };
596
+ return {
597
+ unsupported: true,
598
+ nativeType
599
+ };
600
+ } };
601
+ }
602
+ //#endregion
603
+ //#region src/core/psl-infer/infer-psl-contract.ts
604
+ const SYNTHETIC_SPAN = {
605
+ start: {
606
+ offset: 0,
607
+ line: 1,
608
+ column: 1
609
+ },
610
+ end: {
611
+ offset: 0,
612
+ line: 1,
613
+ column: 1
614
+ }
615
+ };
616
+ const PSL_SCALAR_TYPE_NAMES = /* @__PURE__ */ new Set([
617
+ "String",
618
+ "Boolean",
619
+ "Int",
620
+ "BigInt",
621
+ "Float",
622
+ "Decimal",
623
+ "DateTime",
624
+ "Json",
625
+ "Bytes"
626
+ ]);
627
+ /**
628
+ * Coordinates every element a set of already-assembled contracts declare,
629
+ * mapped to the {@link SqlDescribedContractSpace} that owns it and keyed by
630
+ * the shared {@link coordinateKey} helper. `contract infer` uses this to omit
631
+ * database elements a stack extension pack's contract space already
632
+ * describes — reusing the same coordinate walk the contract-space aggregate
633
+ * and cross-space collision check use (`elementCoordinates`), rather than a
634
+ * bespoke per-entity-kind membership test — and, for a foreign key whose
635
+ * referenced table an entry owns, to resolve the qualified cross-space
636
+ * relation it describes.
637
+ */
638
+ function describedContractOwners(describedContracts) {
639
+ const owners = /* @__PURE__ */ new Map();
640
+ for (const entry of describedContracts) for (const coordinate of elementCoordinates(entry.contract.storage)) owners.set(coordinateKey(coordinate), entry);
641
+ return owners;
642
+ }
643
+ function resolveCrossSpaceTarget(owner, namespaceId, tableName) {
644
+ const domainNamespace = owner.contract.domain.namespaces[namespaceId];
645
+ if (domainNamespace === void 0) return;
646
+ for (const [modelName, model] of Object.entries(domainNamespace.models)) {
647
+ const storage = blindCast(model.storage);
648
+ if (storage.namespaceId !== namespaceId || storage.table !== tableName) continue;
649
+ const fieldNamesByColumn = /* @__PURE__ */ new Map();
650
+ for (const [fieldName, fieldStorage] of Object.entries(storage.fields)) fieldNamesByColumn.set(fieldStorage.column, { fieldName });
651
+ return {
652
+ spaceId: owner.spaceId,
653
+ namespaceId,
654
+ modelName,
655
+ fieldNamesByColumn
656
+ };
657
+ }
658
+ }
659
+ /**
660
+ * Classifies every foreign key on a surviving table into one of three cases.
661
+ * A foreign key that carries a `referencedSchema` is checked against the
662
+ * pack-owned coordinates first, so a pack-owned target wins even when a local
663
+ * table happens to share its bare name; only foreign keys with no owned
664
+ * coordinate fall through to the local/dangling distinction.
665
+ *
666
+ * - **Cross-space**: `referencedSchema` is set and a described contract owns
667
+ * the coordinate `(referencedSchema, 'table', referencedTable)`. The
668
+ * referenced table is absent from the tree (omitted because the pack
669
+ * describes it, or never introspected — `contract infer` walks a single
670
+ * namespace). Removed from `foreignKeys` (so `inferRelations` never falls
671
+ * back to a bare, unqualified table name for it) and replaced with a
672
+ * `RelationField` qualified with the owning pack's space id and namespace
673
+ * id. `owners` holds only pack-declared coordinates, so an app's own table
674
+ * (e.g. `public.users`) is never owned and cannot be captured here.
675
+ * - **Local**: not a pack-owned coordinate, and the referenced table survived
676
+ * introspection — left untouched, `inferRelations` handles it as before.
677
+ * - **Dangling**: not a pack-owned coordinate, and the referenced table is
678
+ * neither in the tree nor owned by any described contract. Removed from
679
+ * `foreignKeys`, keeping the scalar column, rather than emitting a relation
680
+ * to a model that was never defined.
681
+ *
682
+ * A pack that owns the referenced coordinate but declares no domain model
683
+ * mapped to it is malformed; that case throws rather than degrading to a
684
+ * silent drop, which would contradict the dangling definition above.
685
+ */
686
+ function resolveForeignKeys(tables, owners) {
687
+ const resultTables = {};
688
+ const extraRelationsByTable = /* @__PURE__ */ new Map();
689
+ const crossSpaceFieldNamesByTable = /* @__PURE__ */ new Map();
690
+ for (const [tableName, table] of Object.entries(tables)) {
691
+ const keptForeignKeys = [];
692
+ for (const fk of table.foreignKeys) {
693
+ if (fk.referencedSchema !== void 0) {
694
+ const owner = owners.get(coordinateKey({
695
+ namespaceId: fk.referencedSchema,
696
+ entityKind: "table",
697
+ entityName: fk.referencedTable
698
+ }));
699
+ if (owner !== void 0) {
700
+ const target = resolveCrossSpaceTarget(owner, fk.referencedSchema, fk.referencedTable);
701
+ if (target === void 0) throw new Error(`contract infer: described contract space "${owner.spaceId}" owns storage coordinate "${fk.referencedSchema}.${fk.referencedTable}" but declares no domain model mapped to it. A pack that describes a table must also declare the domain model it maps to; this pack is malformed.`);
702
+ if (!crossSpaceFieldNamesByTable.has(fk.referencedTable)) crossSpaceFieldNamesByTable.set(fk.referencedTable, target.fieldNamesByColumn);
703
+ const fieldName = deriveRelationFieldName(fk.columns, fk.referencedTable);
704
+ const optional = fk.columns.some((columnName) => table.columns[columnName]?.nullable ?? false);
705
+ const relationField = {
706
+ ...buildChildRelationField(fieldName, target.modelName, fk, optional),
707
+ typeNamespaceId: target.namespaceId,
708
+ typeContractSpaceId: target.spaceId
709
+ };
710
+ const existingRelations = extraRelationsByTable.get(tableName);
711
+ if (existingRelations) existingRelations.push(relationField);
712
+ else extraRelationsByTable.set(tableName, [relationField]);
713
+ continue;
714
+ }
715
+ }
716
+ if (tables[fk.referencedTable] !== void 0) keptForeignKeys.push(fk);
717
+ }
718
+ resultTables[tableName] = keptForeignKeys.length === table.foreignKeys.length ? table : new SqlTableIR({
719
+ ...table,
720
+ foreignKeys: keptForeignKeys
721
+ });
722
+ }
723
+ return {
724
+ tables: resultTables,
725
+ extraRelationsByTable,
726
+ crossSpaceFieldNamesByTable
727
+ };
728
+ }
729
+ /**
730
+ * Infers a PSL AST (for `printPsl`) from an introspected Postgres schema tree.
731
+ *
732
+ * Target-owned inference: it walks the `PostgresDatabaseSchemaNode` tree and
733
+ * owns the Postgres dialect knowledge — the native type map and default map.
734
+ * Relation inference, name transforms, generic default mapping, and raw-default
735
+ * parsing are shape-neutral utilities imported from the SQL family.
736
+ *
737
+ * This slice emits relational-only PSL, byte-identical to the prior flat
738
+ * inference: the tree's tables (across its namespaces — `contract infer`
739
+ * introspects a single live namespace) are gathered into the model set and
740
+ * emitted as one `UNSPECIFIED_PSL_NAMESPACE_ID` bucket. Top-level entities
741
+ * (policies/roles → PSL extension blocks) are a later slice.
742
+ *
743
+ * `describedContracts` — the stack's extension packs' already-assembled
744
+ * contracts, each paired with its space id — is consulted while gathering
745
+ * tables: a table whose coordinate `(schemaName, 'table', tableName)` one of
746
+ * those contracts already declares is omitted, before the duplicate-name
747
+ * check below and before relation inference, so it cannot spuriously
748
+ * collide with an app table and never contributes a bare relation field. A
749
+ * surviving table's foreign key into an omitted, pack-owned table is not
750
+ * dropped: {@link resolveForeignKeys} rewrites it into a relation qualified
751
+ * with the pack's space id (`<spaceId>:<namespaceId>.<Model>`) instead.
752
+ */
753
+ function inferPostgresPslContract(tree, describedContracts) {
754
+ const namespaces = Object.values(tree.namespaces);
755
+ const owners = describedContractOwners(describedContracts ?? []);
756
+ const enumDefinitions = /* @__PURE__ */ new Map();
757
+ const packOwnedEnumTypesByNamespace = /* @__PURE__ */ new Map();
758
+ const enumNamespaceNames = /* @__PURE__ */ new Set();
759
+ for (const namespace of namespaces) for (const { typeName, members } of namespace.nativeEnums) {
760
+ const owner = owners.get(coordinateKey({
761
+ namespaceId: namespace.schemaName,
762
+ entityKind: "native_enum",
763
+ entityName: typeName
764
+ }));
765
+ if (owner !== void 0) {
766
+ const owned = packOwnedEnumTypesByNamespace.get(namespace.schemaName) ?? /* @__PURE__ */ new Map();
767
+ owned.set(typeName, owner.spaceId);
768
+ owned.set(`${namespace.schemaName}.${typeName}`, owner.spaceId);
769
+ packOwnedEnumTypesByNamespace.set(namespace.schemaName, owned);
770
+ continue;
771
+ }
772
+ enumDefinitions.set(typeName, members);
773
+ enumNamespaceNames.add(namespace.schemaName);
774
+ }
775
+ const tables = {};
776
+ const tableNamespaceNames = /* @__PURE__ */ new Set();
777
+ for (const namespace of namespaces) {
778
+ const ownedEnumTypes = packOwnedEnumTypesByNamespace.get(namespace.schemaName);
779
+ for (const [tableName, table] of Object.entries(namespace.tables)) {
780
+ if (owners.has(coordinateKey({
781
+ namespaceId: namespace.schemaName,
782
+ entityKind: "table",
783
+ entityName: tableName
784
+ }))) continue;
785
+ if (tables[tableName] !== void 0) throw new Error(`contract infer: duplicate table name "${tableName}" across schemas is not yet supported (single-namespace PSL inference emits one flat bucket; multi-namespace \`namespace { … }\` output is a later slice).`);
786
+ if (ownedEnumTypes !== void 0) for (const column of Object.values(table.columns)) {
787
+ const owningSpaceId = ownedEnumTypes.get(column.nativeType);
788
+ if (owningSpaceId !== void 0) throw new Error(`contract infer: column "${tableName}"."${column.name}" is typed by native enum type "${column.nativeType}", which extension pack space "${owningSpaceId}" already describes. A cross-space enum-typed column has no authorable PSL form yet; describe the table in that pack's contract or retype the column before re-running contract infer.`);
789
+ }
790
+ tables[tableName] = new SqlTableIR(table);
791
+ tableNamespaceNames.add(namespace.schemaName);
792
+ }
793
+ }
794
+ let wrapNamespaceName;
795
+ if (enumDefinitions.size > 0) {
796
+ const contentNamespaces = /* @__PURE__ */ new Set([...enumNamespaceNames, ...tableNamespaceNames]);
797
+ if (contentNamespaces.size > 1) throw new Error(`contract infer: native enum adoption with content across multiple schemas is not yet supported (single-namespace PSL inference emits one \`namespace { … }\` block; multi-namespace output is a later slice). Schemas: ${[...contentNamespaces].sort().join(", ")}.`);
798
+ wrapNamespaceName = [...contentNamespaces][0];
799
+ }
800
+ const { tables: resolvedTables, extraRelationsByTable, crossSpaceFieldNamesByTable } = resolveForeignKeys(tables, owners);
801
+ const schemaIR = new SqlSchemaIR({ tables: resolvedTables });
802
+ const enumTypeNames = new Set(enumDefinitions.keys());
803
+ if (wrapNamespaceName !== void 0) for (const typeName of enumDefinitions.keys()) enumTypeNames.add(`${wrapNamespaceName}.${typeName}`);
804
+ const enumInfo = {
805
+ typeNames: enumTypeNames,
806
+ definitions: enumDefinitions
807
+ };
808
+ return buildPslDocumentAst(schemaIR, {
809
+ typeMap: createPostgresTypeMap(enumInfo.typeNames),
810
+ defaultMapping: createPostgresDefaultMapping(),
811
+ parseRawDefault,
812
+ ...enumDefinitions.size > 0 ? { enumInfo } : {}
813
+ }, {
814
+ extraRelationsByTable,
815
+ crossSpaceFieldNamesByTable
816
+ }, wrapNamespaceName);
817
+ }
818
+ function buildPslDocumentAst(schemaIR, options, foreignKeyExtras, namespaceName) {
819
+ const { typeMap, defaultMapping, parseRawDefault: rawDefaultParser } = options;
820
+ const { extraRelationsByTable, crossSpaceFieldNamesByTable } = foreignKeyExtras;
821
+ const modelNames = buildTopLevelNameMap(Object.keys(schemaIR.tables), toModelName, "model", "table");
822
+ const modelNameMap = new Map([...modelNames].map(([tableName, result]) => [tableName, result.name]));
823
+ const { enumNameMap: bareEnumNameMap, enumBlocks } = buildNativeEnumBlocks(options.enumInfo?.definitions ?? /* @__PURE__ */ new Map(), modelNames);
824
+ const enumNameMap = new Map(bareEnumNameMap);
825
+ if (namespaceName !== void 0) for (const [typeName, pslName] of bareEnumNameMap) enumNameMap.set(`${namespaceName}.${typeName}`, pslName);
826
+ const reservedNamedTypeNames = createReservedNamedTypeNames(modelNames, enumNameMap);
827
+ const fieldNamesByTable = new Map([...crossSpaceFieldNamesByTable, ...buildFieldNamesByTable(schemaIR.tables)]);
828
+ const { relationsByTable } = inferRelations(schemaIR.tables, modelNameMap);
829
+ const namedTypes = seedNamedTypeRegistry(schemaIR, typeMap, enumNameMap, reservedNamedTypeNames);
830
+ const models = [];
831
+ for (const table of Object.values(schemaIR.tables)) models.push(buildModel(table, typeMap, enumNameMap, fieldNamesByTable, namedTypes, defaultMapping, rawDefaultParser, [...relationsByTable.get(table.name) ?? [], ...extraRelationsByTable.get(table.name) ?? []]));
832
+ const sortedModels = topologicalSort(models, schemaIR.tables, modelNameMap);
833
+ const namedTypeEntries = [...namedTypes.entriesByKey.values()].sort((a, b) => a.name.localeCompare(b.name));
834
+ const types = namedTypeEntries.length > 0 ? {
835
+ kind: "types",
836
+ declarations: namedTypeEntries.map(buildNamedTypeDeclaration),
837
+ span: SYNTHETIC_SPAN
838
+ } : void 0;
839
+ return {
840
+ kind: "document",
841
+ sourceId: "<sql-schema-ir>",
842
+ namespaces: [makePslNamespace({
843
+ kind: "namespace",
844
+ name: namespaceName ?? UNSPECIFIED_PSL_NAMESPACE_ID,
845
+ entries: makePslNamespaceEntries(sortedModels, [], enumBlocks),
846
+ span: SYNTHETIC_SPAN
847
+ })],
848
+ ...types ? { types } : {},
849
+ span: SYNTHETIC_SPAN
850
+ };
851
+ }
852
+ /**
853
+ * Builds one `native_enum` extension-block AST node per introspected enum
854
+ * definition. Block names go through the shared top-level transform
855
+ * (`toEnumName`, intra-enum collisions throw like model collisions) and are
856
+ * then reserved against the model names — an enum whose PSL name a model
857
+ * already claims gets a numeric suffix, with `@@map` carrying the real type
858
+ * name. Members print as explicit `member = "value"` pairs: the member name
859
+ * is the sanitized value (deduplicated within the block), the JSON-encoded
860
+ * value carries the truth verbatim.
861
+ */
862
+ function buildNativeEnumBlocks(definitions, modelNames) {
863
+ const enumNames = buildTopLevelNameMap([...definitions.keys()].sort(), toEnumName, "enum", "enum type");
864
+ const usedTopLevelNames = new Set(PSL_SCALAR_TYPE_NAMES);
865
+ for (const result of modelNames.values()) usedTopLevelNames.add(result.name);
866
+ const enumNameMap = /* @__PURE__ */ new Map();
867
+ const enumBlocks = [];
868
+ for (const [typeName, result] of enumNames) {
869
+ const name = createUniqueFieldName(result.name, usedTopLevelNames);
870
+ usedTopLevelNames.add(name);
871
+ enumNameMap.set(typeName, name);
872
+ enumBlocks.push(buildNativeEnumBlock(name, typeName, definitions.get(typeName) ?? []));
873
+ }
874
+ return {
875
+ enumNameMap,
876
+ enumBlocks
877
+ };
878
+ }
879
+ function buildNativeEnumBlock(name, typeName, values) {
880
+ const usedMemberNames = /* @__PURE__ */ new Set();
881
+ const parameters = {};
882
+ for (const value of values) {
883
+ const memberName = createUniqueFieldName(toEnumMemberName(value), usedMemberNames);
884
+ usedMemberNames.add(memberName);
885
+ parameters[memberName] = {
886
+ kind: "value",
887
+ raw: JSON.stringify(value),
888
+ span: SYNTHETIC_SPAN
889
+ };
890
+ }
891
+ return {
892
+ kind: "native_enum",
893
+ keyword: "native_enum",
894
+ name,
895
+ parameters,
896
+ blockAttributes: name === typeName ? [] : [{
897
+ name: "map",
898
+ args: [{
899
+ kind: "positional",
900
+ value: `"${escapePslString(typeName)}"`,
901
+ span: SYNTHETIC_SPAN
902
+ }],
903
+ span: SYNTHETIC_SPAN
904
+ }],
905
+ span: SYNTHETIC_SPAN
906
+ };
907
+ }
908
+ function buildModel(table, typeMap, enumNameMap, fieldNamesByTable, namedTypes, defaultMapping, rawDefaultParser, relationFields) {
909
+ const { name: modelName, map: mapName } = toModelName(table.name);
910
+ const fieldNameMap = fieldNamesByTable.get(table.name);
911
+ const pkColumns = new Set(table.primaryKey?.columns ?? []);
912
+ const isSinglePk = pkColumns.size === 1;
913
+ const singlePkConstraintName = isSinglePk ? table.primaryKey?.name : void 0;
914
+ const uniqueColumns = /* @__PURE__ */ new Map();
915
+ for (const unique of table.uniques) if (unique.columns.length === 1) {
916
+ const [columnName = ""] = unique.columns;
917
+ const existingConstraintName = uniqueColumns.get(columnName);
918
+ if (!uniqueColumns.has(columnName) || existingConstraintName === void 0 && unique.name) uniqueColumns.set(columnName, unique.name);
919
+ }
920
+ const fields = [];
921
+ for (const column of Object.values(table.columns)) fields.push(buildScalarField(column, table, typeMap, enumNameMap, fieldNameMap, namedTypes, defaultMapping, rawDefaultParser, pkColumns, isSinglePk, singlePkConstraintName, uniqueColumns));
922
+ const usedFieldNames = new Set(fields.map((field) => field.name));
923
+ for (const rel of relationFields) fields.push(buildRelationField(rel, table.name, fieldNamesByTable, usedFieldNames));
924
+ const modelAttributes = [];
925
+ if (table.primaryKey && table.primaryKey.columns.length > 1) {
926
+ const pkFieldNames = table.primaryKey.columns.map((columnName) => resolveColumnFieldName(fieldNamesByTable, table.name, columnName));
927
+ modelAttributes.push(buildModelConstraintAttribute("id", pkFieldNames, table.primaryKey.name));
928
+ }
929
+ for (const unique of table.uniques) if (unique.columns.length > 1) {
930
+ const uniqueFieldNames = unique.columns.map((columnName) => resolveColumnFieldName(fieldNamesByTable, table.name, columnName));
931
+ modelAttributes.push(buildModelConstraintAttribute("unique", uniqueFieldNames, unique.name));
932
+ }
933
+ for (const index of table.indexes) if (!index.unique) {
934
+ const indexFieldNames = index.columns.map((columnName) => resolveColumnFieldName(fieldNamesByTable, table.name, columnName));
935
+ modelAttributes.push(buildModelConstraintAttribute("index", indexFieldNames, index.name));
936
+ }
937
+ if (mapName) modelAttributes.push(buildMapAttribute("model", mapName));
938
+ const comment = table.primaryKey ? void 0 : "// WARNING: This table has no primary key in the database";
939
+ return {
940
+ kind: "model",
941
+ name: modelName,
942
+ fields,
943
+ attributes: modelAttributes,
944
+ span: SYNTHETIC_SPAN,
945
+ ...comment !== void 0 ? { comment } : {}
946
+ };
947
+ }
948
+ function buildScalarField(column, table, typeMap, enumNameMap, fieldNameMap, namedTypes, defaultMapping, rawDefaultParser, pkColumns, isSinglePk, singlePkConstraintName, uniqueColumns) {
949
+ const resolvedField = fieldNameMap?.get(column.name);
950
+ const fieldName = resolvedField?.fieldName ?? toFieldName(column.name).name;
951
+ const fieldMap = resolvedField?.fieldMap;
952
+ const resolution = typeMap.resolve(column.nativeType, table.annotations);
953
+ if ("unsupported" in resolution) {
954
+ const attrs = [];
955
+ if (fieldMap !== void 0) attrs.push(buildMapAttribute("field", fieldMap));
956
+ return {
957
+ kind: "field",
958
+ name: fieldName,
959
+ typeName: `Unsupported("${escapePslString(resolution.nativeType)}")`,
960
+ optional: column.nullable,
961
+ list: column.many === true,
962
+ attributes: attrs,
963
+ span: SYNTHETIC_SPAN
964
+ };
965
+ }
966
+ let typeName = resolution.pslType;
967
+ let typeConstructor;
968
+ const enumPslName = enumNameMap.get(column.nativeType);
969
+ if (enumPslName) {
970
+ typeName = enumPslName;
971
+ typeConstructor = {
972
+ kind: "typeConstructor",
973
+ path: ["pg", "enum"],
974
+ args: [positionalArg(enumPslName)],
975
+ span: SYNTHETIC_SPAN
976
+ };
977
+ }
978
+ if (resolution.nativeTypeAttribute && !enumPslName) typeName = resolveNamedTypeName(namedTypes, resolution);
979
+ const attributes = [];
980
+ const isId = isSinglePk && pkColumns.has(column.name);
981
+ if (isId) attributes.push(buildSimpleConstraintFieldAttribute("id", singlePkConstraintName));
982
+ if (column.default !== void 0) {
983
+ const parsed = parseColumnDefault(column.default, column.nativeType, rawDefaultParser);
984
+ if (parsed) {
985
+ const result = mapDefault(parsed, defaultMapping);
986
+ if ("attribute" in result) attributes.push(parseDefaultAttributeString(result.attribute));
987
+ }
988
+ }
989
+ if (uniqueColumns.has(column.name) && !isId) {
990
+ const uniqueConstraintName = uniqueColumns.get(column.name);
991
+ attributes.push(buildSimpleConstraintFieldAttribute("unique", uniqueConstraintName));
992
+ }
993
+ if (fieldMap !== void 0) attributes.push(buildMapAttribute("field", fieldMap));
994
+ return {
995
+ kind: "field",
996
+ name: fieldName,
997
+ typeName,
998
+ ...ifDefined("typeConstructor", typeConstructor),
999
+ optional: column.nullable,
1000
+ list: column.many === true,
1001
+ attributes,
1002
+ span: SYNTHETIC_SPAN
1003
+ };
1004
+ }
1005
+ function buildRelationField(rel, hostTableName, fieldNamesByTable, usedFieldNames) {
1006
+ const fieldName = createUniqueFieldName(rel.fieldName, usedFieldNames);
1007
+ usedFieldNames.add(fieldName);
1008
+ const args = [];
1009
+ if (rel.fields && rel.references) {
1010
+ if (rel.relationName) args.push(namedArg("name", `"${escapePslString(rel.relationName)}"`));
1011
+ args.push(namedArg("fields", `[${rel.fields.map((columnName) => resolveColumnFieldName(fieldNamesByTable, hostTableName, columnName)).join(", ")}]`));
1012
+ args.push(namedArg("references", `[${rel.references.map((columnName) => resolveColumnFieldName(fieldNamesByTable, rel.referencedTableName ?? "", columnName)).join(", ")}]`));
1013
+ if (rel.onDelete) args.push(namedArg("onDelete", rel.onDelete));
1014
+ if (rel.onUpdate) args.push(namedArg("onUpdate", rel.onUpdate));
1015
+ if (rel.fkName) args.push(namedArg("map", `"${escapePslString(rel.fkName)}"`));
1016
+ } else if (rel.relationName) args.push(namedArg("name", `"${escapePslString(rel.relationName)}"`));
1017
+ const attrs = args.length > 0 ? [buildAttribute("field", "relation", args)] : [];
1018
+ return {
1019
+ kind: "field",
1020
+ name: fieldName,
1021
+ typeName: rel.typeName,
1022
+ ...ifDefined("typeNamespaceId", rel.typeNamespaceId),
1023
+ ...ifDefined("typeContractSpaceId", rel.typeContractSpaceId),
1024
+ optional: rel.optional,
1025
+ list: rel.list,
1026
+ attributes: attrs,
1027
+ span: SYNTHETIC_SPAN
1028
+ };
1029
+ }
1030
+ function buildModelConstraintAttribute(name, fields, constraintName) {
1031
+ const args = [positionalArg(`[${fields.join(", ")}]`)];
1032
+ if (constraintName !== void 0) args.push(namedArg("map", `"${escapePslString(constraintName)}"`));
1033
+ return buildAttribute("model", name, args);
1034
+ }
1035
+ function buildSimpleConstraintFieldAttribute(name, constraintName) {
1036
+ if (constraintName === void 0) return buildAttribute("field", name, []);
1037
+ return buildAttribute("field", name, [namedArg("map", `"${escapePslString(constraintName)}"`)]);
1038
+ }
1039
+ function parseDefaultAttributeString(attributeText) {
1040
+ return buildAttribute("field", "default", [positionalArg(attributeText.replace(/^@default\(/, "").replace(/\)$/, ""))]);
1041
+ }
1042
+ function buildMapAttribute(target, mapName) {
1043
+ return buildAttribute(target, "map", [positionalArg(`"${escapePslString(mapName)}"`)]);
1044
+ }
1045
+ function buildAttribute(target, name, args) {
1046
+ return {
1047
+ kind: "attribute",
1048
+ target,
1049
+ name,
1050
+ args,
1051
+ span: SYNTHETIC_SPAN
1052
+ };
1053
+ }
1054
+ function positionalArg(value) {
1055
+ return {
1056
+ kind: "positional",
1057
+ value,
1058
+ span: SYNTHETIC_SPAN
1059
+ };
1060
+ }
1061
+ function namedArg(name, value) {
1062
+ return {
1063
+ kind: "named",
1064
+ name,
1065
+ value,
1066
+ span: SYNTHETIC_SPAN
1067
+ };
1068
+ }
1069
+ function buildNamedTypeDeclaration(entry) {
1070
+ const attribute = buildAttribute("namedType", entry.nativeTypeAttribute.name, (entry.nativeTypeAttribute.args ?? []).map(positionalArg));
1071
+ return {
1072
+ kind: "namedType",
1073
+ name: entry.name,
1074
+ baseType: entry.baseType,
1075
+ attributes: [attribute],
1076
+ span: SYNTHETIC_SPAN
1077
+ };
1078
+ }
1079
+ function escapePslString(value) {
1080
+ return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
1081
+ }
1082
+ /**
1083
+ * Resolves a `SqlColumnIR.default` value into a normalized {@link ColumnDefault}.
1084
+ *
1085
+ * `SqlSchemaIR` types the column default as `string` (a raw database default
1086
+ * expression). Some legacy fixtures and tests still pass already-normalized
1087
+ * `ColumnDefault` objects in the same slot, so we accept either shape
1088
+ * defensively at runtime.
1089
+ */
1090
+ function parseColumnDefault(value, nativeType, rawDefaultParser) {
1091
+ if (typeof value === "string") return rawDefaultParser ? rawDefaultParser(value, nativeType) : void 0;
1092
+ if (value !== null && typeof value === "object" && "kind" in value) return value;
1093
+ }
1094
+ function buildFieldNamesByTable(tables) {
1095
+ const fieldNamesByTable = /* @__PURE__ */ new Map();
1096
+ for (const table of Object.values(tables)) {
1097
+ const assignmentOrder = [...Object.values(table.columns).map((column, index) => {
1098
+ const { name, map } = toFieldName(column.name);
1099
+ return {
1100
+ columnName: column.name,
1101
+ desiredFieldName: name,
1102
+ fieldMap: map,
1103
+ index
1104
+ };
1105
+ })].sort((left, right) => {
1106
+ const mapComparison = Number(left.fieldMap !== void 0) - Number(right.fieldMap !== void 0);
1107
+ if (mapComparison !== 0) return mapComparison;
1108
+ return left.index - right.index;
1109
+ });
1110
+ const usedFieldNames = /* @__PURE__ */ new Set();
1111
+ const tableFieldNames = /* @__PURE__ */ new Map();
1112
+ for (const column of assignmentOrder) {
1113
+ const fieldName = createUniqueFieldName(column.desiredFieldName, usedFieldNames);
1114
+ usedFieldNames.add(fieldName);
1115
+ tableFieldNames.set(column.columnName, {
1116
+ fieldName,
1117
+ fieldMap: column.fieldMap
1118
+ });
1119
+ }
1120
+ fieldNamesByTable.set(table.name, tableFieldNames);
1121
+ }
1122
+ return fieldNamesByTable;
1123
+ }
1124
+ function resolveColumnFieldName(fieldNamesByTable, tableName, columnName) {
1125
+ return fieldNamesByTable.get(tableName)?.get(columnName)?.fieldName ?? toFieldName(columnName).name;
1126
+ }
1127
+ function createUniqueFieldName(desiredName, usedFieldNames) {
1128
+ if (!usedFieldNames.has(desiredName)) return desiredName;
1129
+ let counter = 2;
1130
+ while (usedFieldNames.has(`${desiredName}${counter}`)) counter++;
1131
+ return `${desiredName}${counter}`;
1132
+ }
1133
+ function buildTopLevelNameMap(sources, normalize, kind, sourceKind) {
1134
+ const results = /* @__PURE__ */ new Map();
1135
+ const normalizedToSources = /* @__PURE__ */ new Map();
1136
+ for (const source of sources) {
1137
+ const normalized = normalize(source);
1138
+ results.set(source, normalized);
1139
+ normalizedToSources.set(normalized.name, [...normalizedToSources.get(normalized.name) ?? [], source]);
1140
+ }
1141
+ const duplicates = [...normalizedToSources.entries()].filter(([, conflictingSources]) => conflictingSources.length > 1);
1142
+ if (duplicates.length > 0) {
1143
+ const details = duplicates.map(([normalizedName, conflictingSources]) => `- ${kind} "${normalizedName}" from ${sourceKind}s ${conflictingSources.map((source) => `"${source}"`).join(", ")}`);
1144
+ throw new Error(`PSL ${kind} name collisions detected:\n${details.join("\n")}`);
1145
+ }
1146
+ return results;
1147
+ }
1148
+ function createReservedNamedTypeNames(modelNames, enumNameMap) {
1149
+ const reservedNames = new Set(PSL_SCALAR_TYPE_NAMES);
1150
+ for (const result of modelNames.values()) reservedNames.add(result.name);
1151
+ for (const enumPslName of enumNameMap.values()) reservedNames.add(enumPslName);
1152
+ return reservedNames;
1153
+ }
1154
+ function seedNamedTypeRegistry(schemaIR, typeMap, enumNameMap, reservedNames) {
1155
+ const seeds = /* @__PURE__ */ new Map();
1156
+ for (const tableName of Object.keys(schemaIR.tables).sort()) {
1157
+ const table = schemaIR.tables[tableName];
1158
+ if (!table) continue;
1159
+ for (const columnName of Object.keys(table.columns).sort()) {
1160
+ const column = table.columns[columnName];
1161
+ if (!column) continue;
1162
+ const resolution = typeMap.resolve(column.nativeType, table.annotations);
1163
+ if ("unsupported" in resolution || enumNameMap.has(column.nativeType) || !resolution.nativeTypeAttribute) continue;
1164
+ const signatureKey = createNamedTypeSignatureKey(resolution);
1165
+ if (!seeds.has(signatureKey)) seeds.set(signatureKey, {
1166
+ baseType: resolution.pslType,
1167
+ desiredName: toNamedTypeName(column.name),
1168
+ nativeTypeAttribute: resolution.nativeTypeAttribute
1169
+ });
1170
+ }
1171
+ }
1172
+ const registry = {
1173
+ entriesByKey: /* @__PURE__ */ new Map(),
1174
+ usedNames: new Set(reservedNames)
1175
+ };
1176
+ const sortedSeeds = [...seeds.entries()].sort((left, right) => {
1177
+ const desiredNameComparison = left[1].desiredName.localeCompare(right[1].desiredName);
1178
+ if (desiredNameComparison !== 0) return desiredNameComparison;
1179
+ return left[0].localeCompare(right[0]);
1180
+ });
1181
+ for (const [signatureKey, seed] of sortedSeeds) {
1182
+ const name = createUniqueFieldName(seed.desiredName, registry.usedNames);
1183
+ registry.entriesByKey.set(signatureKey, {
1184
+ name,
1185
+ baseType: seed.baseType,
1186
+ nativeTypeAttribute: seed.nativeTypeAttribute
1187
+ });
1188
+ registry.usedNames.add(name);
1189
+ }
1190
+ return registry;
1191
+ }
1192
+ function resolveNamedTypeName(registry, resolution) {
1193
+ const key = createNamedTypeSignatureKey(resolution);
1194
+ const existing = registry.entriesByKey.get(key);
1195
+ if (existing) return existing.name;
1196
+ throw new Error(`Named type registry was not seeded for native type "${resolution.nativeType}"`);
1197
+ }
1198
+ function createNamedTypeSignatureKey(resolution) {
1199
+ return JSON.stringify({
1200
+ baseType: resolution.pslType,
1201
+ nativeTypeAttribute: resolution.nativeTypeAttribute ? {
1202
+ name: resolution.nativeTypeAttribute.name,
1203
+ args: resolution.nativeTypeAttribute.args ?? null
1204
+ } : null
1205
+ });
1206
+ }
1207
+ function topologicalSort(models, tables, modelNameMap) {
1208
+ const modelByName = /* @__PURE__ */ new Map();
1209
+ for (const model of models) modelByName.set(model.name, model);
1210
+ const deps = /* @__PURE__ */ new Map();
1211
+ const tableToModel = /* @__PURE__ */ new Map();
1212
+ for (const tableName of Object.keys(tables)) {
1213
+ const modelName = modelNameMap.get(tableName);
1214
+ tableToModel.set(tableName, modelName);
1215
+ deps.set(modelName, /* @__PURE__ */ new Set());
1216
+ }
1217
+ for (const [tableName, table] of Object.entries(tables)) {
1218
+ const modelName = tableToModel.get(tableName);
1219
+ for (const fk of table.foreignKeys) {
1220
+ const refModelName = tableToModel.get(fk.referencedTable);
1221
+ if (refModelName && refModelName !== modelName) deps.get(modelName).add(refModelName);
1222
+ }
1223
+ }
1224
+ const result = [];
1225
+ const visited = /* @__PURE__ */ new Set();
1226
+ const visiting = /* @__PURE__ */ new Set();
1227
+ const sortedNames = [...deps.keys()].sort();
1228
+ function visit(name) {
1229
+ if (visited.has(name)) return;
1230
+ if (visiting.has(name)) return;
1231
+ visiting.add(name);
1232
+ const sortedDeps = [...deps.get(name)].sort();
1233
+ for (const dep of sortedDeps) visit(dep);
1234
+ visiting.delete(name);
1235
+ visited.add(name);
1236
+ result.push(modelByName.get(name));
1237
+ }
1238
+ for (const name of sortedNames) visit(name);
1239
+ return result;
1240
+ }
1241
+ //#endregion
1242
+ //#region src/exports/control.ts
423
1243
  function postgresRenderDefault(def, column) {
424
1244
  if (def.kind === "function") return def.expression;
425
1245
  return renderDefaultLiteral(def.value, column);
@@ -428,6 +1248,15 @@ const postgresTargetDescriptor = {
428
1248
  ...postgresTargetDescriptorMeta,
429
1249
  contractSerializer: new PostgresContractSerializer(),
430
1250
  schemaVerifier: new PostgresSchemaVerifier(),
1251
+ inferPslContract(schema, describedContracts) {
1252
+ PostgresDatabaseSchemaNode.assert(schema);
1253
+ return inferPostgresPslContract(schema, describedContracts);
1254
+ },
1255
+ diffSchema(input) {
1256
+ return diffPostgresSchema(input);
1257
+ },
1258
+ classifySubjectGranularity: postgresDiffSubjectGranularity,
1259
+ classifyEntityKind: postgresDiffSubjectEntityKind,
431
1260
  migrations: {
432
1261
  createPlanner(adapter) {
433
1262
  return createPostgresMigrationPlanner(adapter);
@@ -436,9 +1265,10 @@ const postgresTargetDescriptor = {
436
1265
  return createPostgresMigrationRunner(family);
437
1266
  },
438
1267
  contractToSchema(contract, frameworkComponents) {
439
- return contractToSchemaIR(contract, {
1268
+ const expander = buildNativeTypeExpander(frameworkComponents);
1269
+ return contractToPostgresDatabaseSchemaNode(blindCast(contract), {
440
1270
  annotationNamespace: "pg",
441
- ...ifDefined("expandNativeType", buildNativeTypeExpander(frameworkComponents)),
1271
+ ...ifDefined("expandNativeType", expander),
442
1272
  renderDefault: postgresRenderDefault
443
1273
  });
444
1274
  }