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

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