@prisma-next/target-postgres 0.14.0-dev.6 → 0.14.0-dev.60

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 (253) hide show
  1. package/dist/authoring-WkqG_MkU.mjs +419 -0
  2. package/dist/authoring-WkqG_MkU.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-CkVQrZ4G.mjs +913 -0
  15. package/dist/codecs-CkVQrZ4G.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 +4 -4
  24. package/dist/control-policy-Co_13Hxa.mjs +1128 -0
  25. package/dist/control-policy-Co_13Hxa.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 +900 -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-B-krEXY1.mjs} +77 -6
  35. package/dist/ddl-B-krEXY1.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-BOcKPaLE.mjs +22 -0
  43. package/dist/descriptor-meta-BOcKPaLE.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-BOsDnH64.mjs +266 -0
  47. package/dist/diff-database-schema-BOsDnH64.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/errors-DO-w0EUS.mjs +35 -0
  52. package/dist/errors-DO-w0EUS.mjs.map +1 -0
  53. package/dist/errors.d.mts +11 -9
  54. package/dist/errors.d.mts.map +1 -1
  55. package/dist/errors.mjs +1 -1
  56. package/dist/issue-planner.d.mts +35 -11
  57. package/dist/issue-planner.d.mts.map +1 -1
  58. package/dist/issue-planner.mjs +2 -2
  59. package/dist/migration.d.mts +5 -5
  60. package/dist/migration.d.mts.map +1 -1
  61. package/dist/migration.mjs +4 -4
  62. package/dist/namespace-ids-xtp_ZY86.mjs +7 -0
  63. package/dist/namespace-ids-xtp_ZY86.mjs.map +1 -0
  64. package/dist/native-type-normalizer.mjs +37 -1
  65. package/dist/native-type-normalizer.mjs.map +1 -0
  66. package/dist/nodes-B815pj_X.mjs +162 -0
  67. package/dist/nodes-B815pj_X.mjs.map +1 -0
  68. package/dist/nodes-BtQyZha6.d.mts +146 -0
  69. package/dist/nodes-BtQyZha6.d.mts.map +1 -0
  70. package/dist/{op-factory-call-DmQEc3XV.d.mts → op-factory-call-D6_7-7Vc.d.mts} +68 -15
  71. package/dist/op-factory-call-D6_7-7Vc.d.mts.map +1 -0
  72. package/dist/{op-factory-call-D_p5vxwt.mjs → op-factory-call-DxNNKUeZ.mjs} +300 -31
  73. package/dist/op-factory-call-DxNNKUeZ.mjs.map +1 -0
  74. package/dist/op-factory-call.d.mts +2 -2
  75. package/dist/op-factory-call.mjs +2 -2
  76. package/dist/pack.d.mts +144 -3
  77. package/dist/pack.d.mts.map +1 -1
  78. package/dist/pack.mjs +1 -1
  79. package/dist/planner-CNrc1Odu.mjs +422 -0
  80. package/dist/planner-CNrc1Odu.mjs.map +1 -0
  81. package/dist/{planner-ddl-builders-B2wOwLqI.mjs → planner-ddl-builders-B8Nn6nHN.mjs} +12 -27
  82. package/dist/planner-ddl-builders-B8Nn6nHN.mjs.map +1 -0
  83. package/dist/planner-ddl-builders.d.mts +4 -6
  84. package/dist/planner-ddl-builders.d.mts.map +1 -1
  85. package/dist/planner-ddl-builders.mjs +2 -2
  86. package/dist/planner-identity-values-CJPha2Sz.mjs.map +1 -1
  87. package/dist/planner-identity-values.d.mts +8 -2
  88. package/dist/planner-identity-values.d.mts.map +1 -1
  89. package/dist/planner-identity-values.mjs +2 -2
  90. package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs → planner-produced-postgres-migration-NI-oGKcw.mjs} +3 -3
  91. package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs.map → planner-produced-postgres-migration-NI-oGKcw.mjs.map} +1 -1
  92. package/dist/{planner-produced-postgres-migration-QqHa2C2l.d.mts → planner-produced-postgres-migration-a-tjfKsA.d.mts} +4 -4
  93. package/dist/{planner-produced-postgres-migration-QqHa2C2l.d.mts.map → planner-produced-postgres-migration-a-tjfKsA.d.mts.map} +1 -1
  94. package/dist/planner-produced-postgres-migration.d.mts +1 -1
  95. package/dist/planner-produced-postgres-migration.mjs +1 -1
  96. package/dist/{planner-sql-checks-jqUUGyQR.mjs → planner-sql-checks-AXoxB1Jl.mjs} +2 -2
  97. package/dist/{planner-sql-checks-jqUUGyQR.mjs.map → planner-sql-checks-AXoxB1Jl.mjs.map} +1 -1
  98. package/dist/planner-sql-checks.d.mts +2 -2
  99. package/dist/planner-sql-checks.d.mts.map +1 -1
  100. package/dist/planner-sql-checks.mjs +1 -1
  101. package/dist/{planner-target-details-CIY6tLeo.d.mts → planner-target-details-HkP4RrRO.d.mts} +2 -2
  102. package/dist/planner-target-details-HkP4RrRO.d.mts.map +1 -0
  103. package/dist/planner-target-details.d.mts +1 -1
  104. package/dist/planner.d.mts +72 -17
  105. package/dist/planner.d.mts.map +1 -1
  106. package/dist/planner.mjs +3 -2
  107. package/dist/postgres-contract-view-C9j5cqP0.d.mts +34 -0
  108. package/dist/postgres-contract-view-C9j5cqP0.d.mts.map +1 -0
  109. package/dist/{postgres-contract-serializer-k3TAcPMY.mjs → postgres-contract-view-Dg-N7KA7.mjs} +45 -41
  110. package/dist/postgres-contract-view-Dg-N7KA7.mjs.map +1 -0
  111. package/dist/postgres-database-schema-node-CfdTY-Qs.d.mts +218 -0
  112. package/dist/postgres-database-schema-node-CfdTY-Qs.d.mts.map +1 -0
  113. package/dist/{postgres-migration-Y4YBJqkS.d.mts → postgres-migration-Bzzi0Asr.d.mts} +28 -9
  114. package/dist/postgres-migration-Bzzi0Asr.d.mts.map +1 -0
  115. package/dist/{postgres-migration-B5jKrXv3.mjs → postgres-migration-ChyRsWvE.mjs} +53 -45
  116. package/dist/postgres-migration-ChyRsWvE.mjs.map +1 -0
  117. package/dist/postgres-native-enum-xdiqmBf_.mjs +41 -0
  118. package/dist/postgres-native-enum-xdiqmBf_.mjs.map +1 -0
  119. package/dist/postgres-rls-policy--CSddvMR.d.mts +52 -0
  120. package/dist/postgres-rls-policy--CSddvMR.d.mts.map +1 -0
  121. package/dist/postgres-role-schema-node-BiSTCTNg.mjs +195 -0
  122. package/dist/postgres-role-schema-node-BiSTCTNg.mjs.map +1 -0
  123. package/dist/postgres-schema-CU4gF6QZ.d.mts +257 -0
  124. package/dist/postgres-schema-CU4gF6QZ.d.mts.map +1 -0
  125. package/dist/{postgres-schema-COGZ1ark.mjs → postgres-schema-DTLA_aRi.mjs} +171 -10
  126. package/dist/postgres-schema-DTLA_aRi.mjs.map +1 -0
  127. package/dist/postgres-table-schema-node-9FCtCUz2.mjs +153 -0
  128. package/dist/postgres-table-schema-node-9FCtCUz2.mjs.map +1 -0
  129. package/dist/render-ops.d.mts +1 -1
  130. package/dist/{render-typescript-KMgosran.mjs → render-typescript-7yqILcwr.mjs} +45 -16
  131. package/dist/render-typescript-7yqILcwr.mjs.map +1 -0
  132. package/dist/render-typescript.mjs +1 -1
  133. package/dist/resolve-ddl-schema-Ca88Tg6W.mjs +22 -0
  134. package/dist/resolve-ddl-schema-Ca88Tg6W.mjs.map +1 -0
  135. package/dist/rls-canonicalize.d.mts +20 -0
  136. package/dist/rls-canonicalize.d.mts.map +1 -0
  137. package/dist/rls-canonicalize.mjs +2 -0
  138. package/dist/runtime.d.mts +6 -8
  139. package/dist/runtime.d.mts.map +1 -1
  140. package/dist/runtime.mjs +3 -3
  141. package/dist/runtime.mjs.map +1 -1
  142. package/dist/schema-ir-annotations.d.mts +15 -0
  143. package/dist/schema-ir-annotations.d.mts.map +1 -0
  144. package/dist/schema-ir-annotations.mjs +2 -0
  145. package/dist/types.d.mts +4 -140
  146. package/dist/types.mjs +5 -2
  147. package/dist/wire-name-rHHtr1h0.mjs +75 -0
  148. package/dist/wire-name-rHHtr1h0.mjs.map +1 -0
  149. package/package.json +23 -17
  150. package/src/contract-free/checks.ts +73 -0
  151. package/src/contract-free/ddl.ts +71 -1
  152. package/src/core/authoring.ts +356 -2
  153. package/src/core/codec-ids.ts +1 -0
  154. package/src/core/codec-type-map.ts +2 -0
  155. package/src/core/codecs.ts +180 -1
  156. package/src/core/ddl/nodes.ts +141 -2
  157. package/src/core/default-normalizer.ts +122 -2
  158. package/src/core/descriptor-meta.ts +10 -1
  159. package/src/core/entity-kinds.ts +41 -0
  160. package/src/core/errors.ts +14 -12
  161. package/src/core/migrations/bound-schema.ts +10 -0
  162. package/src/core/migrations/column-ddl-rendering.ts +117 -0
  163. package/src/core/migrations/contract-to-postgres-database-schema-node.ts +160 -0
  164. package/src/core/migrations/control-policy.ts +99 -46
  165. package/src/core/migrations/diff-database-schema.ts +217 -0
  166. package/src/core/migrations/issue-planner.ts +692 -652
  167. package/src/core/migrations/op-factory-call.ts +189 -21
  168. package/src/core/migrations/operations/columns.ts +24 -12
  169. package/src/core/migrations/operations/constraints.ts +1 -1
  170. package/src/core/migrations/operations/data-transform.ts +6 -0
  171. package/src/core/migrations/operations/dependencies.ts +2 -1
  172. package/src/core/migrations/operations/rls.ts +187 -0
  173. package/src/core/migrations/operations/shared.ts +0 -30
  174. package/src/core/migrations/planner-ddl-builders.ts +20 -58
  175. package/src/core/migrations/planner-identity-values.ts +1 -1
  176. package/src/core/migrations/planner-recipes.ts +31 -13
  177. package/src/core/migrations/planner-sql-checks.ts +1 -1
  178. package/src/core/migrations/planner-strategies.ts +248 -216
  179. package/src/core/migrations/planner-target-details.ts +3 -1
  180. package/src/core/migrations/planner.ts +381 -59
  181. package/src/core/migrations/postgres-migration.ts +70 -86
  182. package/src/core/migrations/render-typescript.ts +42 -15
  183. package/src/core/migrations/resolve-ddl-schema.ts +26 -0
  184. package/src/core/migrations/runner.ts +10 -16
  185. package/src/core/migrations/verify-postgres-namespaces.ts +47 -31
  186. package/src/core/namespace-ids.ts +3 -0
  187. package/src/core/postgres-contract-serializer.ts +46 -71
  188. package/src/core/postgres-contract-view.ts +48 -0
  189. package/src/core/postgres-native-enum.ts +51 -0
  190. package/src/core/postgres-rls-enablement.ts +34 -0
  191. package/src/core/postgres-rls-policy.ts +64 -0
  192. package/src/core/postgres-role.ts +37 -0
  193. package/src/core/postgres-schema-verifier.ts +10 -7
  194. package/src/core/postgres-schema.ts +64 -15
  195. package/src/core/postgres-validators.ts +33 -0
  196. package/src/core/psl-infer/infer-psl-contract.ts +1325 -0
  197. package/src/core/psl-infer/postgres-default-mapping.ts +16 -0
  198. package/src/core/psl-infer/postgres-type-map.ts +128 -0
  199. package/src/core/rls/canonicalize.ts +48 -0
  200. package/src/core/rls/wire-name.ts +33 -0
  201. package/src/core/schema-ir/postgres-database-schema-node.ts +60 -0
  202. package/src/core/schema-ir/postgres-namespace-schema-node.ts +79 -0
  203. package/src/core/schema-ir/postgres-policy-schema-node.ts +90 -0
  204. package/src/core/schema-ir/postgres-role-schema-node.ts +63 -0
  205. package/src/core/schema-ir/postgres-table-schema-node.ts +140 -0
  206. package/src/core/schema-ir/schema-node-kinds.ts +106 -0
  207. package/src/exports/codecs.ts +3 -0
  208. package/src/exports/contract-free.ts +11 -1
  209. package/src/exports/control.ts +27 -33
  210. package/src/exports/ddl.ts +6 -0
  211. package/src/exports/diff-database-schema.ts +7 -0
  212. package/src/exports/issue-planner.ts +1 -1
  213. package/src/exports/migration.ts +1 -0
  214. package/src/exports/op-factory-call.ts +1 -0
  215. package/src/exports/planner-ddl-builders.ts +0 -2
  216. package/src/exports/planner-identity-values.ts +4 -1
  217. package/src/exports/planner.ts +1 -0
  218. package/src/exports/rls-canonicalize.ts +7 -0
  219. package/src/exports/runtime.ts +1 -0
  220. package/src/exports/schema-ir-annotations.ts +1 -0
  221. package/src/exports/types.ts +34 -0
  222. package/dist/codec-ids-BvytN2P8.mjs.map +0 -1
  223. package/dist/codec-ids-CnXu9Qy3.d.mts.map +0 -1
  224. package/dist/codec-types-DHCkwPKE.d.mts.map +0 -1
  225. package/dist/codecs--0A5_4Bq.d.mts.map +0 -1
  226. package/dist/ddl-QDyOSeLc.mjs.map +0 -1
  227. package/dist/default-normalizer-DyyCHQWs.mjs +0 -131
  228. package/dist/default-normalizer-DyyCHQWs.mjs.map +0 -1
  229. package/dist/descriptor-meta-CpGygXpI.mjs +0 -140
  230. package/dist/descriptor-meta-CpGygXpI.mjs.map +0 -1
  231. package/dist/errors-CUk87ByX.mjs +0 -33
  232. package/dist/errors-CUk87ByX.mjs.map +0 -1
  233. package/dist/issue-planner-DL6g3CmE.mjs +0 -824
  234. package/dist/issue-planner-DL6g3CmE.mjs.map +0 -1
  235. package/dist/native-type-normalizer-Bc9XJzWC.mjs +0 -38
  236. package/dist/native-type-normalizer-Bc9XJzWC.mjs.map +0 -1
  237. package/dist/nodes-Bbhs2rwj.mjs +0 -76
  238. package/dist/nodes-Bbhs2rwj.mjs.map +0 -1
  239. package/dist/nodes-pLeLgdis.d.mts +0 -67
  240. package/dist/nodes-pLeLgdis.d.mts.map +0 -1
  241. package/dist/op-factory-call-D_p5vxwt.mjs.map +0 -1
  242. package/dist/op-factory-call-DmQEc3XV.d.mts.map +0 -1
  243. package/dist/planner-Bs_baQax.mjs +0 -324
  244. package/dist/planner-Bs_baQax.mjs.map +0 -1
  245. package/dist/planner-ddl-builders-B2wOwLqI.mjs.map +0 -1
  246. package/dist/planner-target-details-CIY6tLeo.d.mts.map +0 -1
  247. package/dist/postgres-contract-serializer-k3TAcPMY.mjs.map +0 -1
  248. package/dist/postgres-migration-B5jKrXv3.mjs.map +0 -1
  249. package/dist/postgres-migration-Y4YBJqkS.d.mts.map +0 -1
  250. package/dist/postgres-schema-COGZ1ark.mjs.map +0 -1
  251. package/dist/render-typescript-KMgosran.mjs.map +0 -1
  252. package/dist/types.d.mts.map +0 -1
  253. package/src/core/postgres-enum-type-schema.ts +0 -17
