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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (266) hide show
  1. package/dist/authoring-Bi9aa8zG.mjs +574 -0
  2. package/dist/authoring-Bi9aa8zG.mjs.map +1 -0
  3. package/dist/canonicalize-CAbXtVtB.d.mts +37 -0
  4. package/dist/canonicalize-CAbXtVtB.d.mts.map +1 -0
  5. package/dist/{codec-ids-CnXu9Qy3.d.mts → codec-ids-BzrFF-I4.d.mts} +3 -2
  6. package/dist/codec-ids-BzrFF-I4.d.mts.map +1 -0
  7. package/dist/{codec-ids-BvytN2P8.mjs → codec-ids-C_-Hj6bL.mjs} +3 -2
  8. package/dist/codec-ids-C_-Hj6bL.mjs.map +1 -0
  9. package/dist/codec-ids.d.mts +2 -2
  10. package/dist/codec-ids.mjs +2 -2
  11. package/dist/{codec-types-DHCkwPKE.d.mts → codec-types-BiIWziRO.d.mts} +3 -2
  12. package/dist/codec-types-BiIWziRO.d.mts.map +1 -0
  13. package/dist/codec-types.d.mts +1 -1
  14. package/dist/codecs-BemGS69L.mjs +927 -0
  15. package/dist/codecs-BemGS69L.mjs.map +1 -0
  16. package/dist/{codecs--0A5_4Bq.d.mts → codecs-Cm-nS4mQ.d.mts} +111 -4
  17. package/dist/codecs-Cm-nS4mQ.d.mts.map +1 -0
  18. package/dist/codecs.d.mts +2 -2
  19. package/dist/codecs.mjs +3 -757
  20. package/dist/codecs.mjs.map +1 -1
  21. package/dist/contract-free.d.mts +33 -3
  22. package/dist/contract-free.d.mts.map +1 -1
  23. package/dist/contract-free.mjs +23 -7
  24. package/dist/contract-free.mjs.map +1 -1
  25. package/dist/control-policy-5LE2kwfb.mjs +1285 -0
  26. package/dist/control-policy-5LE2kwfb.mjs.map +1 -0
  27. package/dist/control.d.mts +2 -2
  28. package/dist/control.d.mts.map +1 -1
  29. package/dist/control.mjs +866 -36
  30. package/dist/control.mjs.map +1 -1
  31. package/dist/data-transform-BOWpliq8.mjs.map +1 -1
  32. package/dist/{data-transform-DDgWdB5o.d.mts → data-transform-DPzwBMhW.d.mts} +3 -3
  33. package/dist/{data-transform-DDgWdB5o.d.mts.map → data-transform-DPzwBMhW.d.mts.map} +1 -1
  34. package/dist/data-transform.d.mts +1 -1
  35. package/dist/{ddl-QDyOSeLc.mjs → ddl-BQzITB_e.mjs} +128 -6
  36. package/dist/ddl-BQzITB_e.mjs.map +1 -0
  37. package/dist/ddl.d.mts +3 -2
  38. package/dist/ddl.mjs +2 -2
  39. package/dist/default-normalizer.d.mts +1 -1
  40. package/dist/default-normalizer.d.mts.map +1 -1
  41. package/dist/default-normalizer.mjs +247 -1
  42. package/dist/default-normalizer.mjs.map +1 -0
  43. package/dist/descriptor-meta-DzL6vXAz.mjs +22 -0
  44. package/dist/descriptor-meta-DzL6vXAz.mjs.map +1 -0
  45. package/dist/descriptor-meta-runtime-UwYdV8fD.mjs +12 -0
  46. package/dist/descriptor-meta-runtime-UwYdV8fD.mjs.map +1 -0
  47. package/dist/diff-database-schema-DULhiCNM.mjs +305 -0
  48. package/dist/diff-database-schema-DULhiCNM.mjs.map +1 -0
  49. package/dist/diff-database-schema.d.mts +46 -0
  50. package/dist/diff-database-schema.d.mts.map +1 -0
  51. package/dist/diff-database-schema.mjs +2 -0
  52. package/dist/errors-DO-w0EUS.mjs +35 -0
  53. package/dist/errors-DO-w0EUS.mjs.map +1 -0
  54. package/dist/errors.d.mts +11 -9
  55. package/dist/errors.d.mts.map +1 -1
  56. package/dist/errors.mjs +1 -1
  57. package/dist/issue-planner.d.mts +35 -11
  58. package/dist/issue-planner.d.mts.map +1 -1
  59. package/dist/issue-planner.mjs +2 -2
  60. package/dist/migration.d.mts +5 -5
  61. package/dist/migration.d.mts.map +1 -1
  62. package/dist/migration.mjs +4 -4
  63. package/dist/namespace-ids-xtp_ZY86.mjs +7 -0
  64. package/dist/namespace-ids-xtp_ZY86.mjs.map +1 -0
  65. package/dist/native-type-normalizer.mjs +37 -1
  66. package/dist/native-type-normalizer.mjs.map +1 -0
  67. package/dist/nodes-Bc2N3tMy.d.mts +170 -0
  68. package/dist/nodes-Bc2N3tMy.d.mts.map +1 -0
  69. package/dist/nodes-DJC5B8Id.mjs +192 -0
  70. package/dist/nodes-DJC5B8Id.mjs.map +1 -0
  71. package/dist/{op-factory-call-DmQEc3XV.d.mts → op-factory-call-Bn9zDx4_.d.mts} +114 -15
  72. package/dist/op-factory-call-Bn9zDx4_.d.mts.map +1 -0
  73. package/dist/{op-factory-call-D_p5vxwt.mjs → op-factory-call-D6yu-PlS.mjs} +469 -32
  74. package/dist/op-factory-call-D6yu-PlS.mjs.map +1 -0
  75. package/dist/op-factory-call.d.mts +2 -2
  76. package/dist/op-factory-call.mjs +2 -2
  77. package/dist/pack.d.mts +300 -3
  78. package/dist/pack.d.mts.map +1 -1
  79. package/dist/pack.mjs +1 -1
  80. package/dist/planner-DwDxdYxi.mjs +390 -0
  81. package/dist/planner-DwDxdYxi.mjs.map +1 -0
  82. package/dist/{planner-ddl-builders-B2wOwLqI.mjs → planner-ddl-builders-BKlmGDJl.mjs} +17 -28
  83. package/dist/planner-ddl-builders-BKlmGDJl.mjs.map +1 -0
  84. package/dist/planner-ddl-builders.d.mts +4 -6
  85. package/dist/planner-ddl-builders.d.mts.map +1 -1
  86. package/dist/planner-ddl-builders.mjs +2 -2
  87. package/dist/planner-identity-values-CJPha2Sz.mjs.map +1 -1
  88. package/dist/planner-identity-values.d.mts +8 -2
  89. package/dist/planner-identity-values.d.mts.map +1 -1
  90. package/dist/planner-identity-values.mjs +2 -2
  91. package/dist/{planner-produced-postgres-migration-QqHa2C2l.d.mts → planner-produced-postgres-migration-BEY1T0Xm.d.mts} +4 -4
  92. package/dist/{planner-produced-postgres-migration-QqHa2C2l.d.mts.map → planner-produced-postgres-migration-BEY1T0Xm.d.mts.map} +1 -1
  93. package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs → planner-produced-postgres-migration-BGPpq56_.mjs} +3 -3
  94. package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs.map → planner-produced-postgres-migration-BGPpq56_.mjs.map} +1 -1
  95. package/dist/planner-produced-postgres-migration.d.mts +1 -1
  96. package/dist/planner-produced-postgres-migration.mjs +1 -1
  97. package/dist/{planner-sql-checks-jqUUGyQR.mjs → planner-sql-checks-CDXn2uaS.mjs} +5 -5
  98. package/dist/{planner-sql-checks-jqUUGyQR.mjs.map → planner-sql-checks-CDXn2uaS.mjs.map} +1 -1
  99. package/dist/planner-sql-checks.d.mts +2 -2
  100. package/dist/planner-sql-checks.d.mts.map +1 -1
  101. package/dist/planner-sql-checks.mjs +1 -1
  102. package/dist/{planner-target-details-CIY6tLeo.d.mts → planner-target-details-HkP4RrRO.d.mts} +2 -2
  103. package/dist/planner-target-details-HkP4RrRO.d.mts.map +1 -0
  104. package/dist/planner-target-details.d.mts +1 -1
  105. package/dist/planner.d.mts +72 -17
  106. package/dist/planner.d.mts.map +1 -1
  107. package/dist/planner.mjs +3 -2
  108. package/dist/{postgres-contract-serializer-k3TAcPMY.mjs → postgres-contract-view-C3LPCLP_.mjs} +45 -41
  109. package/dist/postgres-contract-view-C3LPCLP_.mjs.map +1 -0
  110. package/dist/postgres-contract-view-C9j5cqP0.d.mts +34 -0
  111. package/dist/postgres-contract-view-C9j5cqP0.d.mts.map +1 -0
  112. package/dist/postgres-database-schema-node-CJv5bfbs.d.mts +262 -0
  113. package/dist/postgres-database-schema-node-CJv5bfbs.d.mts.map +1 -0
  114. package/dist/{postgres-migration-Y4YBJqkS.d.mts → postgres-migration-DbckK1su.d.mts} +58 -9
  115. package/dist/postgres-migration-DbckK1su.d.mts.map +1 -0
  116. package/dist/{postgres-migration-B5jKrXv3.mjs → postgres-migration-et1td40f.mjs} +78 -45
  117. package/dist/postgres-migration-et1td40f.mjs.map +1 -0
  118. package/dist/postgres-native-enum-BwVNf0Ku.mjs +45 -0
  119. package/dist/postgres-native-enum-BwVNf0Ku.mjs.map +1 -0
  120. package/dist/postgres-rls-policy--CSddvMR.d.mts +52 -0
  121. package/dist/postgres-rls-policy--CSddvMR.d.mts.map +1 -0
  122. package/dist/postgres-role-schema-node-Cm-j0ZGM.mjs +190 -0
  123. package/dist/postgres-role-schema-node-Cm-j0ZGM.mjs.map +1 -0
  124. package/dist/postgres-schema-DKq6s1P3.d.mts +269 -0
  125. package/dist/postgres-schema-DKq6s1P3.d.mts.map +1 -0
  126. package/dist/{postgres-schema-COGZ1ark.mjs → postgres-schema-DYATroNx.mjs} +200 -11
  127. package/dist/postgres-schema-DYATroNx.mjs.map +1 -0
  128. package/dist/postgres-table-schema-node-D6LvInCe.mjs +216 -0
  129. package/dist/postgres-table-schema-node-D6LvInCe.mjs.map +1 -0
  130. package/dist/render-ops.d.mts +1 -1
  131. package/dist/{render-typescript-KMgosran.mjs → render-typescript-7yqILcwr.mjs} +45 -16
  132. package/dist/render-typescript-7yqILcwr.mjs.map +1 -0
  133. package/dist/render-typescript.mjs +1 -1
  134. package/dist/resolve-ddl-schema-DpGte50u.mjs +22 -0
  135. package/dist/resolve-ddl-schema-DpGte50u.mjs.map +1 -0
  136. package/dist/rls-canonicalize.d.mts +20 -0
  137. package/dist/rls-canonicalize.d.mts.map +1 -0
  138. package/dist/rls-canonicalize.mjs +2 -0
  139. package/dist/runtime.d.mts +6 -8
  140. package/dist/runtime.d.mts.map +1 -1
  141. package/dist/runtime.mjs +3 -3
  142. package/dist/runtime.mjs.map +1 -1
  143. package/dist/schema-ir-annotations.d.mts +15 -0
  144. package/dist/schema-ir-annotations.d.mts.map +1 -0
  145. package/dist/schema-ir-annotations.mjs +2 -0
  146. package/dist/{sql-utils-DcfMz4MQ.mjs → sql-utils-SU4FDvIV.mjs} +12 -3
  147. package/dist/{sql-utils-DcfMz4MQ.mjs.map → sql-utils-SU4FDvIV.mjs.map} +1 -1
  148. package/dist/sql-utils.d.mts +8 -1
  149. package/dist/sql-utils.d.mts.map +1 -1
  150. package/dist/sql-utils.mjs +2 -2
  151. package/dist/types.d.mts +4 -140
  152. package/dist/types.mjs +5 -2
  153. package/dist/wire-name-rHHtr1h0.mjs +75 -0
  154. package/dist/wire-name-rHHtr1h0.mjs.map +1 -0
  155. package/package.json +26 -20
  156. package/src/contract-free/checks.ts +153 -0
  157. package/src/contract-free/control-bootstrap.ts +20 -3
  158. package/src/contract-free/ddl.ts +98 -1
  159. package/src/core/authoring.ts +509 -2
  160. package/src/core/codec-helpers.ts +33 -7
  161. package/src/core/codec-ids.ts +1 -0
  162. package/src/core/codec-type-map.ts +2 -0
  163. package/src/core/codecs.ts +193 -12
  164. package/src/core/ddl/nodes.ts +185 -2
  165. package/src/core/default-normalizer.ts +122 -2
  166. package/src/core/descriptor-meta.ts +10 -1
  167. package/src/core/entity-kinds.ts +41 -0
  168. package/src/core/errors.ts +14 -12
  169. package/src/core/migrations/bound-schema.ts +10 -0
  170. package/src/core/migrations/column-ddl-rendering.ts +117 -0
  171. package/src/core/migrations/contract-to-postgres-database-schema-node.ts +189 -0
  172. package/src/core/migrations/control-policy.ts +217 -65
  173. package/src/core/migrations/diff-database-schema.ts +252 -0
  174. package/src/core/migrations/issue-planner.ts +817 -656
  175. package/src/core/migrations/op-factory-call.ts +383 -23
  176. package/src/core/migrations/operations/columns.ts +24 -12
  177. package/src/core/migrations/operations/constraints.ts +1 -1
  178. package/src/core/migrations/operations/data-transform.ts +6 -0
  179. package/src/core/migrations/operations/dependencies.ts +2 -1
  180. package/src/core/migrations/operations/native-enum-types.ts +62 -0
  181. package/src/core/migrations/operations/rls.ts +187 -0
  182. package/src/core/migrations/operations/shared.ts +0 -30
  183. package/src/core/migrations/planner-ddl-builders.ts +31 -59
  184. package/src/core/migrations/planner-identity-values.ts +1 -1
  185. package/src/core/migrations/planner-recipes.ts +31 -13
  186. package/src/core/migrations/planner-sql-checks.ts +1 -1
  187. package/src/core/migrations/planner-strategies.ts +248 -216
  188. package/src/core/migrations/planner-target-details.ts +3 -1
  189. package/src/core/migrations/planner.ts +357 -67
  190. package/src/core/migrations/postgres-migration.ts +118 -86
  191. package/src/core/migrations/render-typescript.ts +42 -15
  192. package/src/core/migrations/resolve-ddl-schema.ts +26 -0
  193. package/src/core/migrations/runner.ts +11 -16
  194. package/src/core/migrations/verify-postgres-namespaces.ts +46 -31
  195. package/src/core/namespace-ids.ts +3 -0
  196. package/src/core/postgres-contract-serializer.ts +46 -71
  197. package/src/core/postgres-contract-view.ts +48 -0
  198. package/src/core/postgres-native-enum.ts +61 -0
  199. package/src/core/postgres-rls-enablement.ts +34 -0
  200. package/src/core/postgres-rls-policy.ts +64 -0
  201. package/src/core/postgres-role.ts +59 -0
  202. package/src/core/postgres-schema-verifier.ts +10 -7
  203. package/src/core/postgres-schema.ts +85 -15
  204. package/src/core/postgres-validators.ts +34 -0
  205. package/src/core/psl-infer/infer-psl-contract.ts +1273 -0
  206. package/src/core/psl-infer/postgres-default-mapping.ts +16 -0
  207. package/src/core/psl-infer/postgres-type-map.ts +128 -0
  208. package/src/core/rls/canonicalize.ts +48 -0
  209. package/src/core/rls/wire-name.ts +33 -0
  210. package/src/core/schema-ir/node-storage-coordinate.ts +26 -0
  211. package/src/core/schema-ir/postgres-database-schema-node.ts +61 -0
  212. package/src/core/schema-ir/postgres-namespace-schema-node.ts +70 -0
  213. package/src/core/schema-ir/postgres-native-enum-schema-node.ts +83 -0
  214. package/src/core/schema-ir/postgres-policy-schema-node.ts +90 -0
  215. package/src/core/schema-ir/postgres-role-schema-node.ts +65 -0
  216. package/src/core/schema-ir/postgres-table-schema-node.ts +140 -0
  217. package/src/core/schema-ir/schema-node-kinds.ts +122 -0
  218. package/src/core/sql-utils.ts +15 -2
  219. package/src/exports/codecs.ts +3 -0
  220. package/src/exports/contract-free.ts +11 -1
  221. package/src/exports/control.ts +27 -33
  222. package/src/exports/ddl.ts +8 -0
  223. package/src/exports/diff-database-schema.ts +7 -0
  224. package/src/exports/issue-planner.ts +1 -1
  225. package/src/exports/migration.ts +1 -0
  226. package/src/exports/op-factory-call.ts +4 -0
  227. package/src/exports/planner-ddl-builders.ts +0 -2
  228. package/src/exports/planner-identity-values.ts +4 -1
  229. package/src/exports/planner.ts +1 -0
  230. package/src/exports/rls-canonicalize.ts +7 -0
  231. package/src/exports/runtime.ts +1 -0
  232. package/src/exports/schema-ir-annotations.ts +1 -0
  233. package/src/exports/sql-utils.ts +1 -0
  234. package/src/exports/types.ts +37 -0
  235. package/dist/codec-ids-BvytN2P8.mjs.map +0 -1
  236. package/dist/codec-ids-CnXu9Qy3.d.mts.map +0 -1
  237. package/dist/codec-types-DHCkwPKE.d.mts.map +0 -1
  238. package/dist/codecs--0A5_4Bq.d.mts.map +0 -1
  239. package/dist/ddl-QDyOSeLc.mjs.map +0 -1
  240. package/dist/default-normalizer-DyyCHQWs.mjs +0 -131
  241. package/dist/default-normalizer-DyyCHQWs.mjs.map +0 -1
  242. package/dist/descriptor-meta-CpGygXpI.mjs +0 -140
  243. package/dist/descriptor-meta-CpGygXpI.mjs.map +0 -1
  244. package/dist/errors-CUk87ByX.mjs +0 -33
  245. package/dist/errors-CUk87ByX.mjs.map +0 -1
  246. package/dist/issue-planner-DL6g3CmE.mjs +0 -824
  247. package/dist/issue-planner-DL6g3CmE.mjs.map +0 -1
  248. package/dist/native-type-normalizer-Bc9XJzWC.mjs +0 -38
  249. package/dist/native-type-normalizer-Bc9XJzWC.mjs.map +0 -1
  250. package/dist/nodes-Bbhs2rwj.mjs +0 -76
  251. package/dist/nodes-Bbhs2rwj.mjs.map +0 -1
  252. package/dist/nodes-pLeLgdis.d.mts +0 -67
  253. package/dist/nodes-pLeLgdis.d.mts.map +0 -1
  254. package/dist/op-factory-call-D_p5vxwt.mjs.map +0 -1
  255. package/dist/op-factory-call-DmQEc3XV.d.mts.map +0 -1
  256. package/dist/planner-Bs_baQax.mjs +0 -324
  257. package/dist/planner-Bs_baQax.mjs.map +0 -1
  258. package/dist/planner-ddl-builders-B2wOwLqI.mjs.map +0 -1
  259. package/dist/planner-target-details-CIY6tLeo.d.mts.map +0 -1
  260. package/dist/postgres-contract-serializer-k3TAcPMY.mjs.map +0 -1
  261. package/dist/postgres-migration-B5jKrXv3.mjs.map +0 -1
  262. package/dist/postgres-migration-Y4YBJqkS.d.mts.map +0 -1
  263. package/dist/postgres-schema-COGZ1ark.mjs.map +0 -1
  264. package/dist/render-typescript-KMgosran.mjs.map +0 -1
  265. package/dist/types.d.mts.map +0 -1
  266. package/src/core/postgres-enum-type-schema.ts +0 -17