package/dist/control.mjs CHANGED
@@ -1,18 +1,22 @@
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 PostgresNativeEnum } from "./postgres-native-enum-xdiqmBf_.mjs";
2
+ import { t as postgresTargetDescriptorMeta } from "./descriptor-meta-BOcKPaLE.mjs";
3
+ import { i as postgresDiffSubjectGranularity, r as postgresDiffSubjectEntityKind } from "./postgres-table-schema-node-9FCtCUz2.mjs";
4
+ import { i as PostgresDatabaseSchemaNode } from "./postgres-role-schema-node-BiSTCTNg.mjs";
5
+ import { n as diffPostgresSchema, r as contractToPostgresDatabaseSchemaNode } from "./diff-database-schema-BOsDnH64.mjs";
6
+ import { r as renderDefaultLiteral } from "./planner-ddl-builders-B8Nn6nHN.mjs";
7
+ import { n as PostgresContractSerializer } from "./postgres-contract-view-Dg-N7KA7.mjs";
8
+ import { t as createPostgresMigrationPlanner } from "./planner-CNrc1Odu.mjs";
9
+ import { UNBOUND_NAMESPACE_ID, coordinateKey, elementCoordinates, isPlainRecord } from "@prisma-next/framework-components/ir";
7
10
  import { blindCast } from "@prisma-next/utils/casts";
8
- import { contractToSchemaIR, extractCodecControlHooks, runnerFailure, runnerSuccess } from "@prisma-next/family-sql/control";
11
+ import { buildNativeTypeExpander, runnerFailure, runnerSuccess } from "@prisma-next/family-sql/control";
9
12
  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";
13
+ import { SqlSchemaIR, SqlTableIR } from "@prisma-next/sql-schema-ir/types";
13
14
  import { APP_SPACE_ID } from "@prisma-next/framework-components/control";
14
- import { SqlQueryError } from "@prisma-next/sql-errors";
15
+ import { notOk, ok, okVoid } from "@prisma-next/utils/result";
15
16
  import { SqlSchemaVerifierBase } from "@prisma-next/family-sql/ir";
17
+ import { SqlQueryError } from "@prisma-next/sql-errors";
18
+ import { buildChildRelationField, deriveRelationFieldName, inferRelations, mapDefault, parseRawDefault, toEnumMemberName, toEnumName, toFieldName, toModelName, toNamedTypeName } from "@prisma-next/family-sql/psl-infer";
19
+ import { UNSPECIFIED_PSL_NAMESPACE_ID, makePslNamespace, makePslNamespaceEntries } from "@prisma-next/framework-components/psl-ast";
16
20
  //#region src/core/migrations/runner.ts
17
21
  const LOCK_DOMAIN = "prisma_next.contract.marker";