@@ -0,0 +1,1273 @@
1
+ import type { ColumnDefault } from '@prisma-next/contract/types';
2
+ import type { SqlDescribedContractSpace } from '@prisma-next/family-sql/control';
3
+ import type {
4
+ DefaultMappingOptions,
5
+ EnumInfo,
6
+ PslNativeTypeAttribute,
7
+ PslPrinterOptions,
8
+ PslTypeMap,
9
+ RelationField,
10
+ } from '@prisma-next/family-sql/psl-infer';
11
+ import {
12
+ buildChildRelationField,
13
+ deriveRelationFieldName,
14
+ inferRelations,
15
+ mapDefault,
16
+ parseRawDefault,
17
+ toEnumMemberName,
18
+ toEnumName,
19
+ toFieldName,
20
+ toModelName,
21
+ toNamedTypeName,
22
+ } from '@prisma-next/family-sql/psl-infer';
23
+ import { coordinateKey, elementCoordinates } from '@prisma-next/framework-components/ir';
24
+ import type {
25
+ PslAttribute,
26
+ PslAttributeArgument,
27
+ PslDocumentAst,
28
+ PslExtensionBlock,
29
+ PslExtensionBlockParamValue,
30
+ PslField,
31
+ PslFieldAttribute,
32
+ PslModel,
33
+ PslModelAttribute,
34
+ PslNamedTypeDeclaration,
35
+ PslSpan,
36
+ PslTypeConstructorCall,
37
+ PslTypesBlock,
38
+ } from '@prisma-next/framework-components/psl-ast';
39
+ import {
40
+ makePslNamespace,
41
+ makePslNamespaceEntries,
42
+ UNSPECIFIED_PSL_NAMESPACE_ID,
43
+ } from '@prisma-next/framework-components/psl-ast';
44
+ import type { SqlModelStorage } from '@prisma-next/sql-contract/types';
45
+ import type { SqlColumnIR, SqlForeignKeyIR } from '@prisma-next/sql-schema-ir/types';
46
+ import { SqlSchemaIR, SqlTableIR } from '@prisma-next/sql-schema-ir/types';
47
+ import { blindCast } from '@prisma-next/utils/casts';
48
+ import { ifDefined } from '@prisma-next/utils/defined';
49
+ import type { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';
50
+ import { createPostgresDefaultMapping } from './postgres-default-mapping';
51
+ import { createPostgresTypeMap } from './postgres-type-map';
52
+
53
+ const SYNTHETIC_SPAN: PslSpan = {
54
+ start: { offset: 0, line: 1, column: 1 },
55
+ end: { offset: 0, line: 1, column: 1 },
56
+ };
57
+
58
+ const PSL_SCALAR_TYPE_NAMES = new Set([
59
+ 'String',
60
+ 'Boolean',
61
+ 'Int',
62
+ 'BigInt',
63
+ 'Float',
64
+ 'Decimal',
65
+ 'DateTime',
66
+ 'Json',
67
+ 'Bytes',
68
+ ]);
69
+
70
+ type ResolvedColumnFieldName = {
71
+ readonly fieldName: string;
72
+ readonly fieldMap?: string | undefined;
73
+ };
74
+
75
+ type TableColumnFieldNameMap = ReadonlyMap<string, ResolvedColumnFieldName>;
76
+
77
+ type NamedTypeRegistryEntry = {
78
+ readonly name: string;
79
+ readonly baseType: string;
80
+ readonly nativeTypeAttribute: PslNativeTypeAttribute;
81
+ };
82
+
83
+ type NamedTypeRegistry = {
84
+ readonly entriesByKey: Map<string, NamedTypeRegistryEntry>;
85
+ readonly usedNames: Set<string>;
86
+ };
87
+
88
+ type TopLevelNameResult = {
89
+ readonly name: string;
90
+ readonly map?: string | undefined;
91
+ };
92
+
93
+ /**
94
+ * Coordinates every element a set of already-assembled contracts declare,
95
+ * mapped to the {@link SqlDescribedContractSpace} that owns it and keyed by
96
+ * the shared {@link coordinateKey} helper. `contract infer` uses this to omit
97
+ * database elements a stack extension pack's contract space already
98
+ * describes — reusing the same coordinate walk the contract-space aggregate
99
+ * and cross-space collision check use (`elementCoordinates`), rather than a
100
+ * bespoke per-entity-kind membership test — and, for a foreign key whose
101
+ * referenced table an entry owns, to resolve the qualified cross-space
102
+ * relation it describes.
103
+ */
104
+ function describedContractOwners(
105
+ describedContracts: readonly SqlDescribedContractSpace[],
106
+ ): ReadonlyMap<string, SqlDescribedContractSpace> {
107
+ const owners = new Map<string, SqlDescribedContractSpace>();
108
+ for (const entry of describedContracts) {
109
+ for (const coordinate of elementCoordinates(entry.contract.storage)) {
110
+ owners.set(coordinateKey(coordinate), entry);
111
+ }
112
+ }
113
+ return owners;
114
+ }
115
+
116
+ /**
117
+ * The domain model a described contract maps a `(namespaceId, tableName)`
118
+ * storage coordinate to, plus the pack's own space id and column→field-name
119
+ * mapping — everything `buildModel`/`buildRelationField` need to emit the
120
+ * cross-space relation `<spaceId>:<namespaceId>.<modelName>` and resolve its
121
+ * `references` argument to the pack's own field names rather than a generic
122
+ * column-name guess.
123
+ */
124
+ type CrossSpaceTarget = {
125
+ readonly spaceId: string;
126
+ readonly namespaceId: string;
127
+ readonly modelName: string;
128
+ readonly fieldNamesByColumn: TableColumnFieldNameMap;
129
+ };
130
+
131
+ function resolveCrossSpaceTarget(
132
+ owner: SqlDescribedContractSpace,
133
+ namespaceId: string,
134
+ tableName: string,
135
+ ): CrossSpaceTarget | undefined {
136
+ const domainNamespace = owner.contract.domain.namespaces[namespaceId];
137
+ if (domainNamespace === undefined) {
138
+ return undefined;
139
+ }
140
+
141
+ for (const [modelName, model] of Object.entries(domainNamespace.models)) {
142
+ const storage = blindCast<SqlModelStorage, 'SQL contract model storage'>(model.storage);
143
+ if (storage.namespaceId !== namespaceId || storage.table !== tableName) {
144
+ continue;
145
+ }
146
+
147
+ const fieldNamesByColumn = new Map<string, ResolvedColumnFieldName>();
148
+ for (const [fieldName, fieldStorage] of Object.entries(storage.fields)) {
149
+ fieldNamesByColumn.set(fieldStorage.column, { fieldName });
150
+ }
151
+
152
+ return { spaceId: owner.spaceId, namespaceId, modelName, fieldNamesByColumn };
153
+ }
154
+
155
+ return undefined;
156
+ }
157
+
158
+ type ForeignKeyResolution = {
159
+ /** `tables`, with every cross-space or dangling foreign key removed. */
160
+ readonly tables: Record<string, SqlTableIR>;
161
+ /** Cross-space relation fields to merge onto `inferRelations`'s output, keyed by host table name. */
162
+ readonly extraRelationsByTable: ReadonlyMap<string, readonly RelationField[]>;
163
+ /** Synthetic field-name maps for cross-space-referenced pack tables, merged into `fieldNamesByTable`. */
164
+ readonly crossSpaceFieldNamesByTable: ReadonlyMap<string, TableColumnFieldNameMap>;
165
+ };
166
+
167
+ /**
168
+ * Classifies every foreign key on a surviving table into one of three cases.
169
+ * A foreign key that carries a `referencedSchema` is checked against the
170
+ * pack-owned coordinates first, so a pack-owned target wins even when a local
171
+ * table happens to share its bare name; only foreign keys with no owned
172
+ * coordinate fall through to the local/dangling distinction.
173
+ *
174
+ * - **Cross-space**: `referencedSchema` is set and a described contract owns
175
+ * the coordinate `(referencedSchema, 'table', referencedTable)`. The
176
+ * referenced table is absent from the tree (omitted because the pack
177
+ * describes it, or never introspected — `contract infer` walks a single
178
+ * namespace). Removed from `foreignKeys` (so `inferRelations` never falls
179
+ * back to a bare, unqualified table name for it) and replaced with a
180
+ * `RelationField` qualified with the owning pack's space id and namespace
181
+ * id. `owners` holds only pack-declared coordinates, so an app's own table
182
+ * (e.g. `public.users`) is never owned and cannot be captured here.
183
+ * - **Local**: not a pack-owned coordinate, and the referenced table survived
184
+ * introspection — left untouched, `inferRelations` handles it as before.
185
+ * - **Dangling**: not a pack-owned coordinate, and the referenced table is
186
+ * neither in the tree nor owned by any described contract. Removed from
187
+ * `foreignKeys`, keeping the scalar column, rather than emitting a relation
188
+ * to a model that was never defined.
189
+ *
190
+ * A pack that owns the referenced coordinate but declares no domain model
191
+ * mapped to it is malformed; that case throws rather than degrading to a
192
+ * silent drop, which would contradict the dangling definition above.
193
+ */
194
+ function resolveForeignKeys(
195
+ tables: Readonly<Record<string, SqlTableIR>>,
196
+ owners: ReadonlyMap<string, SqlDescribedContractSpace>,
197
+ ): ForeignKeyResolution {
198
+ const resultTables: Record<string, SqlTableIR> = {};
199
+ const extraRelationsByTable = new Map<string, RelationField[]>();
200
+ const crossSpaceFieldNamesByTable = new Map<string, TableColumnFieldNameMap>();
201
+
202
+ for (const [tableName, table] of Object.entries(tables)) {
203
+ const keptForeignKeys: SqlForeignKeyIR[] = [];
204
+
205
+ for (const fk of table.foreignKeys) {
206
+ if (fk.referencedSchema !== undefined) {
207
+ const owner = owners.get(
208
+ coordinateKey({
209
+ namespaceId: fk.referencedSchema,
210
+ entityKind: 'table',
211
+ entityName: fk.referencedTable,
212
+ }),
213
+ );
214
+ if (owner !== undefined) {
215
+ const target = resolveCrossSpaceTarget(owner, fk.referencedSchema, fk.referencedTable);
216
+ if (target === undefined) {
217
+ throw new Error(
218
+ `contract infer: described contract space "${owner.spaceId}" owns storage ` +
219
+ `coordinate "${fk.referencedSchema}.${fk.referencedTable}" but declares no ` +
220
+ 'domain model mapped to it. A pack that describes a table must also declare the ' +
221
+ 'domain model it maps to; this pack is malformed.',
222
+ );
223
+ }
224
+
225
+ if (!crossSpaceFieldNamesByTable.has(fk.referencedTable)) {
226
+ crossSpaceFieldNamesByTable.set(fk.referencedTable, target.fieldNamesByColumn);
227
+ }
228
+
229
+ const fieldName = deriveRelationFieldName(fk.columns, fk.referencedTable);
230
+ const optional = fk.columns.some(
231
+ (columnName) => table.columns[columnName]?.nullable ?? false,
232
+ );
233
+ const relationField: RelationField = {
234
+ ...buildChildRelationField(fieldName, target.modelName, fk, optional),
235
+ typeNamespaceId: target.namespaceId,
236
+ typeContractSpaceId: target.spaceId,
237
+ };
238
+
239
+ const existingRelations = extraRelationsByTable.get(tableName);
240
+ if (existingRelations) {
241
+ existingRelations.push(relationField);
242
+ } else {
243
+ extraRelationsByTable.set(tableName, [relationField]);
244
+ }
245
+ continue;
246
+ }
247
+ }
248
+
249
+ // Not a pack-owned coordinate: keep the foreign key if the referenced
250
+ // table survived introspection (local), otherwise drop it while keeping
251
+ // the scalar column (dangling).
252
+ if (tables[fk.referencedTable] !== undefined) {
253
+ keptForeignKeys.push(fk);
254
+ }
255
+ }
256
+
257
+ resultTables[tableName] =
258
+ keptForeignKeys.length === table.foreignKeys.length
259
+ ? table
260
+ : new SqlTableIR({ ...table, foreignKeys: keptForeignKeys });
261
+ }
262
+
263
+ return { tables: resultTables, extraRelationsByTable, crossSpaceFieldNamesByTable };
264
+ }
265
+
266
+ /**
267
+ * Infers a PSL AST (for `printPsl`) from an introspected Postgres schema tree.
268
+ *
269
+ * Target-owned inference: it walks the `PostgresDatabaseSchemaNode` tree and
270
+ * owns the Postgres dialect knowledge — the native type map and default map.
271
+ * Relation inference, name transforms, generic default mapping, and raw-default
272
+ * parsing are shape-neutral utilities imported from the SQL family.
273
+ *
274
+ * This slice emits relational-only PSL, byte-identical to the prior flat
275
+ * inference: the tree's tables (across its namespaces — `contract infer`
276
+ * introspects a single live namespace) are gathered into the model set and
277
+ * emitted as one `UNSPECIFIED_PSL_NAMESPACE_ID` bucket. Top-level entities
278
+ * (policies/roles → PSL extension blocks) are a later slice.
279
+ *
280
+ * `describedContracts` — the stack's extension packs' already-assembled
281
+ * contracts, each paired with its space id — is consulted while gathering
282
+ * tables: a table whose coordinate `(schemaName, 'table', tableName)` one of
283
+ * those contracts already declares is omitted, before the duplicate-name
284
+ * check below and before relation inference, so it cannot spuriously
285
+ * collide with an app table and never contributes a bare relation field. A
286
+ * surviving table's foreign key into an omitted, pack-owned table is not
287
+ * dropped: {@link resolveForeignKeys} rewrites it into a relation qualified
288
+ * with the pack's space id (`<spaceId>:<namespaceId>.<Model>`) instead.
289
+ */
290
+ export function inferPostgresPslContract(
291
+ tree: PostgresDatabaseSchemaNode,
292
+ describedContracts?: readonly SqlDescribedContractSpace[],
293
+ ): PslDocumentAst {
294
+ const namespaces = Object.values(tree.namespaces);
295
+ const owners = describedContractOwners(describedContracts ?? []);
296
+
297
+ // Native enum adoption: each namespace's introspected `enums` nodes become
298
+ // `native_enum` blocks + `pg.enum(<Name>)` columns, minus the types a
299
+ // described pack contract already declares (resolved through the same
300
+ // `owners` / `describedContractOwners` coordinate map as table subtraction —
301
+ // `elementCoordinates` keys `entries.native_enum` by physical type name, no
302
+ // enum-specific index). An inferred block carries no explicit `control` and
303
+ // inherits the contract's `defaultControl`; under `defaultControl: 'managed'`
304
+ // the planner owns the type's create/drop lifecycle and `db verify` reports
305
+ // member drift (#949). A suffix-appended member plans `ALTER TYPE ... ADD
306
+ // VALUE`; any other member change (rename, removal, reorder) is refused
307
+ // with a named diagnostic — see `docs/reference/postgres-native-enums.md`.
308
+ const enumDefinitions = new Map<string, readonly string[]>();
309
+ const packOwnedEnumTypesByNamespace = new Map<string, Map<string, string>>();
310
+ const enumNamespaceNames = new Set<string>();
311
+ for (const namespace of namespaces) {
312
+ for (const { typeName, members } of namespace.nativeEnums) {
313
+ const owner = owners.get(
314
+ coordinateKey({
315
+ namespaceId: namespace.schemaName,
316
+ entityKind: 'native_enum',
317
+ entityName: typeName,
318
+ }),
319
+ );
320
+ if (owner !== undefined) {
321
+ const owned = packOwnedEnumTypesByNamespace.get(namespace.schemaName) ?? new Map();
322
+ // Columns reference the type either bare or schema-qualified —
323
+ // `format_type` qualifies a type outside the connection's
324
+ // search_path — so both spellings are owned.
325
+ owned.set(typeName, owner.spaceId);
326
+ owned.set(`${namespace.schemaName}.${typeName}`, owner.spaceId);
327
+ packOwnedEnumTypesByNamespace.set(namespace.schemaName, owned);
328
+ continue;
329
+ }
330
+ enumDefinitions.set(typeName, members);
331
+ enumNamespaceNames.add(namespace.schemaName);
332
+ }
333
+ }
334
+
335
+ // Stopgap (TML-2958): flatten the schema-IR *tree* into the single `{ tables }`
336
+ // map the PSL writer expects. The writer still walks a flat table map, so this
337
+ // is a read-only projection — it does not reintroduce a stored flat schema.
338
+ // The real fix is to extend the PSL writer to walk the namespace tree and emit
339
+ // per-namespace `namespace { … }` blocks; until then `contract infer` handles a
340
+ // single introspected namespace, and a same-named table in two schemas has no
341
+ // unambiguous single-bucket model, so we throw rather than silently drop one.
342
+ const tables: Record<string, SqlTableIR> = {};
343
+ const tableNamespaceNames = new Set<string>();
344
+ for (const namespace of namespaces) {
345
+ const ownedEnumTypes = packOwnedEnumTypesByNamespace.get(namespace.schemaName);
346
+ for (const [tableName, table] of Object.entries(namespace.tables)) {
347
+ if (
348
+ owners.has(
349
+ coordinateKey({
350
+ namespaceId: namespace.schemaName,
351
+ entityKind: 'table',
352
+ entityName: tableName,
353
+ }),
354
+ )
355
+ ) {
356
+ continue;
357
+ }
358
+ if (tables[tableName] !== undefined) {
359
+ throw new Error(
360
+ `contract infer: duplicate table name "${tableName}" across schemas is not yet supported ` +
361
+ '(single-namespace PSL inference emits one flat bucket; multi-namespace `namespace { … }` ' +
362
+ 'output is a later slice).',
363
+ );
364
+ }
365
+ if (ownedEnumTypes !== undefined) {
366
+ for (const column of Object.values(table.columns)) {
367
+ const owningSpaceId = ownedEnumTypes.get(column.nativeType);
368
+ if (owningSpaceId !== undefined) {
369
+ throw new Error(
370
+ `contract infer: column "${tableName}"."${column.name}" is typed by native enum ` +
371
+ `type "${column.nativeType}", which extension pack space "${owningSpaceId}" ` +
372
+ 'already describes. A cross-space enum-typed column has no authorable PSL form ' +
373
+ "yet; describe the table in that pack's contract or retype the column before " +
374
+ 're-running contract infer.',
375
+ );
376
+ }
377
+ }
378
+ }
379
+ tables[tableName] = new SqlTableIR(table);
380
+ tableNamespaceNames.add(namespace.schemaName);
381
+ }
382
+ }
383
+
384
+ // Namespace wrap (pinned during shaping): a `native_enum` block only lowers
385
+ // inside an explicit `namespace { … }` block — the interpreter skips
386
+ // extension entities in the unspecified top-level bucket — so enum-bearing
387
+ // output wraps everything in the introspected schema's name. Enum-free
388
+ // output stays flat and byte-identical to the prior inference.
389
+ let wrapNamespaceName: string | undefined;
390
+ if (enumDefinitions.size > 0) {
391
+ const contentNamespaces = new Set([...enumNamespaceNames, ...tableNamespaceNames]);
392
+ if (contentNamespaces.size > 1) {
393
+ throw new Error(
394
+ 'contract infer: native enum adoption with content across multiple schemas is not yet ' +
395
+ 'supported (single-namespace PSL inference emits one `namespace { … }` block; ' +
396
+ `multi-namespace output is a later slice). Schemas: ${[...contentNamespaces]
397
+ .sort()
398
+ .join(', ')}.`,
399
+ );
400
+ }
401
+ wrapNamespaceName = [...contentNamespaces][0];
402
+ }
403
+
404
+ const {
405
+ tables: resolvedTables,
406
+ extraRelationsByTable,
407
+ crossSpaceFieldNamesByTable,
408
+ } = resolveForeignKeys(tables, owners);
409
+ const schemaIR = new SqlSchemaIR({ tables: resolvedTables });
410
+
411
+ // Live introspection reports an enum column's nativeType schema-qualified
412
+ // whenever the type sits outside the connection's search_path (`format_type`
413
+ // semantics; e.g. `auth.aal_level`), while `pg_type.typname` — the
414
+ // definitions key — is always bare. Register the qualified spelling as an
415
+ // alias so those columns resolve; block emission stays keyed on the bare
416
+ // name (one block per type).
417
+ const enumTypeNames = new Set(enumDefinitions.keys());
418
+ if (wrapNamespaceName !== undefined) {
419
+ for (const typeName of enumDefinitions.keys()) {
420
+ enumTypeNames.add(`${wrapNamespaceName}.${typeName}`);
421
+ }
422
+ }
423
+ const enumInfo: EnumInfo = {
424
+ typeNames: enumTypeNames,
425
+ definitions: enumDefinitions,
426
+ };
427
+ const options: PslPrinterOptions = {
428
+ typeMap: createPostgresTypeMap(enumInfo.typeNames),
429
+ defaultMapping: createPostgresDefaultMapping(),
430
+ parseRawDefault,
431
+ ...(enumDefinitions.size > 0 ? { enumInfo } : {}),
432
+ };
433
+
434
+ return buildPslDocumentAst(
435
+ schemaIR,
436
+ options,
437
+ {
438
+ extraRelationsByTable,
439
+ crossSpaceFieldNamesByTable,
440
+ },
441
+ wrapNamespaceName,
442
+ );
443
+ }
444
+
445
+ export function buildPslDocumentAst(
446
+ schemaIR: SqlSchemaIR,
447
+ options: PslPrinterOptions,
448
+ foreignKeyExtras: Pick<
449
+ ForeignKeyResolution,
450
+ 'extraRelationsByTable' | 'crossSpaceFieldNamesByTable'
451
+ >,
452
+ namespaceName?: string,
453
+ ): PslDocumentAst {
454
+ const { typeMap, defaultMapping, parseRawDefault: rawDefaultParser } = options;
455
+ const { extraRelationsByTable, crossSpaceFieldNamesByTable } = foreignKeyExtras;
456
+
457
+ const modelNames = buildTopLevelNameMap(
458
+ Object.keys(schemaIR.tables),
459
+ toModelName,
460
+ 'model',
461
+ 'table',
462
+ );
463
+
464
+ const modelNameMap = new Map(
465
+ [...modelNames].map(([tableName, result]) => [tableName, result.name]),
466
+ );
467
+
468
+ const { enumNameMap: bareEnumNameMap, enumBlocks } = buildNativeEnumBlocks(
469
+ options.enumInfo?.definitions ?? new Map(),
470
+ modelNames,
471
+ );
472
+
473
+ // Columns reference an enum type bare or schema-qualified (`format_type`
474
+ // qualifies types outside the search_path); alias the qualified spelling
475
+ // onto the same PSL name. Blocks stay keyed on the bare name.
476
+ const enumNameMap = new Map(bareEnumNameMap);
477
+ if (namespaceName !== undefined) {
478
+ for (const [typeName, pslName] of bareEnumNameMap) {
479
+ enumNameMap.set(`${namespaceName}.${typeName}`, pslName);
480
+ }
481
+ }
482
+
483
+ const reservedNamedTypeNames = createReservedNamedTypeNames(modelNames, enumNameMap);
484
+
485
+ // Cross-space entries are seeded first so a real local table of the same
486
+ // bare name (an existing single-namespace-flat-bucket limitation, not new
487
+ // here) always wins the merge, matching `resolveForeignKeys`'s own
488
+ // precedence: a surviving local table is never treated as cross-space.
489
+ const fieldNamesByTable = new Map([
490
+ ...crossSpaceFieldNamesByTable,
491
+ ...buildFieldNamesByTable(schemaIR.tables),
492
+ ]);
493
+ const { relationsByTable } = inferRelations(schemaIR.tables, modelNameMap);
494
+ const namedTypes = seedNamedTypeRegistry(schemaIR, typeMap, enumNameMap, reservedNamedTypeNames);
495
+
496
+ const models: PslModel[] = [];
497
+ for (const table of Object.values(schemaIR.tables)) {
498
+ models.push(
499
+ buildModel(
500
+ table,
501
+ typeMap,
502
+ enumNameMap,
503
+ fieldNamesByTable,
504
+ namedTypes,
505
+ defaultMapping,
506
+ rawDefaultParser,
507
+ [
508
+ ...(relationsByTable.get(table.name) ?? []),
509
+ ...(extraRelationsByTable.get(table.name) ?? []),
510
+ ],
511
+ ),
512
+ );
513
+ }
514
+
515
+ const sortedModels = topologicalSort(models, schemaIR.tables, modelNameMap);
516
+
517
+ const namedTypeEntries = [...namedTypes.entriesByKey.values()].sort((a, b) =>
518
+ a.name.localeCompare(b.name),
519
+ );
520
+ const types: PslTypesBlock | undefined =
521
+ namedTypeEntries.length > 0
522
+ ? {
523
+ kind: 'types',
524
+ declarations: namedTypeEntries.map(buildNamedTypeDeclaration),
525
+ span: SYNTHETIC_SPAN,
526
+ }
527
+ : undefined;
528
+
529
+ // Inferred PSL nodes will eventually be routed into per-namespace buckets
530
+ // matching the source storage; for now everything lands in a single bucket.
531
+ // Without a `namespaceName` that bucket is the synthesised `__unspecified__`
532
+ // one, which the framework printer emits at top level with no
533
+ // `namespace { … }` wrapper — preserving the existing flat introspection
534
+ // output verbatim. With a `namespaceName` (enum-bearing output) the bucket
535
+ // is a real named namespace, printed as an explicit block.
536
+ const ast: PslDocumentAst = {
537
+ kind: 'document',
538
+ sourceId: '<sql-schema-ir>',
539
+ namespaces: [
540
+ makePslNamespace({
541
+ kind: 'namespace',
542
+ name: namespaceName ?? UNSPECIFIED_PSL_NAMESPACE_ID,
543
+ entries: makePslNamespaceEntries(sortedModels, [], enumBlocks),
544
+ span: SYNTHETIC_SPAN,
545
+ }),
546
+ ],
547
+ ...(types ? { types } : {}),
548
+ span: SYNTHETIC_SPAN,
549
+ };
550
+
551
+ return ast;
552
+ }
553
+
554
+ type NativeEnumBlockResult = {
555
+ /** Native enum type name → PSL block name, for `pg.enum(<Name>)` field refs. */
556
+ readonly enumNameMap: ReadonlyMap<string, string>;
557
+ readonly enumBlocks: readonly PslExtensionBlock[];
558
+ };
559
+
560
+ /**
561
+ * Builds one `native_enum` extension-block AST node per introspected enum
562
+ * definition. Block names go through the shared top-level transform
563
+ * (`toEnumName`, intra-enum collisions throw like model collisions) and are
564
+ * then reserved against the model names — an enum whose PSL name a model
565
+ * already claims gets a numeric suffix, with `@@map` carrying the real type
566
+ * name. Members print as explicit `member = "value"` pairs: the member name
567
+ * is the sanitized value (deduplicated within the block), the JSON-encoded
568
+ * value carries the truth verbatim.
569
+ */
570
+ function buildNativeEnumBlocks(
571
+ definitions: ReadonlyMap<string, readonly string[]>,
572
+ modelNames: ReadonlyMap<string, TopLevelNameResult>,
573
+ ): NativeEnumBlockResult {
574
+ const enumNames = buildTopLevelNameMap(
575
+ [...definitions.keys()].sort(),
576
+ toEnumName,
577
+ 'enum',
578
+ 'enum type',
579
+ );
580
+
581
+ const usedTopLevelNames = new Set<string>(PSL_SCALAR_TYPE_NAMES);
582
+ for (const result of modelNames.values()) {
583
+ usedTopLevelNames.add(result.name);
584
+ }
585
+
586
+ const enumNameMap = new Map<string, string>();
587
+ const enumBlocks: PslExtensionBlock[] = [];
588
+ for (const [typeName, result] of enumNames) {
589
+ const name = createUniqueFieldName(result.name, usedTopLevelNames);
590
+ usedTopLevelNames.add(name);
591
+ enumNameMap.set(typeName, name);
592
+ enumBlocks.push(buildNativeEnumBlock(name, typeName, definitions.get(typeName) ?? []));
593
+ }
594
+
595
+ return { enumNameMap, enumBlocks };
596
+ }
597
+
598
+ function buildNativeEnumBlock(
599
+ name: string,
600
+ typeName: string,
601
+ values: readonly string[],
602
+ ): PslExtensionBlock {
603
+ const usedMemberNames = new Set<string>();
604
+ const parameters: Record<string, PslExtensionBlockParamValue> = {};
605
+ for (const value of values) {
606
+ const memberName = createUniqueFieldName(toEnumMemberName(value), usedMemberNames);
607
+ usedMemberNames.add(memberName);
608
+ parameters[memberName] = { kind: 'value', raw: JSON.stringify(value), span: SYNTHETIC_SPAN };
609
+ }
610
+
611
+ return {
612
+ kind: 'native_enum',
613
+ keyword: 'native_enum',
614
+ name,
615
+ parameters,
616
+ blockAttributes:
617
+ name === typeName
618
+ ? []
619
+ : [
620
+ {
621
+ name: 'map',
622
+ args: [
623
+ {
624
+ kind: 'positional',
625
+ value: `"${escapePslString(typeName)}"`,
626
+ span: SYNTHETIC_SPAN,
627
+ },
628
+ ],
629
+ span: SYNTHETIC_SPAN,
630
+ },
631
+ ],
632
+ span: SYNTHETIC_SPAN,
633
+ };
634
+ }
635
+
636
+ function buildModel(
637
+ table: SqlTableIR,
638
+ typeMap: PslTypeMap,
639
+ enumNameMap: ReadonlyMap<string, string>,
640
+ fieldNamesByTable: ReadonlyMap<string, TableColumnFieldNameMap>,
641
+ namedTypes: NamedTypeRegistry,
642
+ defaultMapping: DefaultMappingOptions | undefined,
643
+ rawDefaultParser: PslPrinterOptions['parseRawDefault'],
644
+ relationFields: readonly RelationField[],
645
+ ): PslModel {
646
+ const { name: modelName, map: mapName } = toModelName(table.name);
647
+ const fieldNameMap = fieldNamesByTable.get(table.name);
648
+
649
+ const pkColumns = new Set(table.primaryKey?.columns ?? []);
650
+ const isSinglePk = pkColumns.size === 1;
651
+ const singlePkConstraintName = isSinglePk ? table.primaryKey?.name : undefined;
652
+
653
+ const uniqueColumns = new Map<string, string | undefined>();
654
+ for (const unique of table.uniques) {
655
+ if (unique.columns.length === 1) {
656
+ const [columnName = ''] = unique.columns;
657
+ const existingConstraintName = uniqueColumns.get(columnName);
658
+ if (!uniqueColumns.has(columnName) || (existingConstraintName === undefined && unique.name)) {
659
+ uniqueColumns.set(columnName, unique.name);
660
+ }
661
+ }
662
+ }
663
+
664
+ const fields: PslField[] = [];
665
+ for (const column of Object.values(table.columns)) {
666
+ fields.push(
667
+ buildScalarField(
668
+ column,
669
+ table,
670
+ typeMap,
671
+ enumNameMap,
672
+ fieldNameMap,
673
+ namedTypes,
674
+ defaultMapping,
675
+ rawDefaultParser,
676
+ pkColumns,
677
+ isSinglePk,
678
+ singlePkConstraintName,
679
+ uniqueColumns,
680
+ ),
681
+ );
682
+ }
683
+
684
+ const usedFieldNames = new Set(fields.map((field) => field.name));
685
+ for (const rel of relationFields) {
686
+ fields.push(buildRelationField(rel, table.name, fieldNamesByTable, usedFieldNames));
687
+ }
688
+
689
+ const modelAttributes: PslModelAttribute[] = [];
690
+
691
+ if (table.primaryKey && table.primaryKey.columns.length > 1) {
692
+ const pkFieldNames = table.primaryKey.columns.map((columnName) =>
693
+ resolveColumnFieldName(fieldNamesByTable, table.name, columnName),
694
+ );
695
+ modelAttributes.push(buildModelConstraintAttribute('id', pkFieldNames, table.primaryKey.name));
696
+ }
697
+
698
+ for (const unique of table.uniques) {
699
+ if (unique.columns.length > 1) {
700
+ const uniqueFieldNames = unique.columns.map((columnName) =>
701
+ resolveColumnFieldName(fieldNamesByTable, table.name, columnName),
702
+ );
703
+ modelAttributes.push(buildModelConstraintAttribute('unique', uniqueFieldNames, unique.name));
704
+ }
705
+ }
706
+
707
+ for (const index of table.indexes) {
708
+ if (!index.unique) {
709
+ const indexFieldNames = index.columns.map((columnName) =>
710
+ resolveColumnFieldName(fieldNamesByTable, table.name, columnName),
711
+ );
712
+ modelAttributes.push(buildModelConstraintAttribute('index', indexFieldNames, index.name));
713
+ }
714
+ }
715
+
716
+ if (mapName) {
717
+ modelAttributes.push(buildMapAttribute('model', mapName));
718
+ }
719
+
720
+ // Surface introspection advisory: tables without a primary key cannot serve
721
+ // as the right-hand side of a `findUnique`-style query downstream, so the
722
+ // user should add an `@id`. This warning is part of the emitted SQL output
723
+ // and is asserted byte-for-byte, so keep the exact wording.
724
+ const comment = table.primaryKey
725
+ ? undefined
726
+ : '// WARNING: This table has no primary key in the database';
727
+
728
+ return {
729
+ kind: 'model',
730
+ name: modelName,
731
+ fields,
732
+ attributes: modelAttributes,
733
+ span: SYNTHETIC_SPAN,
734
+ ...(comment !== undefined ? { comment } : {}),
735
+ };
736
+ }
737
+
738
+ function buildScalarField(
739
+ column: SqlColumnIR,
740
+ table: SqlTableIR,
741
+ typeMap: PslTypeMap,
742
+ enumNameMap: ReadonlyMap<string, string>,
743
+ fieldNameMap: TableColumnFieldNameMap | undefined,
744
+ namedTypes: NamedTypeRegistry,
745
+ defaultMapping: DefaultMappingOptions | undefined,
746
+ rawDefaultParser: PslPrinterOptions['parseRawDefault'],
747
+ pkColumns: ReadonlySet<string>,
748
+ isSinglePk: boolean,
749
+ singlePkConstraintName: string | undefined,
750
+ uniqueColumns: ReadonlyMap<string, string | undefined>,
751
+ ): PslField {
752
+ const resolvedField = fieldNameMap?.get(column.name);
753
+ const fieldName = resolvedField?.fieldName ?? toFieldName(column.name).name;
754
+ const fieldMap = resolvedField?.fieldMap;
755
+
756
+ const resolution = typeMap.resolve(column.nativeType, table.annotations);
757
+
758
+ if ('unsupported' in resolution) {
759
+ const attrs: PslFieldAttribute[] = [];
760
+ if (fieldMap !== undefined) {
761
+ attrs.push(buildMapAttribute('field', fieldMap));
762
+ }
763
+ return {
764
+ kind: 'field',
765
+ name: fieldName,
766
+ typeName: `Unsupported("${escapePslString(resolution.nativeType)}")`,
767
+ optional: column.nullable,
768
+ list: column.many === true,
769
+ attributes: attrs,
770
+ span: SYNTHETIC_SPAN,
771
+ };
772
+ }
773
+
774
+ // An enum-typed column emits the `pg.enum(<Name>)` type-constructor call —
775
+ // the Phase-1 authoring form a `native_enum` ref field takes — not a bare
776
+ // name substitution. The printer renders `typeConstructor` when present and
777
+ // composes `?`/`[]` exactly like any other field type.
778
+ let typeName = resolution.pslType;
779
+ let typeConstructor: PslTypeConstructorCall | undefined;
780
+ const enumPslName = enumNameMap.get(column.nativeType);
781
+ if (enumPslName) {
782
+ typeName = enumPslName;
783
+ typeConstructor = {
784
+ kind: 'typeConstructor',
785
+ path: ['pg', 'enum'],
786
+ args: [positionalArg(enumPslName)],
787
+ span: SYNTHETIC_SPAN,
788
+ };
789
+ }
790
+ if (resolution.nativeTypeAttribute && !enumPslName) {
791
+ typeName = resolveNamedTypeName(namedTypes, resolution);
792
+ }
793
+
794
+ const attributes: PslFieldAttribute[] = [];
795
+ const isId = isSinglePk && pkColumns.has(column.name);
796
+ if (isId) {
797
+ attributes.push(buildSimpleConstraintFieldAttribute('id', singlePkConstraintName));
798
+ }
799
+
800
+ if (column.default !== undefined) {
801
+ const parsed = parseColumnDefault(column.default, column.nativeType, rawDefaultParser);
802
+ if (parsed) {
803
+ const result = mapDefault(parsed, defaultMapping);
804
+ if ('attribute' in result) {
805
+ attributes.push(parseDefaultAttributeString(result.attribute));
806
+ }
807
+ // 'comment' fallback (unrecognized raw default) is dropped — the
808
+ // M1 legacy path emitted a `// Raw default: ...` line above the field via
809
+ // `PrinterField.comment`. M2 drops this since it would require comment
810
+ // nodes in the AST.
811
+ }
812
+ }
813
+
814
+ if (uniqueColumns.has(column.name) && !isId) {
815
+ const uniqueConstraintName = uniqueColumns.get(column.name);
816
+ attributes.push(buildSimpleConstraintFieldAttribute('unique', uniqueConstraintName));
817
+ }
818
+
819
+ if (fieldMap !== undefined) {
820
+ attributes.push(buildMapAttribute('field', fieldMap));
821
+ }
822
+
823
+ return {
824
+ kind: 'field',
825
+ name: fieldName,
826
+ typeName,
827
+ ...ifDefined('typeConstructor', typeConstructor),
828
+ optional: column.nullable,
829
+ list: column.many === true,
830
+ attributes,
831
+ span: SYNTHETIC_SPAN,
832
+ };
833
+ }
834
+
835
+ function buildRelationField(
836
+ rel: RelationField,
837
+ hostTableName: string,
838
+ fieldNamesByTable: ReadonlyMap<string, TableColumnFieldNameMap>,
839
+ usedFieldNames: Set<string>,
840
+ ): PslField {
841
+ const fieldName = createUniqueFieldName(rel.fieldName, usedFieldNames);
842
+ usedFieldNames.add(fieldName);
843
+
844
+ const args: PslAttributeArgument[] = [];
845
+
846
+ if (rel.fields && rel.references) {
847
+ if (rel.relationName) {
848
+ args.push(namedArg('name', `"${escapePslString(rel.relationName)}"`));
849
+ }
850
+ args.push(
851
+ namedArg(
852
+ 'fields',
853
+ `[${rel.fields
854
+ .map((columnName) => resolveColumnFieldName(fieldNamesByTable, hostTableName, columnName))
855
+ .join(', ')}]`,
856
+ ),
857
+ );
858
+ args.push(
859
+ namedArg(
860
+ 'references',
861
+ `[${rel.references
862
+ .map((columnName) =>
863
+ resolveColumnFieldName(fieldNamesByTable, rel.referencedTableName ?? '', columnName),
864
+ )
865
+ .join(', ')}]`,
866
+ ),
867
+ );
868
+ if (rel.onDelete) {
869
+ args.push(namedArg('onDelete', rel.onDelete));
870
+ }
871
+ if (rel.onUpdate) {
872
+ args.push(namedArg('onUpdate', rel.onUpdate));
873
+ }
874
+ if (rel.fkName) {
875
+ args.push(namedArg('map', `"${escapePslString(rel.fkName)}"`));
876
+ }
877
+ } else if (rel.relationName) {
878
+ args.push(namedArg('name', `"${escapePslString(rel.relationName)}"`));
879
+ }
880
+
881
+ const attrs: PslFieldAttribute[] =
882
+ args.length > 0 ? [buildAttribute('field', 'relation', args)] : [];
883
+
884
+ return {
885
+ kind: 'field',
886
+ name: fieldName,
887
+ typeName: rel.typeName,
888
+ ...ifDefined('typeNamespaceId', rel.typeNamespaceId),
889
+ ...ifDefined('typeContractSpaceId', rel.typeContractSpaceId),
890
+ optional: rel.optional,
891
+ list: rel.list,
892
+ attributes: attrs,
893
+ span: SYNTHETIC_SPAN,
894
+ };
895
+ }
896
+
897
+ function buildModelConstraintAttribute(
898
+ name: 'id' | 'unique' | 'index',
899
+ fields: readonly string[],
900
+ constraintName?: string,
901
+ ): PslModelAttribute {
902
+ const args: PslAttributeArgument[] = [positionalArg(`[${fields.join(', ')}]`)];
903
+ if (constraintName !== undefined) {
904
+ args.push(namedArg('map', `"${escapePslString(constraintName)}"`));
905
+ }
906
+ return buildAttribute('model', name, args);
907
+ }
908
+
909
+ function buildSimpleConstraintFieldAttribute(
910
+ name: 'id' | 'unique',
911
+ constraintName: string | undefined,
912
+ ): PslFieldAttribute {
913
+ if (constraintName === undefined) {
914
+ return buildAttribute('field', name, []);
915
+ }
916
+ return buildAttribute('field', name, [namedArg('map', `"${escapePslString(constraintName)}"`)]);
917
+ }
918
+
919
+ function parseDefaultAttributeString(attributeText: string): PslFieldAttribute {
920
+ // Strip leading "@default(" and trailing ")" — `mapDefault` always returns one
921
+ // top-level positional expression.
922
+ const inner = attributeText.replace(/^@default\(/, '').replace(/\)$/, '');
923
+ return buildAttribute('field', 'default', [positionalArg(inner)]);
924
+ }
925
+
926
+ function buildMapAttribute(target: 'model' | 'field' | 'enum', mapName: string): PslAttribute {
927
+ return buildAttribute(target, 'map', [positionalArg(`"${escapePslString(mapName)}"`)]);
928
+ }
929
+
930
+ function buildAttribute(
931
+ target: PslAttribute['target'],
932
+ name: string,
933
+ args: readonly PslAttributeArgument[],
934
+ ): PslAttribute {
935
+ return {
936
+ kind: 'attribute',
937
+ target,
938
+ name,
939
+ args,
940
+ span: SYNTHETIC_SPAN,
941
+ };
942
+ }
943
+
944
+ function positionalArg(value: string): PslAttributeArgument {
945
+ return { kind: 'positional', value, span: SYNTHETIC_SPAN };
946
+ }
947
+
948
+ function namedArg(name: string, value: string): PslAttributeArgument {
949
+ return { kind: 'named', name, value, span: SYNTHETIC_SPAN };
950
+ }
951
+
952
+ function buildNamedTypeDeclaration(entry: NamedTypeRegistryEntry): PslNamedTypeDeclaration {
953
+ const attribute = buildAttribute(
954
+ 'namedType',
955
+ entry.nativeTypeAttribute.name,
956
+ (entry.nativeTypeAttribute.args ?? []).map(positionalArg),
957
+ );
958
+ return {
959
+ kind: 'namedType',
960
+ name: entry.name,
961
+ baseType: entry.baseType,
962
+ attributes: [attribute],
963
+ span: SYNTHETIC_SPAN,
964
+ };
965
+ }
966
+
967
+ function escapePslString(value: string): string {
968
+ return value
969
+ .replace(/\\/g, '\\\\')
970
+ .replace(/"/g, '\\"')
971
+ .replace(/\n/g, '\\n')
972
+ .replace(/\r/g, '\\r');
973
+ }
974
+
975
+ /**
976
+ * Resolves a `SqlColumnIR.default` value into a normalized {@link ColumnDefault}.
977
+ *
978
+ * `SqlSchemaIR` types the column default as `string` (a raw database default
979
+ * expression). Some legacy fixtures and tests still pass already-normalized
980
+ * `ColumnDefault` objects in the same slot, so we accept either shape
981
+ * defensively at runtime.
982
+ */
983
+ function parseColumnDefault(
984
+ value: unknown,
985
+ nativeType: string | undefined,
986
+ rawDefaultParser: PslPrinterOptions['parseRawDefault'],
987
+ ): ColumnDefault | undefined {
988
+ if (typeof value === 'string') {
989
+ return rawDefaultParser ? rawDefaultParser(value, nativeType) : undefined;
990
+ }
991
+ if (value !== null && typeof value === 'object' && 'kind' in (value as Record<string, unknown>)) {
992
+ return value as ColumnDefault;
993
+ }
994
+ return undefined;
995
+ }
996
+
997
+ function buildFieldNamesByTable(
998
+ tables: Record<string, SqlTableIR>,
999
+ ): ReadonlyMap<string, TableColumnFieldNameMap> {
1000
+ const fieldNamesByTable = new Map<string, TableColumnFieldNameMap>();
1001
+
1002
+ for (const table of Object.values(tables)) {
1003
+ const columns = Object.values(table.columns).map((column, index) => {
1004
+ const { name, map } = toFieldName(column.name);
1005
+ return {
1006
+ columnName: column.name,
1007
+ desiredFieldName: name,
1008
+ fieldMap: map,
1009
+ index,
1010
+ };
1011
+ });
1012
+
1013
+ const assignmentOrder = [...columns].sort((left, right) => {
1014
+ const mapComparison =
1015
+ Number(left.fieldMap !== undefined) - Number(right.fieldMap !== undefined);
1016
+ if (mapComparison !== 0) {
1017
+ return mapComparison;
1018
+ }
1019
+ return left.index - right.index;
1020
+ });
1021
+
1022
+ const usedFieldNames = new Set<string>();
1023
+ const tableFieldNames = new Map<string, ResolvedColumnFieldName>();
1024
+
1025
+ for (const column of assignmentOrder) {
1026
+ const fieldName = createUniqueFieldName(column.desiredFieldName, usedFieldNames);
1027
+ usedFieldNames.add(fieldName);
1028
+ tableFieldNames.set(column.columnName, {
1029
+ fieldName,
1030
+ fieldMap: column.fieldMap,
1031
+ });
1032
+ }
1033
+
1034
+ fieldNamesByTable.set(table.name, tableFieldNames);
1035
+ }
1036
+
1037
+ return fieldNamesByTable;
1038
+ }
1039
+
1040
+ function resolveColumnFieldName(
1041
+ fieldNamesByTable: ReadonlyMap<string, TableColumnFieldNameMap>,
1042
+ tableName: string,
1043
+ columnName: string,
1044
+ ): string {
1045
+ return (
1046
+ fieldNamesByTable.get(tableName)?.get(columnName)?.fieldName ?? toFieldName(columnName).name
1047
+ );
1048
+ }
1049
+
1050
+ function createUniqueFieldName(desiredName: string, usedFieldNames: ReadonlySet<string>): string {
1051
+ if (!usedFieldNames.has(desiredName)) {
1052
+ return desiredName;
1053
+ }
1054
+
1055
+ let counter = 2;
1056
+ while (usedFieldNames.has(`${desiredName}${counter}`)) {
1057
+ counter++;
1058
+ }
1059
+ return `${desiredName}${counter}`;
1060
+ }
1061
+
1062
+ function buildTopLevelNameMap(
1063
+ sources: Iterable<string>,
1064
+ normalize: (source: string) => TopLevelNameResult,
1065
+ kind: 'model' | 'enum',
1066
+ sourceKind: 'table' | 'enum type',
1067
+ ): Map<string, TopLevelNameResult> {
1068
+ const results = new Map<string, TopLevelNameResult>();
1069
+ const normalizedToSources = new Map<string, string[]>();
1070
+
1071
+ for (const source of sources) {
1072
+ const normalized = normalize(source);
1073
+ results.set(source, normalized);
1074
+ normalizedToSources.set(normalized.name, [
1075
+ ...(normalizedToSources.get(normalized.name) ?? []),
1076
+ source,
1077
+ ]);
1078
+ }
1079
+
1080
+ const duplicates = [...normalizedToSources.entries()].filter(
1081
+ ([, conflictingSources]) => conflictingSources.length > 1,
1082
+ );
1083
+ if (duplicates.length > 0) {
1084
+ const details = duplicates.map(
1085
+ ([normalizedName, conflictingSources]) =>
1086
+ `- ${kind} "${normalizedName}" from ${sourceKind}s ${conflictingSources
1087
+ .map((source) => `"${source}"`)
1088
+ .join(', ')}`,
1089
+ );
1090
+ throw new Error(`PSL ${kind} name collisions detected:\n${details.join('\n')}`);
1091
+ }
1092
+
1093
+ return results;
1094
+ }
1095
+
1096
+ function createReservedNamedTypeNames(
1097
+ modelNames: ReadonlyMap<string, TopLevelNameResult>,
1098
+ enumNameMap: ReadonlyMap<string, string>,
1099
+ ): Set<string> {
1100
+ const reservedNames = new Set<string>(PSL_SCALAR_TYPE_NAMES);
1101
+
1102
+ for (const result of modelNames.values()) {
1103
+ reservedNames.add(result.name);
1104
+ }
1105
+ for (const enumPslName of enumNameMap.values()) {
1106
+ reservedNames.add(enumPslName);
1107
+ }
1108
+
1109
+ return reservedNames;
1110
+ }
1111
+
1112
+ function seedNamedTypeRegistry(
1113
+ schemaIR: SqlSchemaIR,
1114
+ typeMap: PslTypeMap,
1115
+ enumNameMap: ReadonlyMap<string, string>,
1116
+ reservedNames: ReadonlySet<string>,
1117
+ ): NamedTypeRegistry {
1118
+ type Seed = {
1119
+ readonly baseType: string;
1120
+ readonly desiredName: string;
1121
+ readonly nativeTypeAttribute: PslNativeTypeAttribute;
1122
+ };
1123
+
1124
+ const seeds = new Map<string, Seed>();
1125
+
1126
+ for (const tableName of Object.keys(schemaIR.tables).sort()) {
1127
+ const table = schemaIR.tables[tableName];
1128
+ if (!table) {
1129
+ continue;
1130
+ }
1131
+
1132
+ for (const columnName of Object.keys(table.columns).sort()) {
1133
+ const column = table.columns[columnName];
1134
+ if (!column) {
1135
+ continue;
1136
+ }
1137
+
1138
+ const resolution = typeMap.resolve(column.nativeType, table.annotations);
1139
+ if (
1140
+ 'unsupported' in resolution ||
1141
+ enumNameMap.has(column.nativeType) ||
1142
+ !resolution.nativeTypeAttribute
1143
+ ) {
1144
+ continue;
1145
+ }
1146
+
1147
+ const signatureKey = createNamedTypeSignatureKey(resolution);
1148
+ if (!seeds.has(signatureKey)) {
1149
+ seeds.set(signatureKey, {
1150
+ baseType: resolution.pslType,
1151
+ desiredName: toNamedTypeName(column.name),
1152
+ nativeTypeAttribute: resolution.nativeTypeAttribute,
1153
+ });
1154
+ }
1155
+ }
1156
+ }
1157
+
1158
+ const registry: NamedTypeRegistry = {
1159
+ entriesByKey: new Map<string, NamedTypeRegistryEntry>(),
1160
+ usedNames: new Set<string>(reservedNames),
1161
+ };
1162
+
1163
+ const sortedSeeds = [...seeds.entries()].sort((left, right) => {
1164
+ const desiredNameComparison = left[1].desiredName.localeCompare(right[1].desiredName);
1165
+ if (desiredNameComparison !== 0) {
1166
+ return desiredNameComparison;
1167
+ }
1168
+ return left[0].localeCompare(right[0]);
1169
+ });
1170
+
1171
+ for (const [signatureKey, seed] of sortedSeeds) {
1172
+ const name = createUniqueFieldName(seed.desiredName, registry.usedNames);
1173
+ registry.entriesByKey.set(signatureKey, {
1174
+ name,
1175
+ baseType: seed.baseType,
1176
+ nativeTypeAttribute: seed.nativeTypeAttribute,
1177
+ });
1178
+ registry.usedNames.add(name);
1179
+ }
1180
+
1181
+ return registry;
1182
+ }
1183
+
1184
+ function resolveNamedTypeName(
1185
+ registry: NamedTypeRegistry,
1186
+ resolution: {
1187
+ readonly pslType: string;
1188
+ readonly nativeType: string;
1189
+ readonly typeParams?: Record<string, unknown>;
1190
+ readonly nativeTypeAttribute?: PslNativeTypeAttribute;
1191
+ },
1192
+ ): string {
1193
+ const key = createNamedTypeSignatureKey(resolution);
1194
+ const existing = registry.entriesByKey.get(key);
1195
+ if (existing) {
1196
+ return existing.name;
1197
+ }
1198
+
1199
+ throw new Error(`Named type registry was not seeded for native type "${resolution.nativeType}"`);
1200
+ }
1201
+
1202
+ function createNamedTypeSignatureKey(resolution: {
1203
+ readonly pslType: string;
1204
+ readonly nativeType: string;
1205
+ readonly typeParams?: Record<string, unknown>;
1206
+ readonly nativeTypeAttribute?: PslNativeTypeAttribute;
1207
+ }): string {
1208
+ return JSON.stringify({
1209
+ baseType: resolution.pslType,
1210
+ nativeTypeAttribute: resolution.nativeTypeAttribute
1211
+ ? {
1212
+ name: resolution.nativeTypeAttribute.name,
1213
+ args: resolution.nativeTypeAttribute.args ?? null,
1214
+ }
1215
+ : null,
1216
+ });
1217
+ }
1218
+
1219
+ function topologicalSort(
1220
+ models: PslModel[],
1221
+ tables: Record<string, SqlTableIR>,
1222
+ modelNameMap: ReadonlyMap<string, string>,
1223
+ ): PslModel[] {
1224
+ const modelByName = new Map<string, PslModel>();
1225
+ for (const model of models) {
1226
+ modelByName.set(model.name, model);
1227
+ }
1228
+
1229
+ const deps = new Map<string, Set<string>>();
1230
+ const tableToModel = new Map<string, string>();
1231
+ for (const tableName of Object.keys(tables)) {
1232
+ const modelName = modelNameMap.get(tableName) as string;
1233
+ tableToModel.set(tableName, modelName);
1234
+ deps.set(modelName, new Set());
1235
+ }
1236
+
1237
+ for (const [tableName, table] of Object.entries(tables)) {
1238
+ const modelName = tableToModel.get(tableName) as string;
1239
+ for (const fk of table.foreignKeys) {
1240
+ const refModelName = tableToModel.get(fk.referencedTable);
1241
+ if (refModelName && refModelName !== modelName) {
1242
+ (deps.get(modelName) as Set<string>).add(refModelName);
1243
+ }
1244
+ }
1245
+ }
1246
+
1247
+ const result: PslModel[] = [];
1248
+ const visited = new Set<string>();
1249
+ const visiting = new Set<string>();
1250
+
1251
+ const sortedNames = [...deps.keys()].sort();
1252
+
1253
+ function visit(name: string): void {
1254
+ if (visited.has(name)) return;
1255
+ if (visiting.has(name)) return;
1256
+ visiting.add(name);
1257
+
1258
+ const sortedDeps = [...(deps.get(name) as Set<string>)].sort();
1259
+ for (const dep of sortedDeps) {
1260
+ visit(dep);
1261
+ }
1262
+
1263
+ visiting.delete(name);
1264
+ visited.add(name);
1265
+ result.push(modelByName.get(name) as PslModel);
1266
+ }
1267
+
1268
+ for (const name of sortedNames) {
1269
+ visit(name);
1270
+ }
1271
+
1272
+ return result;
1273
+ }