18
22
  /**
@@ -74,19 +78,15 @@ var PostgresMigrationRunner = class {
74
78
  applyValue = applyResult.value;
75
79
  }
76
80
  if (space === APP_SPACE_ID) {
77
- const schemaIR = await this.family.introspect({
81
+ const schemaNode = await this.family.introspect({
78
82
  driver,
79
83
  contract: options.destinationContract
80
84
  });
81
- const schemaVerifyResult = verifySqlSchema({
85
+ const schemaVerifyResult = this.family.verifySchema({
82
86
  contract: options.destinationContract,
83
- schema: schemaIR,
87
+ schema: schemaNode,
84
88
  strict: options.strictVerification ?? true,
85
- context: options.context ?? {},
86
- typeMetadataRegistry: this.family.typeMetadataRegistry,
87
- frameworkComponents: options.frameworkComponents,
88
- normalizeDefault: parsePostgresDefault,
89
- normalizeNativeType: normalizeSchemaNativeType
89
+ frameworkComponents: options.frameworkComponents
90
90
  });
91
91
  if (!schemaVerifyResult.ok) return runnerFailure("SCHEMA_VERIFY_FAILED", schemaVerifyResult.summary, {
92
92
  why: "The resulting database schema does not satisfy the destination contract.",
@@ -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,873 @@ 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
420
+ };
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 = 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 enumOwners = describedNativeEnumOwnersByTypeName(describedContracts ?? []);
757
+ const enumDefinitions = /* @__PURE__ */ new Map();
758
+ const packOwnedEnumTypesByNamespace = /* @__PURE__ */ new Map();
759
+ const enumNamespaceNames = /* @__PURE__ */ new Set();
760
+ for (const namespace of namespaces) {
761
+ const definitionsForNamespace = new Set(namespace.nativeEnums.map((e) => e.typeName));
762
+ for (const typeName of namespace.nativeEnumTypeNames) if (!definitionsForNamespace.has(typeName)) throw new Error(`contract infer: introspection reported native enum type "${typeName}" in schema "${namespace.schemaName}" without member values — the introspected tree's \`nativeEnumTypeNames\` and \`nativeEnums\` are out of sync (internal invariant).`);
763
+ for (const { typeName, values } of namespace.nativeEnums) {
764
+ const owner = enumOwners.get(coordinateKey({
765
+ namespaceId: namespace.schemaName,
766
+ entityKind: "native_enum",
767
+ entityName: typeName
768
+ }));
769
+ if (owner !== void 0) {
770
+ const owned = packOwnedEnumTypesByNamespace.get(namespace.schemaName) ?? /* @__PURE__ */ new Map();
771
+ owned.set(typeName, owner.spaceId);
772
+ owned.set(`${namespace.schemaName}.${typeName}`, owner.spaceId);
773
+ packOwnedEnumTypesByNamespace.set(namespace.schemaName, owned);
774
+ continue;
775
+ }
776
+ enumDefinitions.set(typeName, values);
777
+ enumNamespaceNames.add(namespace.schemaName);
778
+ }
779
+ }
780
+ const tables = {};
781
+ const tableNamespaceNames = /* @__PURE__ */ new Set();
782
+ for (const namespace of namespaces) {
783
+ const ownedEnumTypes = packOwnedEnumTypesByNamespace.get(namespace.schemaName);
784
+ for (const [tableName, table] of Object.entries(namespace.tables)) {
785
+ if (owners.has(coordinateKey({
786
+ namespaceId: namespace.schemaName,
787
+ entityKind: "table",
788
+ entityName: tableName
789
+ }))) continue;
790
+ 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).`);
791
+ if (ownedEnumTypes !== void 0) for (const column of Object.values(table.columns)) {
792
+ const owningSpaceId = ownedEnumTypes.get(column.nativeType);
793
+ 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.`);
794
+ }
795
+ tables[tableName] = new SqlTableIR(table);
796
+ tableNamespaceNames.add(namespace.schemaName);
797
+ }
798
+ }
799
+ let wrapNamespaceName;
800
+ if (enumDefinitions.size > 0) {
801
+ const contentNamespaces = new Set([...enumNamespaceNames, ...tableNamespaceNames]);
802
+ 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(", ")}.`);
803
+ wrapNamespaceName = [...contentNamespaces][0];
804
+ }
805
+ const { tables: resolvedTables, extraRelationsByTable, crossSpaceFieldNamesByTable } = resolveForeignKeys(tables, owners);
806
+ const schemaIR = new SqlSchemaIR({ tables: resolvedTables });
807
+ const enumTypeNames = new Set(enumDefinitions.keys());
808
+ if (wrapNamespaceName !== void 0) for (const typeName of enumDefinitions.keys()) enumTypeNames.add(`${wrapNamespaceName}.${typeName}`);
809
+ const enumInfo = {
810
+ typeNames: enumTypeNames,
811
+ definitions: enumDefinitions
812
+ };
813
+ return buildPslDocumentAst(schemaIR, {
814
+ typeMap: createPostgresTypeMap(enumInfo.typeNames),
815
+ defaultMapping: createPostgresDefaultMapping(),
816
+ parseRawDefault,
817
+ ...enumDefinitions.size > 0 ? { enumInfo } : {}
818
+ }, {
819
+ extraRelationsByTable,
820
+ crossSpaceFieldNamesByTable
821
+ }, wrapNamespaceName);
822
+ }
823
+ /**
824
+ * Native-enum ownership index for pack subtraction, keyed by TYPE NAME
825
+ * coordinate. A pack contract keys `entries.native_enum` by HANDLE name
826
+ * (`AalLevel`) while introspection sees the Postgres type name (`aal_level`);
827
+ * the entity's `typeName` field carries the mapping, so this walk indexes by
828
+ * it rather than reusing {@link describedContractOwners}' entries-key
829
+ * coordinates.
830
+ *
831
+ * Reads `entries.native_enum` directly: the kind map is carried
832
+ * non-enumerable on `PostgresSchema.entries`, so the generic
833
+ * `elementCoordinates` walk never yields it. Serialized pack contracts do
834
+ * not carry `native_enum` entries at all (`PostgresContractSerializer`
835
+ * strips them; only the derived `valueSet` survives), so this subtraction
836
+ * currently matches in-memory described contracts only.
837
+ */
838
+ function describedNativeEnumOwnersByTypeName(describedContracts) {
839
+ const owners = /* @__PURE__ */ new Map();
840
+ for (const entry of describedContracts) for (const [namespaceId, ns] of Object.entries(entry.contract.storage.namespaces)) {
841
+ const kindMap = ns.entries["native_enum"];
842
+ if (!isPlainRecord(kindMap)) continue;
843
+ for (const entity of Object.values(kindMap)) {
844
+ if (!PostgresNativeEnum.is(entity)) continue;
845
+ owners.set(coordinateKey({
846
+ namespaceId,
847
+ entityKind: "native_enum",
848
+ entityName: entity.typeName
849
+ }), entry);
850
+ }
851
+ }
852
+ return owners;
853
+ }
854
+ function buildPslDocumentAst(schemaIR, options, foreignKeyExtras, namespaceName) {
855
+ const { typeMap, defaultMapping, parseRawDefault: rawDefaultParser } = options;
856
+ const { extraRelationsByTable, crossSpaceFieldNamesByTable } = foreignKeyExtras;
857
+ const modelNames = buildTopLevelNameMap(Object.keys(schemaIR.tables), toModelName, "model", "table");
858
+ const modelNameMap = new Map([...modelNames].map(([tableName, result]) => [tableName, result.name]));
859
+ const { enumNameMap: bareEnumNameMap, enumBlocks } = buildNativeEnumBlocks(options.enumInfo?.definitions ?? /* @__PURE__ */ new Map(), modelNames);
860
+ const enumNameMap = new Map(bareEnumNameMap);
861
+ if (namespaceName !== void 0) for (const [typeName, pslName] of bareEnumNameMap) enumNameMap.set(`${namespaceName}.${typeName}`, pslName);
862
+ const reservedNamedTypeNames = createReservedNamedTypeNames(modelNames, enumNameMap);
863
+ const fieldNamesByTable = new Map([...crossSpaceFieldNamesByTable, ...buildFieldNamesByTable(schemaIR.tables)]);
864
+ const { relationsByTable } = inferRelations(schemaIR.tables, modelNameMap);
865
+ const namedTypes = seedNamedTypeRegistry(schemaIR, typeMap, enumNameMap, reservedNamedTypeNames);
866
+ const models = [];
867
+ 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) ?? []]));
868
+ const sortedModels = topologicalSort(models, schemaIR.tables, modelNameMap);
869
+ const namedTypeEntries = [...namedTypes.entriesByKey.values()].sort((a, b) => a.name.localeCompare(b.name));
870
+ const types = namedTypeEntries.length > 0 ? {
871
+ kind: "types",
872
+ declarations: namedTypeEntries.map(buildNamedTypeDeclaration),
873
+ span: SYNTHETIC_SPAN
874
+ } : void 0;
875
+ return {
876
+ kind: "document",
877
+ sourceId: "<sql-schema-ir>",
878
+ namespaces: [makePslNamespace({
879
+ kind: "namespace",
880
+ name: namespaceName ?? UNSPECIFIED_PSL_NAMESPACE_ID,
881
+ entries: makePslNamespaceEntries(sortedModels, [], enumBlocks),
882
+ span: SYNTHETIC_SPAN
883
+ })],
884
+ ...types ? { types } : {},
885
+ span: SYNTHETIC_SPAN
886
+ };
887
+ }
888
+ /**
889
+ * Builds one `native_enum` extension-block AST node per introspected enum
890
+ * definition. Block names go through the shared top-level transform
891
+ * (`toEnumName`, intra-enum collisions throw like model collisions) and are
892
+ * then reserved against the model names — an enum whose PSL name a model
893
+ * already claims gets a numeric suffix, with `@@map` carrying the real type
894
+ * name. Members print as explicit `member = "value"` pairs: the member name
895
+ * is the sanitized value (deduplicated within the block), the JSON-encoded
896
+ * value carries the truth verbatim.
897
+ */
898
+ function buildNativeEnumBlocks(definitions, modelNames) {
899
+ const enumNames = buildTopLevelNameMap([...definitions.keys()].sort(), toEnumName, "enum", "enum type");
900
+ const usedTopLevelNames = new Set(PSL_SCALAR_TYPE_NAMES);
901
+ for (const result of modelNames.values()) usedTopLevelNames.add(result.name);
902
+ const enumNameMap = /* @__PURE__ */ new Map();
903
+ const enumBlocks = [];
904
+ for (const [typeName, result] of enumNames) {
905
+ const name = createUniqueFieldName(result.name, usedTopLevelNames);
906
+ usedTopLevelNames.add(name);
907
+ enumNameMap.set(typeName, name);
908
+ enumBlocks.push(buildNativeEnumBlock(name, typeName, definitions.get(typeName) ?? []));
909
+ }
910
+ return {
911
+ enumNameMap,
912
+ enumBlocks
913
+ };
914
+ }
915
+ function buildNativeEnumBlock(name, typeName, values) {
916
+ const usedMemberNames = /* @__PURE__ */ new Set();
917
+ const parameters = {};
918
+ for (const value of values) {
919
+ const memberName = createUniqueFieldName(toEnumMemberName(value), usedMemberNames);
920
+ usedMemberNames.add(memberName);
921
+ parameters[memberName] = {
922
+ kind: "value",
923
+ raw: JSON.stringify(value),
924
+ span: SYNTHETIC_SPAN
925
+ };
926
+ }
927
+ return {
928
+ kind: "native_enum",
929
+ name,
930
+ parameters,
931
+ blockAttributes: name === typeName ? [] : [{
932
+ name: "map",
933
+ args: [{
934
+ kind: "positional",
935
+ value: `"${escapePslString(typeName)}"`,
936
+ span: SYNTHETIC_SPAN
937
+ }],
938
+ span: SYNTHETIC_SPAN
939
+ }],
940
+ span: SYNTHETIC_SPAN
941
+ };
942
+ }
943
+ function buildModel(table, typeMap, enumNameMap, fieldNamesByTable, namedTypes, defaultMapping, rawDefaultParser, relationFields) {
944
+ const { name: modelName, map: mapName } = toModelName(table.name);
945
+ const fieldNameMap = fieldNamesByTable.get(table.name);
946
+ const pkColumns = new Set(table.primaryKey?.columns ?? []);
947
+ const isSinglePk = pkColumns.size === 1;
948
+ const singlePkConstraintName = isSinglePk ? table.primaryKey?.name : void 0;
949
+ const uniqueColumns = /* @__PURE__ */ new Map();
950
+ for (const unique of table.uniques) if (unique.columns.length === 1) {
951
+ const [columnName = ""] = unique.columns;
952
+ const existingConstraintName = uniqueColumns.get(columnName);
953
+ if (!uniqueColumns.has(columnName) || existingConstraintName === void 0 && unique.name) uniqueColumns.set(columnName, unique.name);
954
+ }
955
+ const fields = [];
956
+ for (const column of Object.values(table.columns)) fields.push(buildScalarField(column, table, typeMap, enumNameMap, fieldNameMap, namedTypes, defaultMapping, rawDefaultParser, pkColumns, isSinglePk, singlePkConstraintName, uniqueColumns));
957
+ const usedFieldNames = new Set(fields.map((field) => field.name));
958
+ for (const rel of relationFields) fields.push(buildRelationField(rel, table.name, fieldNamesByTable, usedFieldNames));
959
+ const modelAttributes = [];
960
+ if (table.primaryKey && table.primaryKey.columns.length > 1) {
961
+ const pkFieldNames = table.primaryKey.columns.map((columnName) => resolveColumnFieldName(fieldNamesByTable, table.name, columnName));
962
+ modelAttributes.push(buildModelConstraintAttribute("id", pkFieldNames, table.primaryKey.name));
963
+ }
964
+ for (const unique of table.uniques) if (unique.columns.length > 1) {
965
+ const uniqueFieldNames = unique.columns.map((columnName) => resolveColumnFieldName(fieldNamesByTable, table.name, columnName));
966
+ modelAttributes.push(buildModelConstraintAttribute("unique", uniqueFieldNames, unique.name));
967
+ }
968
+ for (const index of table.indexes) if (!index.unique) {
969
+ const indexFieldNames = index.columns.map((columnName) => resolveColumnFieldName(fieldNamesByTable, table.name, columnName));
970
+ modelAttributes.push(buildModelConstraintAttribute("index", indexFieldNames, index.name));
971
+ }
972
+ if (mapName) modelAttributes.push(buildMapAttribute("model", mapName));
973
+ const comment = table.primaryKey ? void 0 : "// WARNING: This table has no primary key in the database";
974
+ return {
975
+ kind: "model",
976
+ name: modelName,
977
+ fields,
978
+ attributes: modelAttributes,
979
+ span: SYNTHETIC_SPAN,
980
+ ...comment !== void 0 ? { comment } : {}
981
+ };
982
+ }
983
+ function buildScalarField(column, table, typeMap, enumNameMap, fieldNameMap, namedTypes, defaultMapping, rawDefaultParser, pkColumns, isSinglePk, singlePkConstraintName, uniqueColumns) {
984
+ const resolvedField = fieldNameMap?.get(column.name);
985
+ const fieldName = resolvedField?.fieldName ?? toFieldName(column.name).name;
986
+ const fieldMap = resolvedField?.fieldMap;
987
+ const resolution = typeMap.resolve(column.nativeType, table.annotations);
988
+ if ("unsupported" in resolution) {
989
+ const attrs = [];
990
+ if (fieldMap !== void 0) attrs.push(buildMapAttribute("field", fieldMap));
991
+ return {
992
+ kind: "field",
993
+ name: fieldName,
994
+ typeName: `Unsupported("${escapePslString(resolution.nativeType)}")`,
995
+ optional: column.nullable,
996
+ list: column.many === true,
997
+ attributes: attrs,
998
+ span: SYNTHETIC_SPAN
999
+ };
1000
+ }
1001
+ let typeName = resolution.pslType;
1002
+ let typeConstructor;
1003
+ const enumPslName = enumNameMap.get(column.nativeType);
1004
+ if (enumPslName) {
1005
+ typeName = enumPslName;
1006
+ typeConstructor = {
1007
+ kind: "typeConstructor",
1008
+ path: ["pg", "enum"],
1009
+ args: [positionalArg(enumPslName)],
1010
+ span: SYNTHETIC_SPAN
1011
+ };
1012
+ }
1013
+ if (resolution.nativeTypeAttribute && !enumPslName) typeName = resolveNamedTypeName(namedTypes, resolution);
1014
+ const attributes = [];
1015
+ const isId = isSinglePk && pkColumns.has(column.name);
1016
+ if (isId) attributes.push(buildSimpleConstraintFieldAttribute("id", singlePkConstraintName));
1017
+ if (column.default !== void 0) {
1018
+ const parsed = parseColumnDefault(column.default, column.nativeType, rawDefaultParser);
1019
+ if (parsed) {
1020
+ const result = mapDefault(parsed, defaultMapping);
1021
+ if ("attribute" in result) attributes.push(parseDefaultAttributeString(result.attribute));
1022
+ }
1023
+ }
1024
+ if (uniqueColumns.has(column.name) && !isId) {
1025
+ const uniqueConstraintName = uniqueColumns.get(column.name);
1026
+ attributes.push(buildSimpleConstraintFieldAttribute("unique", uniqueConstraintName));
1027
+ }
1028
+ if (fieldMap !== void 0) attributes.push(buildMapAttribute("field", fieldMap));
1029
+ return {
1030
+ kind: "field",
1031
+ name: fieldName,
1032
+ typeName,
1033
+ ...ifDefined("typeConstructor", typeConstructor),
1034
+ optional: column.nullable,
1035
+ list: column.many === true,
1036
+ attributes,
1037
+ span: SYNTHETIC_SPAN
1038
+ };
1039
+ }
1040
+ function buildRelationField(rel, hostTableName, fieldNamesByTable, usedFieldNames) {
1041
+ const fieldName = createUniqueFieldName(rel.fieldName, usedFieldNames);
1042
+ usedFieldNames.add(fieldName);
1043
+ const args = [];
1044
+ if (rel.fields && rel.references) {
1045
+ if (rel.relationName) args.push(namedArg("name", `"${escapePslString(rel.relationName)}"`));
1046
+ args.push(namedArg("fields", `[${rel.fields.map((columnName) => resolveColumnFieldName(fieldNamesByTable, hostTableName, columnName)).join(", ")}]`));
1047
+ args.push(namedArg("references", `[${rel.references.map((columnName) => resolveColumnFieldName(fieldNamesByTable, rel.referencedTableName ?? "", columnName)).join(", ")}]`));
1048
+ if (rel.onDelete) args.push(namedArg("onDelete", rel.onDelete));
1049
+ if (rel.onUpdate) args.push(namedArg("onUpdate", rel.onUpdate));
1050
+ if (rel.fkName) args.push(namedArg("map", `"${escapePslString(rel.fkName)}"`));
1051
+ } else if (rel.relationName) args.push(namedArg("name", `"${escapePslString(rel.relationName)}"`));
1052
+ const attrs = args.length > 0 ? [buildAttribute("field", "relation", args)] : [];
1053
+ return {
1054
+ kind: "field",
1055
+ name: fieldName,
1056
+ typeName: rel.typeName,
1057
+ ...ifDefined("typeNamespaceId", rel.typeNamespaceId),
1058
+ ...ifDefined("typeContractSpaceId", rel.typeContractSpaceId),
1059
+ optional: rel.optional,
1060
+ list: rel.list,
1061
+ attributes: attrs,
1062
+ span: SYNTHETIC_SPAN
1063
+ };
1064
+ }
1065
+ function buildModelConstraintAttribute(name, fields, constraintName) {
1066
+ const args = [positionalArg(`[${fields.join(", ")}]`)];
1067
+ if (constraintName !== void 0) args.push(namedArg("map", `"${escapePslString(constraintName)}"`));
1068
+ return buildAttribute("model", name, args);
1069
+ }
1070
+ function buildSimpleConstraintFieldAttribute(name, constraintName) {
1071
+ if (constraintName === void 0) return buildAttribute("field", name, []);
1072
+ return buildAttribute("field", name, [namedArg("map", `"${escapePslString(constraintName)}"`)]);
1073
+ }
1074
+ function parseDefaultAttributeString(attributeText) {
1075
+ return buildAttribute("field", "default", [positionalArg(attributeText.replace(/^@default\(/, "").replace(/\)$/, ""))]);
1076
+ }
1077
+ function buildMapAttribute(target, mapName) {
1078
+ return buildAttribute(target, "map", [positionalArg(`"${escapePslString(mapName)}"`)]);
1079
+ }
1080
+ function buildAttribute(target, name, args) {
1081
+ return {
1082
+ kind: "attribute",
1083
+ target,
1084
+ name,
1085
+ args,
1086
+ span: SYNTHETIC_SPAN
1087
+ };
1088
+ }
1089
+ function positionalArg(value) {
1090
+ return {
1091
+ kind: "positional",
1092
+ value,
1093
+ span: SYNTHETIC_SPAN
421
1094
  };
422
1095
  }
1096
+ function namedArg(name, value) {
1097
+ return {
1098
+ kind: "named",
1099
+ name,
1100
+ value,
1101
+ span: SYNTHETIC_SPAN
1102
+ };
1103
+ }
1104
+ function buildNamedTypeDeclaration(entry) {
1105
+ const attribute = buildAttribute("namedType", entry.nativeTypeAttribute.name, (entry.nativeTypeAttribute.args ?? []).map(positionalArg));
1106
+ return {
1107
+ kind: "namedType",
1108
+ name: entry.name,
1109
+ baseType: entry.baseType,
1110
+ attributes: [attribute],
1111
+ span: SYNTHETIC_SPAN
1112
+ };
1113
+ }
1114
+ function escapePslString(value) {
1115
+ return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
1116
+ }
1117
+ /**
1118
+ * Resolves a `SqlColumnIR.default` value into a normalized {@link ColumnDefault}.
1119
+ *
1120
+ * `SqlSchemaIR` types the column default as `string` (a raw database default
1121
+ * expression). Some legacy fixtures and tests still pass already-normalized
1122
+ * `ColumnDefault` objects in the same slot, so we accept either shape
1123
+ * defensively at runtime.
1124
+ */
1125
+ function parseColumnDefault(value, nativeType, rawDefaultParser) {
1126
+ if (typeof value === "string") return rawDefaultParser ? rawDefaultParser(value, nativeType) : void 0;
1127
+ if (value !== null && typeof value === "object" && "kind" in value) return value;
1128
+ }
1129
+ function buildFieldNamesByTable(tables) {
1130
+ const fieldNamesByTable = /* @__PURE__ */ new Map();
1131
+ for (const table of Object.values(tables)) {
1132
+ const assignmentOrder = [...Object.values(table.columns).map((column, index) => {
1133
+ const { name, map } = toFieldName(column.name);
1134
+ return {
1135
+ columnName: column.name,
1136
+ desiredFieldName: name,
1137
+ fieldMap: map,
1138
+ index
1139
+ };
1140
+ })].sort((left, right) => {
1141
+ const mapComparison = Number(left.fieldMap !== void 0) - Number(right.fieldMap !== void 0);
1142
+ if (mapComparison !== 0) return mapComparison;
1143
+ return left.index - right.index;
1144
+ });
1145
+ const usedFieldNames = /* @__PURE__ */ new Set();
1146
+ const tableFieldNames = /* @__PURE__ */ new Map();
1147
+ for (const column of assignmentOrder) {
1148
+ const fieldName = createUniqueFieldName(column.desiredFieldName, usedFieldNames);
1149
+ usedFieldNames.add(fieldName);
1150
+ tableFieldNames.set(column.columnName, {
1151
+ fieldName,
1152
+ fieldMap: column.fieldMap
1153
+ });
1154
+ }
1155
+ fieldNamesByTable.set(table.name, tableFieldNames);
1156
+ }
1157
+ return fieldNamesByTable;
1158
+ }
1159
+ function resolveColumnFieldName(fieldNamesByTable, tableName, columnName) {
1160
+ return fieldNamesByTable.get(tableName)?.get(columnName)?.fieldName ?? toFieldName(columnName).name;
1161
+ }
1162
+ function createUniqueFieldName(desiredName, usedFieldNames) {
1163
+ if (!usedFieldNames.has(desiredName)) return desiredName;
1164
+ let counter = 2;
1165
+ while (usedFieldNames.has(`${desiredName}${counter}`)) counter++;
1166
+ return `${desiredName}${counter}`;
1167
+ }
1168
+ function buildTopLevelNameMap(sources, normalize, kind, sourceKind) {
1169
+ const results = /* @__PURE__ */ new Map();
1170
+ const normalizedToSources = /* @__PURE__ */ new Map();
1171
+ for (const source of sources) {
1172
+ const normalized = normalize(source);
1173
+ results.set(source, normalized);
1174
+ normalizedToSources.set(normalized.name, [...normalizedToSources.get(normalized.name) ?? [], source]);
1175
+ }
1176
+ const duplicates = [...normalizedToSources.entries()].filter(([, conflictingSources]) => conflictingSources.length > 1);
1177
+ if (duplicates.length > 0) {
1178
+ const details = duplicates.map(([normalizedName, conflictingSources]) => `- ${kind} "${normalizedName}" from ${sourceKind}s ${conflictingSources.map((source) => `"${source}"`).join(", ")}`);
1179
+ throw new Error(`PSL ${kind} name collisions detected:\n${details.join("\n")}`);
1180
+ }
1181
+ return results;
1182
+ }
1183
+ function createReservedNamedTypeNames(modelNames, enumNameMap) {
1184
+ const reservedNames = new Set(PSL_SCALAR_TYPE_NAMES);
1185
+ for (const result of modelNames.values()) reservedNames.add(result.name);
1186
+ for (const enumPslName of enumNameMap.values()) reservedNames.add(enumPslName);
1187
+ return reservedNames;
1188
+ }
1189
+ function seedNamedTypeRegistry(schemaIR, typeMap, enumNameMap, reservedNames) {
1190
+ const seeds = /* @__PURE__ */ new Map();
1191
+ for (const tableName of Object.keys(schemaIR.tables).sort()) {
1192
+ const table = schemaIR.tables[tableName];
1193
+ if (!table) continue;
1194
+ for (const columnName of Object.keys(table.columns).sort()) {
1195
+ const column = table.columns[columnName];
1196
+ if (!column) continue;
1197
+ const resolution = typeMap.resolve(column.nativeType, table.annotations);
1198
+ if ("unsupported" in resolution || enumNameMap.has(column.nativeType) || !resolution.nativeTypeAttribute) continue;
1199
+ const signatureKey = createNamedTypeSignatureKey(resolution);
1200
+ if (!seeds.has(signatureKey)) seeds.set(signatureKey, {
1201
+ baseType: resolution.pslType,
1202
+ desiredName: toNamedTypeName(column.name),
1203
+ nativeTypeAttribute: resolution.nativeTypeAttribute
1204
+ });
1205
+ }
1206
+ }
1207
+ const registry = {
1208
+ entriesByKey: /* @__PURE__ */ new Map(),
1209
+ usedNames: new Set(reservedNames)
1210
+ };
1211
+ const sortedSeeds = [...seeds.entries()].sort((left, right) => {
1212
+ const desiredNameComparison = left[1].desiredName.localeCompare(right[1].desiredName);
1213
+ if (desiredNameComparison !== 0) return desiredNameComparison;
1214
+ return left[0].localeCompare(right[0]);
1215
+ });
1216
+ for (const [signatureKey, seed] of sortedSeeds) {
1217
+ const name = createUniqueFieldName(seed.desiredName, registry.usedNames);
1218
+ registry.entriesByKey.set(signatureKey, {
1219
+ name,
1220
+ baseType: seed.baseType,
1221
+ nativeTypeAttribute: seed.nativeTypeAttribute
1222
+ });
1223
+ registry.usedNames.add(name);
1224
+ }
1225
+ return registry;
1226
+ }
1227
+ function resolveNamedTypeName(registry, resolution) {
1228
+ const key = createNamedTypeSignatureKey(resolution);
1229
+ const existing = registry.entriesByKey.get(key);
1230
+ if (existing) return existing.name;
1231
+ throw new Error(`Named type registry was not seeded for native type "${resolution.nativeType}"`);
1232
+ }
1233
+ function createNamedTypeSignatureKey(resolution) {
1234
+ return JSON.stringify({
1235
+ baseType: resolution.pslType,
1236
+ nativeTypeAttribute: resolution.nativeTypeAttribute ? {
1237
+ name: resolution.nativeTypeAttribute.name,
1238
+ args: resolution.nativeTypeAttribute.args ?? null
1239
+ } : null
1240
+ });
1241
+ }
1242
+ function topologicalSort(models, tables, modelNameMap) {
1243
+ const modelByName = /* @__PURE__ */ new Map();
1244
+ for (const model of models) modelByName.set(model.name, model);
1245
+ const deps = /* @__PURE__ */ new Map();
1246
+ const tableToModel = /* @__PURE__ */ new Map();
1247
+ for (const tableName of Object.keys(tables)) {
1248
+ const modelName = modelNameMap.get(tableName);
1249
+ tableToModel.set(tableName, modelName);
1250
+ deps.set(modelName, /* @__PURE__ */ new Set());
1251
+ }
1252
+ for (const [tableName, table] of Object.entries(tables)) {
1253
+ const modelName = tableToModel.get(tableName);
1254
+ for (const fk of table.foreignKeys) {
1255
+ const refModelName = tableToModel.get(fk.referencedTable);
1256
+ if (refModelName && refModelName !== modelName) deps.get(modelName).add(refModelName);
1257
+ }
1258
+ }
1259
+ const result = [];
1260
+ const visited = /* @__PURE__ */ new Set();
1261
+ const visiting = /* @__PURE__ */ new Set();
1262
+ const sortedNames = [...deps.keys()].sort();
1263
+ function visit(name) {
1264
+ if (visited.has(name)) return;
1265
+ if (visiting.has(name)) return;
1266
+ visiting.add(name);
1267
+ const sortedDeps = [...deps.get(name)].sort();
1268
+ for (const dep of sortedDeps) visit(dep);
1269
+ visiting.delete(name);
1270
+ visited.add(name);
1271
+ result.push(modelByName.get(name));
1272
+ }
1273
+ for (const name of sortedNames) visit(name);
1274
+ return result;
1275
+ }
1276
+ //#endregion
1277
+ //#region src/exports/control.ts
423
1278
  function postgresRenderDefault(def, column) {
424
1279
  if (def.kind === "function") return def.expression;
425
1280
  return renderDefaultLiteral(def.value, column);
@@ -428,6 +1283,15 @@ const postgresTargetDescriptor = {
428
1283
  ...postgresTargetDescriptorMeta,
429
1284
  contractSerializer: new PostgresContractSerializer(),
430
1285
  schemaVerifier: new PostgresSchemaVerifier(),
1286
+ inferPslContract(schema, describedContracts) {
1287
+ PostgresDatabaseSchemaNode.assert(schema);
1288
+ return inferPostgresPslContract(schema, describedContracts);
1289
+ },
1290
+ diffSchema(input) {
1291
+ return diffPostgresSchema(input);
1292
+ },
1293
+ classifySubjectGranularity: postgresDiffSubjectGranularity,
1294
+ classifyEntityKind: postgresDiffSubjectEntityKind,
431
1295
  migrations: {
432
1296
  createPlanner(adapter) {
433
1297
  return createPostgresMigrationPlanner(adapter);
@@ -436,9 +1300,10 @@ const postgresTargetDescriptor = {
436
1300
  return createPostgresMigrationRunner(family);
437
1301
  },
438
1302
  contractToSchema(contract, frameworkComponents) {
439
- return contractToSchemaIR(contract, {
1303
+ const expander = buildNativeTypeExpander(frameworkComponents);
1304
+ return contractToPostgresDatabaseSchemaNode(blindCast(contract), {
440
1305
  annotationNamespace: "pg",
441
- ...ifDefined("expandNativeType", buildNativeTypeExpander(frameworkComponents)),
1306
+ ...ifDefined("expandNativeType", expander),
442
1307
  renderDefault: postgresRenderDefault
443
1308
  });
444
1309
  }