sf-plugin-data 0.1.0 → 0.2.0

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 (269) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +572 -240
  3. package/docs/artifact-format.md +527 -633
  4. package/docs/capabilities.md +1159 -168
  5. package/docs/git-workflow.md +135 -12
  6. package/docs/handover.md +7826 -12
  7. package/lib/api.d.ts +7 -0
  8. package/lib/api.js +7 -0
  9. package/lib/artifacts/code-fields.d.ts +49 -0
  10. package/lib/artifacts/code-fields.js +142 -0
  11. package/lib/artifacts/data-graph-document.d.ts +29 -0
  12. package/lib/artifacts/data-graph-document.js +52 -0
  13. package/lib/artifacts/data-space-field.d.ts +65 -0
  14. package/lib/artifacts/data-space-field.js +98 -0
  15. package/lib/artifacts/data-stream-document.d.ts +264 -0
  16. package/lib/artifacts/data-stream-document.js +680 -0
  17. package/lib/artifacts/data-transform-document.d.ts +152 -0
  18. package/lib/artifacts/data-transform-document.js +560 -0
  19. package/lib/artifacts/dependency-selection.d.ts +51 -0
  20. package/lib/artifacts/dependency-selection.js +154 -0
  21. package/lib/artifacts/dlo-document.d.ts +93 -0
  22. package/lib/artifacts/dlo-document.js +253 -0
  23. package/lib/artifacts/enum-case.d.ts +39 -0
  24. package/lib/artifacts/enum-case.js +67 -0
  25. package/lib/artifacts/git-deploy-selection.d.ts +68 -0
  26. package/lib/artifacts/git-deploy-selection.js +474 -0
  27. package/lib/artifacts/identity-resolution-document.d.ts +133 -0
  28. package/lib/artifacts/identity-resolution-document.js +625 -0
  29. package/lib/artifacts/mapping-document.d.ts +1 -0
  30. package/lib/artifacts/mapping-document.js +1 -0
  31. package/lib/artifacts/native-calculated-insight-document.d.ts +142 -0
  32. package/lib/artifacts/native-calculated-insight-document.js +321 -0
  33. package/lib/artifacts/native-data-graph-document.d.ts +124 -0
  34. package/lib/artifacts/native-data-graph-document.js +780 -0
  35. package/lib/artifacts/native-dmo-document.d.ts +151 -0
  36. package/lib/artifacts/native-dmo-document.js +313 -0
  37. package/lib/artifacts/native-mapping-document.d.ts +67 -0
  38. package/lib/artifacts/native-mapping-document.js +187 -0
  39. package/lib/artifacts/native-relationship-document.d.ts +76 -0
  40. package/lib/artifacts/native-relationship-document.js +232 -0
  41. package/lib/artifacts/path-selector.d.ts +55 -0
  42. package/lib/artifacts/path-selector.js +167 -0
  43. package/lib/artifacts/read-deploy-input.d.ts +222 -6
  44. package/lib/artifacts/read-deploy-input.js +1213 -53
  45. package/lib/artifacts/segment-document.d.ts +183 -0
  46. package/lib/artifacts/segment-document.js +570 -0
  47. package/lib/artifacts/verbatim-document.d.ts +203 -0
  48. package/lib/artifacts/verbatim-document.js +339 -0
  49. package/lib/artifacts/write-data-graph.d.ts +17 -0
  50. package/lib/artifacts/write-data-graph.js +162 -0
  51. package/lib/artifacts/write-data-stream.d.ts +11 -0
  52. package/lib/artifacts/write-data-stream.js +175 -0
  53. package/lib/artifacts/write-data-transform.d.ts +11 -0
  54. package/lib/artifacts/write-data-transform.js +180 -0
  55. package/lib/artifacts/write-dlo.d.ts +11 -0
  56. package/lib/artifacts/write-dlo.js +158 -0
  57. package/lib/artifacts/write-identity-resolution.d.ts +18 -0
  58. package/lib/artifacts/write-identity-resolution.js +165 -0
  59. package/lib/artifacts/write-mapping-definition.d.ts +17 -0
  60. package/lib/artifacts/write-mapping-definition.js +127 -0
  61. package/lib/artifacts/write-member-export.d.ts +88 -0
  62. package/lib/artifacts/write-member-export.js +199 -0
  63. package/lib/artifacts/write-native-calculated-insight.d.ts +21 -0
  64. package/lib/artifacts/write-native-calculated-insight.js +176 -0
  65. package/lib/artifacts/write-native-dmo.d.ts +11 -0
  66. package/lib/artifacts/write-native-dmo.js +158 -0
  67. package/lib/artifacts/write-native-mapping.d.ts +11 -0
  68. package/lib/artifacts/write-native-mapping.js +157 -0
  69. package/lib/artifacts/write-native-relationship.d.ts +11 -0
  70. package/lib/artifacts/write-native-relationship.js +157 -0
  71. package/lib/artifacts/write-segment.d.ts +26 -0
  72. package/lib/artifacts/write-segment.js +212 -0
  73. package/lib/commands/data360/delete.d.ts +280 -0
  74. package/lib/commands/data360/delete.js +2297 -0
  75. package/lib/commands/data360/deploy.d.ts +234 -15
  76. package/lib/commands/data360/deploy.js +2292 -100
  77. package/lib/commands/data360/publish.d.ts +93 -0
  78. package/lib/commands/data360/publish.js +292 -0
  79. package/lib/commands/data360/retrieve.d.ts +260 -13
  80. package/lib/commands/data360/retrieve.js +1880 -85
  81. package/lib/commands/data360/segment/members/export.d.ts +101 -0
  82. package/lib/commands/data360/segment/members/export.js +318 -0
  83. package/lib/errors/codes/calculated-insight.d.ts +2 -0
  84. package/lib/errors/codes/calculated-insight.js +25 -0
  85. package/lib/errors/codes/data-graph.d.ts +2 -0
  86. package/lib/errors/codes/data-graph.js +22 -0
  87. package/lib/errors/codes/data-stream.d.ts +2 -0
  88. package/lib/errors/codes/data-stream.js +70 -0
  89. package/lib/errors/codes/data-transform.d.ts +2 -0
  90. package/lib/errors/codes/data-transform.js +35 -0
  91. package/lib/errors/codes/dependency.d.ts +2 -0
  92. package/lib/errors/codes/dependency.js +11 -0
  93. package/lib/errors/codes/dlo.d.ts +2 -0
  94. package/lib/errors/codes/dlo.js +31 -0
  95. package/lib/errors/codes/dmo.d.ts +2 -0
  96. package/lib/errors/codes/dmo.js +28 -0
  97. package/lib/errors/codes/general.d.ts +2 -0
  98. package/lib/errors/codes/general.js +57 -0
  99. package/lib/errors/codes/identity-resolution.d.ts +2 -0
  100. package/lib/errors/codes/identity-resolution.js +24 -0
  101. package/lib/errors/codes/mapping.d.ts +2 -0
  102. package/lib/errors/codes/mapping.js +42 -0
  103. package/lib/errors/codes/relationship.d.ts +2 -0
  104. package/lib/errors/codes/relationship.js +21 -0
  105. package/lib/errors/codes/segment.d.ts +2 -0
  106. package/lib/errors/codes/segment.js +49 -0
  107. package/lib/errors/registry.d.ts +60 -0
  108. package/lib/errors/registry.js +123 -0
  109. package/lib/plugin.d.ts +1 -0
  110. package/lib/plugin.js +3 -1
  111. package/lib/services/acquire-retrieve-selection.d.ts +43 -0
  112. package/lib/services/acquire-retrieve-selection.js +145 -0
  113. package/lib/services/bind-identity-resolution-dependencies.d.ts +53 -0
  114. package/lib/services/bind-identity-resolution-dependencies.js +238 -0
  115. package/lib/services/bind-segment-dependencies.d.ts +49 -0
  116. package/lib/services/bind-segment-dependencies.js +115 -0
  117. package/lib/services/bounded-reads.d.ts +17 -0
  118. package/lib/services/bounded-reads.js +42 -0
  119. package/lib/services/calculated-insight-sql-checks.d.ts +33 -0
  120. package/lib/services/calculated-insight-sql-checks.js +193 -0
  121. package/lib/services/command-dlo.d.ts +48 -0
  122. package/lib/services/command-dlo.js +103 -0
  123. package/lib/services/command-native-data-graph.d.ts +54 -0
  124. package/lib/services/command-native-data-graph.js +485 -0
  125. package/lib/services/command-native-data-stream.d.ts +104 -0
  126. package/lib/services/command-native-data-stream.js +257 -0
  127. package/lib/services/command-native-dmo.d.ts +124 -0
  128. package/lib/services/command-native-dmo.js +338 -0
  129. package/lib/services/command-native-mapping.d.ts +65 -0
  130. package/lib/services/command-native-mapping.js +129 -0
  131. package/lib/services/command-native-relationship.d.ts +46 -0
  132. package/lib/services/command-native-relationship.js +103 -0
  133. package/lib/services/cross-dataspace-deploy.d.ts +111 -0
  134. package/lib/services/cross-dataspace-deploy.js +493 -0
  135. package/lib/services/cross-dataspace-rename.d.ts +74 -0
  136. package/lib/services/cross-dataspace-rename.js +1314 -0
  137. package/lib/services/cross-dataspace-sql.d.ts +109 -0
  138. package/lib/services/cross-dataspace-sql.js +1301 -0
  139. package/lib/services/cross-space-context.d.ts +23 -0
  140. package/lib/services/cross-space-context.js +36 -0
  141. package/lib/services/crud-plan.d.ts +137 -0
  142. package/lib/services/crud-plan.js +408 -0
  143. package/lib/services/data-space-check.d.ts +89 -0
  144. package/lib/services/data-space-check.js +162 -0
  145. package/lib/services/data-space-prefix.d.ts +77 -0
  146. package/lib/services/data-space-prefix.js +127 -0
  147. package/lib/services/data-transform-space.d.ts +31 -0
  148. package/lib/services/data-transform-space.js +79 -0
  149. package/lib/services/delete-calculated-insight.d.ts +44 -0
  150. package/lib/services/delete-calculated-insight.js +101 -0
  151. package/lib/services/delete-data-transform.d.ts +52 -0
  152. package/lib/services/delete-data-transform.js +222 -0
  153. package/lib/services/delete-dmo-field.d.ts +211 -0
  154. package/lib/services/delete-dmo-field.js +472 -0
  155. package/lib/services/delete-identity-resolution.d.ts +43 -0
  156. package/lib/services/delete-identity-resolution.js +295 -0
  157. package/lib/services/delete-segment.d.ts +42 -0
  158. package/lib/services/delete-segment.js +248 -0
  159. package/lib/services/deploy-result.d.ts +54 -0
  160. package/lib/services/deploy-result.js +60 -0
  161. package/lib/services/escaped-copy.d.ts +23 -0
  162. package/lib/services/escaped-copy.js +88 -0
  163. package/lib/services/execute-calculated-insight-deploy.d.ts +42 -0
  164. package/lib/services/execute-calculated-insight-deploy.js +96 -0
  165. package/lib/services/execute-data-transform-deploy.d.ts +56 -0
  166. package/lib/services/execute-data-transform-deploy.js +168 -0
  167. package/lib/services/execute-native-identity-resolution-deploy.d.ts +48 -0
  168. package/lib/services/execute-native-identity-resolution-deploy.js +360 -0
  169. package/lib/services/execute-segment-deploy.d.ts +45 -0
  170. package/lib/services/execute-segment-deploy.js +393 -0
  171. package/lib/services/local-file-removal.d.ts +36 -0
  172. package/lib/services/local-file-removal.js +103 -0
  173. package/lib/services/native-calculated-insight.d.ts +87 -0
  174. package/lib/services/native-calculated-insight.js +164 -0
  175. package/lib/services/native-crm-data-stream.d.ts +91 -0
  176. package/lib/services/native-crm-data-stream.js +272 -0
  177. package/lib/services/native-data-graph-context.d.ts +12 -0
  178. package/lib/services/native-data-graph-context.js +139 -0
  179. package/lib/services/native-data-graph-crd.d.ts +261 -0
  180. package/lib/services/native-data-graph-crd.js +866 -0
  181. package/lib/services/native-data-stream.d.ts +329 -0
  182. package/lib/services/native-data-stream.js +1830 -0
  183. package/lib/services/native-dlo.d.ts +163 -0
  184. package/lib/services/native-dlo.js +402 -0
  185. package/lib/services/native-dmo.d.ts +191 -0
  186. package/lib/services/native-dmo.js +614 -0
  187. package/lib/services/native-mapping.d.ts +255 -0
  188. package/lib/services/native-mapping.js +1226 -0
  189. package/lib/services/native-relationship.d.ts +132 -0
  190. package/lib/services/native-relationship.js +512 -0
  191. package/lib/services/operation-diagnostic.d.ts +83 -0
  192. package/lib/services/operation-diagnostic.js +272 -0
  193. package/lib/services/preflight-calculated-insight-deploy.d.ts +58 -0
  194. package/lib/services/preflight-calculated-insight-deploy.js +95 -0
  195. package/lib/services/preflight-data-transform-deploy.d.ts +33 -0
  196. package/lib/services/preflight-data-transform-deploy.js +104 -0
  197. package/lib/services/preflight-identity-resolution-deploy.d.ts +107 -0
  198. package/lib/services/preflight-identity-resolution-deploy.js +281 -0
  199. package/lib/services/preflight-segment-deploy.d.ts +31 -0
  200. package/lib/services/preflight-segment-deploy.js +109 -0
  201. package/lib/services/publish-calculated-insight.d.ts +40 -0
  202. package/lib/services/publish-calculated-insight.js +95 -0
  203. package/lib/services/publish-segment.d.ts +65 -0
  204. package/lib/services/publish-segment.js +194 -0
  205. package/lib/services/readback-pace.d.ts +16 -0
  206. package/lib/services/readback-pace.js +23 -0
  207. package/lib/services/retrieve-data-transform.d.ts +26 -0
  208. package/lib/services/retrieve-data-transform.js +65 -0
  209. package/lib/services/retrieve-identity-resolution.d.ts +40 -0
  210. package/lib/services/retrieve-identity-resolution.js +87 -0
  211. package/lib/services/retrieve-inventory.d.ts +32 -0
  212. package/lib/services/retrieve-inventory.js +151 -0
  213. package/lib/services/retrieve-segment.d.ts +120 -0
  214. package/lib/services/retrieve-segment.js +502 -0
  215. package/lib/services/segment-lookup.d.ts +46 -0
  216. package/lib/services/segment-lookup.js +108 -0
  217. package/lib/services/segment-members.d.ts +144 -0
  218. package/lib/services/segment-members.js +402 -0
  219. package/lib/services/select-native-retrieve.d.ts +60 -0
  220. package/lib/services/select-native-retrieve.js +226 -0
  221. package/lib/services/settle-calculated-insight.d.ts +22 -0
  222. package/lib/services/settle-calculated-insight.js +53 -0
  223. package/lib/services/sql-tokens.d.ts +58 -0
  224. package/lib/services/sql-tokens.js +147 -0
  225. package/lib/transport/api-version.d.ts +36 -0
  226. package/lib/transport/api-version.js +89 -0
  227. package/lib/transport/bound-ssot.d.ts +27 -0
  228. package/lib/transport/bound-ssot.js +116 -0
  229. package/lib/transport/calculated-insight-rest.d.ts +28 -0
  230. package/lib/transport/calculated-insight-rest.js +62 -0
  231. package/lib/transport/connect-client.d.ts +94 -32
  232. package/lib/transport/connect-client.js +318 -178
  233. package/lib/transport/connect-diagnostic.d.ts +89 -0
  234. package/lib/transport/connect-diagnostic.js +331 -0
  235. package/lib/transport/data-graph-rest.d.ts +27 -0
  236. package/lib/transport/data-graph-rest.js +76 -0
  237. package/lib/transport/data-stream-rest.d.ts +62 -0
  238. package/lib/transport/data-stream-rest.js +348 -0
  239. package/lib/transport/data-transform-rest.d.ts +25 -0
  240. package/lib/transport/data-transform-rest.js +100 -0
  241. package/lib/transport/dlo-native-rest.d.ts +22 -0
  242. package/lib/transport/dlo-native-rest.js +89 -0
  243. package/lib/transport/dlo-rest.d.ts +23 -0
  244. package/lib/transport/dlo-rest.js +135 -0
  245. package/lib/transport/dmo-native-rest.d.ts +18 -0
  246. package/lib/transport/dmo-native-rest.js +55 -0
  247. package/lib/transport/dmo-rest.d.ts +30 -0
  248. package/lib/transport/dmo-rest.js +163 -0
  249. package/lib/transport/mapping-rest.d.ts +63 -0
  250. package/lib/transport/mapping-rest.js +341 -0
  251. package/lib/transport/project-metadata.d.ts +36 -0
  252. package/lib/transport/project-metadata.js +118 -0
  253. package/lib/transport/relationship-rest.d.ts +43 -0
  254. package/lib/transport/relationship-rest.js +201 -0
  255. package/package.json +29 -6
  256. package/lib/artifacts/dmo-document.d.ts +0 -181
  257. package/lib/artifacts/dmo-document.js +0 -848
  258. package/lib/artifacts/dmo-update-delta.d.ts +0 -28
  259. package/lib/artifacts/dmo-update-delta.js +0 -86
  260. package/lib/artifacts/write-other-dmo.d.ts +0 -17
  261. package/lib/artifacts/write-other-dmo.js +0 -140
  262. package/lib/services/execute-dmo-create.d.ts +0 -24
  263. package/lib/services/execute-dmo-create.js +0 -118
  264. package/lib/services/execute-dmo-deploy.d.ts +0 -33
  265. package/lib/services/execute-dmo-deploy.js +0 -197
  266. package/lib/services/preflight-dmo-deploy.d.ts +0 -69
  267. package/lib/services/preflight-dmo-deploy.js +0 -161
  268. package/lib/services/retrieve-other-dmo.d.ts +0 -46
  269. package/lib/services/retrieve-other-dmo.js +0 -140
@@ -0,0 +1,1301 @@
1
+ import { isSqlTokenProblem, spellToken, tokenName, tokenizeSql } from './sql-tokens.js';
2
+ const clauseWords = new Set([
3
+ 'FROM',
4
+ 'WHERE',
5
+ 'GROUP',
6
+ 'HAVING',
7
+ 'QUALIFY',
8
+ 'WINDOW',
9
+ 'ORDER',
10
+ 'LIMIT',
11
+ 'OFFSET',
12
+ 'FETCH',
13
+ 'CLUSTER',
14
+ 'DISTRIBUTE',
15
+ 'SORT',
16
+ ]);
17
+ // The clauses in which a name equal to a select alias reads the alias.
18
+ const aliasClauseWords = new Set(['HAVING', 'QUALIFY', 'ORDER', 'CLUSTER', 'DISTRIBUTE', 'SORT']);
19
+ const setWords = new Set(['UNION', 'INTERSECT', 'EXCEPT', 'MINUS']);
20
+ const joinWords = new Set([
21
+ 'JOIN',
22
+ 'INNER',
23
+ 'LEFT',
24
+ 'RIGHT',
25
+ 'FULL',
26
+ 'OUTER',
27
+ 'CROSS',
28
+ 'NATURAL',
29
+ 'SEMI',
30
+ 'ANTI',
31
+ 'LATERAL',
32
+ ]);
33
+ // Words that end an expression but are never an alias.
34
+ export const reservedWords = new Set([
35
+ ...clauseWords,
36
+ ...setWords,
37
+ ...joinWords,
38
+ 'ALL',
39
+ 'AND',
40
+ 'AS',
41
+ 'ASC',
42
+ 'BETWEEN',
43
+ 'BY',
44
+ 'CASE',
45
+ 'DAY',
46
+ 'DESC',
47
+ 'DISTINCT',
48
+ 'ELSE',
49
+ 'END',
50
+ 'FALSE',
51
+ 'FIRST',
52
+ 'FOLLOWING',
53
+ 'HOUR',
54
+ 'IN',
55
+ 'INTERVAL',
56
+ 'IS',
57
+ 'LAST',
58
+ 'LIKE',
59
+ 'MINUTE',
60
+ 'MONTH',
61
+ 'NOT',
62
+ 'NULL',
63
+ 'NULLS',
64
+ 'ON',
65
+ 'OR',
66
+ 'OVER',
67
+ 'PARTITION',
68
+ 'PRECEDING',
69
+ 'RANGE',
70
+ 'ROW',
71
+ 'ROWS',
72
+ 'SECOND',
73
+ 'SELECT',
74
+ 'THEN',
75
+ 'TRUE',
76
+ 'UNBOUNDED',
77
+ 'USING',
78
+ 'VALUES',
79
+ 'WEEK',
80
+ 'WHEN',
81
+ 'WITH',
82
+ 'YEAR',
83
+ ]);
84
+ // A join word that is never a function name, so it starts a join also before a parenthesis.
85
+ const joinOnlyWords = new Set([
86
+ 'JOIN',
87
+ 'INNER',
88
+ 'OUTER',
89
+ 'CROSS',
90
+ 'NATURAL',
91
+ 'FULL',
92
+ 'SEMI',
93
+ 'ANTI',
94
+ ]);
95
+ // Words after which the next word is an operand, never a column alias (NULL, TRUE, FALSE and END
96
+ // end an operand, so a word after them can be an alias).
97
+ export const operatorWords = new Set([
98
+ 'ALL',
99
+ 'AND',
100
+ 'ANY',
101
+ 'AS',
102
+ 'BETWEEN',
103
+ 'BY',
104
+ 'CASE',
105
+ 'COLLATE',
106
+ 'DISTINCT',
107
+ 'DIV',
108
+ 'ELSE',
109
+ 'ESCAPE',
110
+ 'EXISTS',
111
+ 'ILIKE',
112
+ 'IN',
113
+ 'INTERVAL',
114
+ 'IS',
115
+ 'LIKE',
116
+ 'MOD',
117
+ 'NOT',
118
+ 'ON',
119
+ 'OR',
120
+ 'OVER',
121
+ 'REGEXP',
122
+ 'RLIKE',
123
+ 'SIMILAR',
124
+ 'SOME',
125
+ 'THEN',
126
+ 'TO',
127
+ 'WHEN',
128
+ 'XOR',
129
+ 'ZONE',
130
+ ]);
131
+ // An HTML character reference as Salesforce writes it into returned SQL.
132
+ const htmlEntity = /&(?:#\d+|#x[\da-f]+|quot|amp|lt|gt|apos);/iu;
133
+ // Spark and Data Cloud SQL read names without regard to case.
134
+ const fieldLike = /__c$/iu;
135
+ const objectLike = /__(?:dlm|cio|dll)$/iu;
136
+ /**
137
+ * Whether a name looks like a Data Cloud object or field name the rewrite must account for.
138
+ * @param {string} name Name.
139
+ * @returns {boolean} Name-like.
140
+ */
141
+ function nameLike(name) {
142
+ return fieldLike.test(name) || objectLike.test(name) || name.toLowerCase().includes('ssot__');
143
+ }
144
+ /**
145
+ * Combine what every table that may own a column answers: no owner, a refusal, one name, or a
146
+ * refusal when the owners would spell it differently.
147
+ * @param {FieldAnswer[]} answers Answers.
148
+ * @param {string} field Column name.
149
+ * @returns {FieldAnswer} Combined answer.
150
+ */
151
+ function agree(answers, field) {
152
+ const owners = answers.filter((answer) => answer.owns);
153
+ if (owners.length === 0)
154
+ return { owns: false };
155
+ const refusal = owners.find((answer) => 'reason' in answer);
156
+ if (refusal)
157
+ return refusal;
158
+ const named = owners.filter((answer) => 'name' in answer);
159
+ if (named.length === 0)
160
+ return { owns: true, skip: true };
161
+ const names = new Set(named.map((answer) => answer.name));
162
+ if (names.size > 1)
163
+ return {
164
+ owns: true,
165
+ reason: `${field} has no table name in front, and the tables that could own it spell it differently in the target data space (${[...names].join(', ')}); write the table or alias in front of it`,
166
+ };
167
+ return named.find((answer) => answer.rule !== undefined) ?? named[0];
168
+ }
169
+ /**
170
+ * The columns of a WITH block or subquery as a table answers them.
171
+ * @param {Columns} columns Its columns.
172
+ * @returns {(field: string) => FieldAnswer} Column lookup.
173
+ */
174
+ function derivedColumns(columns) {
175
+ return (field) => {
176
+ const named = columns.named.get(field.toLowerCase());
177
+ if (named)
178
+ return named;
179
+ if (columns.stars.length === 0)
180
+ return { owns: false };
181
+ return agree(columns.stars.map((source) => source.columns(field)), field);
182
+ };
183
+ }
184
+ /** One SQL text under analysis. */
185
+ class SqlAnalysis {
186
+ tokens;
187
+ namer;
188
+ sig;
189
+ match = new Map();
190
+ out = {
191
+ edits: new Map(),
192
+ unresolved: new Map(),
193
+ seen: new Set(),
194
+ userNames: new Set(),
195
+ follows: new Map(),
196
+ };
197
+ /** The columns the outermost query of each statement puts out. */
198
+ statements = [];
199
+ constructor(tokens, namer) {
200
+ this.tokens = tokens;
201
+ this.namer = namer;
202
+ this.sig = tokens.flatMap((token, index) => token.kind === 'space' || token.kind === 'comment' ? [] : [index]);
203
+ }
204
+ /**
205
+ * Run the analysis over the whole text.
206
+ * @returns {Collector | string} What was found, or why the text has no readable structure.
207
+ */
208
+ run() {
209
+ const open = [];
210
+ for (let p = 0; p < this.sig.length; p++) {
211
+ const text = this.tok(p).text;
212
+ if (this.tok(p).kind !== 'punct')
213
+ continue;
214
+ if (text === '(')
215
+ open.push(p);
216
+ else if (text === ')') {
217
+ const start = open.pop();
218
+ if (start === undefined)
219
+ return 'its parentheses do not match';
220
+ this.match.set(start, p);
221
+ }
222
+ }
223
+ if (open.length > 0)
224
+ return 'its parentheses do not match';
225
+ let start = 0;
226
+ for (let p = 0; p <= this.sig.length; p++)
227
+ if (p === this.sig.length || this.isPunct(p, ';')) {
228
+ if (p > start)
229
+ this.statements.push(this.query(start, p, undefined, []));
230
+ start = p + 1;
231
+ }
232
+ return this.out;
233
+ }
234
+ tok(p) {
235
+ return this.tokens[this.sig[p]];
236
+ }
237
+ upper(p, end) {
238
+ return p < end && this.tok(p).kind === 'word' ? this.tok(p).text.toUpperCase() : '';
239
+ }
240
+ isPunct(p, text, end = this.sig.length) {
241
+ return p < end && this.tok(p).kind === 'punct' && this.tok(p).text === text;
242
+ }
243
+ isName(p, end) {
244
+ return p < end && (this.tok(p).kind === 'word' || this.tok(p).kind === 'quoted');
245
+ }
246
+ nameAt(p) {
247
+ return tokenName(this.tok(p)) ?? '';
248
+ }
249
+ /**
250
+ * The position after a token, jumping over a parenthesis group.
251
+ * @param {number} p Position among the significant tokens.
252
+ * @returns {number} The next position.
253
+ */
254
+ skip(p) {
255
+ return this.isPunct(p, '(') ? this.match.get(p) + 1 : p + 1;
256
+ }
257
+ refuse(p, reason) {
258
+ const index = this.sig[p];
259
+ if (!this.out.unresolved.has(index))
260
+ this.out.unresolved.set(index, reason);
261
+ this.out.seen.add(index);
262
+ }
263
+ keep(p, userName = false) {
264
+ this.out.seen.add(this.sig[p]);
265
+ if (userName)
266
+ this.out.userNames.add(this.sig[p]);
267
+ }
268
+ edit(p, to) {
269
+ this.out.seen.add(this.sig[p]);
270
+ if (to.name !== this.nameAt(p))
271
+ this.out.edits.set(this.sig[p], { to: to.name, rule: to.rule });
272
+ }
273
+ /**
274
+ * Whether a parenthesis group holds a query.
275
+ * @param {number} p Position among the significant tokens.
276
+ * @returns {boolean} Whether it starts with SELECT or WITH.
277
+ */
278
+ holdsQuery(p) {
279
+ const inner = p + 1;
280
+ const end = this.match.get(p);
281
+ return ['SELECT', 'WITH'].includes(this.upper(inner, end));
282
+ }
283
+ /**
284
+ * A query: an optional WITH list, then select blocks joined by set operators.
285
+ * @param {number} from First position of the range.
286
+ * @param {number} to End of the range (exclusive).
287
+ * @param {Scope | undefined} outer The enclosing query block, if any.
288
+ * @param {readonly Cte[]} ctes The WITH blocks visible here.
289
+ * @returns {Columns} The columns of its first block.
290
+ */
291
+ query(from, to, outer, ctes) {
292
+ let p = from;
293
+ let visible = [...ctes];
294
+ if (this.upper(p, to) === 'WITH') {
295
+ p++;
296
+ const recursive = this.upper(p, to) === 'RECURSIVE';
297
+ if (recursive)
298
+ p++;
299
+ for (;;) {
300
+ if (!this.isName(p, to))
301
+ return this.expressionQuery(p, to, outer, visible);
302
+ const nameAt = p;
303
+ const name = this.nameAt(p);
304
+ this.keep(p, true);
305
+ p++;
306
+ let listed;
307
+ if (this.isPunct(p, '(', to)) {
308
+ listed = [];
309
+ const close = this.match.get(p);
310
+ for (let q = p + 1; q < close; q++)
311
+ if (this.isName(q, close)) {
312
+ listed.push(this.nameAt(q));
313
+ this.keep(q, true);
314
+ }
315
+ p = close + 1;
316
+ }
317
+ if (this.upper(p, to) !== 'AS')
318
+ return this.expressionQuery(nameAt, to, outer, visible);
319
+ p++;
320
+ while (['NOT', 'MATERIALIZED'].includes(this.upper(p, to)))
321
+ p++;
322
+ if (!this.isPunct(p, '(', to))
323
+ return this.expressionQuery(p, to, outer, visible);
324
+ const close = this.match.get(p);
325
+ let columns;
326
+ if (recursive) {
327
+ // Its own name inside its body: the columns of its first block, from a dry run.
328
+ const real = this.out;
329
+ this.out = {
330
+ edits: new Map(),
331
+ unresolved: new Map(),
332
+ seen: new Set(),
333
+ userNames: new Set(),
334
+ follows: new Map(),
335
+ };
336
+ const anchor = this.query(p + 1, close, outer, visible);
337
+ this.out = real;
338
+ columns = this.query(p + 1, close, outer, [
339
+ ...visible,
340
+ { name, columns: listed ? listedColumns(listed) : anchor },
341
+ ]);
342
+ }
343
+ else
344
+ columns = this.query(p + 1, close, outer, visible);
345
+ visible = [...visible, { name, columns: listed ? listedColumns(listed) : columns }];
346
+ p = close + 1;
347
+ if (this.isPunct(p, ',', to)) {
348
+ p++;
349
+ continue;
350
+ }
351
+ break;
352
+ }
353
+ }
354
+ return this.setOperations(p, to, outer, visible);
355
+ }
356
+ /**
357
+ * A range that does not read as a query: its names are checked as an expression.
358
+ * @param {number} from First position of the range.
359
+ * @param {number} to End of the range (exclusive).
360
+ * @param {Scope | undefined} outer The enclosing query block, if any.
361
+ * @param {readonly Cte[]} ctes The WITH blocks visible here.
362
+ * @returns {Columns} No known columns.
363
+ */
364
+ expressionQuery(from, to, outer, ctes) {
365
+ this.expression(from, to, outer ?? { sources: [], aliases: new Set() }, ctes);
366
+ return { named: new Map(), stars: [] };
367
+ }
368
+ setOperations(from, to, outer, ctes) {
369
+ const parts = [];
370
+ let start = from;
371
+ for (let p = from; p < to; p = this.skip(p))
372
+ if (setWords.has(this.upper(p, to))) {
373
+ parts.push([start, p]);
374
+ start = p + 1;
375
+ while (['ALL', 'DISTINCT'].includes(this.upper(start, to)))
376
+ start++;
377
+ }
378
+ parts.push([start, to]);
379
+ let first;
380
+ for (const [index, [begin, end]] of parts.entries()) {
381
+ let columns;
382
+ if (this.isPunct(begin, '(', end) && this.holdsQuery(begin)) {
383
+ const close = this.match.get(begin);
384
+ columns = this.query(begin + 1, close, outer, ctes);
385
+ if (close + 1 < end)
386
+ this.expression(close + 1, end, outer ?? { sources: [], aliases: new Set() }, ctes);
387
+ }
388
+ else if (this.upper(begin, end) === 'SELECT')
389
+ columns = this.selectBlock(begin, end, outer, ctes, index > 0 && index === parts.length - 1);
390
+ else
391
+ columns = this.expressionQuery(begin, end, outer, ctes);
392
+ if (first && (columns.orderUses || columns.plainOrderUses))
393
+ this.setOrderUses(first, columns.orderUses ?? new Map(), columns.plainOrderUses);
394
+ first ??= columns;
395
+ }
396
+ return first;
397
+ }
398
+ /**
399
+ * The ORDER BY (SORT BY, …) at the end of a set operation reads the columns the operation puts
400
+ * out, which its first branch names, not the aliases of the last branch it is written in. A use
401
+ * of a last-branch alias, or of any other name, follows the column of that name the first
402
+ * branch puts out (its alias, or its column), never a table of the last branch; a name the
403
+ * first branch does not put out is not placed.
404
+ * @param {Columns} first The columns of the first branch, changed in place.
405
+ * @param {ReadonlyMap<string, number[]>} uses Alias uses in the trailing clauses (token indices).
406
+ * @param {ReadonlyMap<string, number[]>} [plainUses] The other names in those clauses.
407
+ */
408
+ setOrderUses(first, uses, plainUses) {
409
+ const firstNames = new Map();
410
+ for (const entry of first.names ?? []) {
411
+ const name = (tokenName(this.tokens[entry.token]) ?? '').toLowerCase();
412
+ if (!firstNames.has(name))
413
+ firstNames.set(name, entry);
414
+ }
415
+ const firstAliases = new Set((first.names ?? [])
416
+ .filter((entry) => entry.aliased)
417
+ .map((entry) => (tokenName(this.tokens[entry.token]) ?? '').toLowerCase()));
418
+ for (const [name, indices] of plainUses ?? []) {
419
+ const output = firstNames.get(name);
420
+ for (const index of indices)
421
+ if (output?.aliased) {
422
+ this.out.userNames.add(index);
423
+ first.aliasUses ??= new Map();
424
+ first.aliasUses.set(name, [...(first.aliasUses.get(name) ?? []), index]);
425
+ }
426
+ else if (output)
427
+ this.out.follows.set(index, output.token);
428
+ else if (!this.out.unresolved.has(index))
429
+ this.out.unresolved.set(index, 'after a set operation (UNION, …) this clause reads the columns the first branch puts out, and the first branch puts out no column of this name, so its spelling cannot be placed: name a column the first branch puts out');
430
+ }
431
+ for (const [name, indices] of uses) {
432
+ if (firstAliases.has(name)) {
433
+ first.aliasUses ??= new Map();
434
+ first.aliasUses.set(name, [...(first.aliasUses.get(name) ?? []), ...indices]);
435
+ continue;
436
+ }
437
+ // A plain column of the first branch: the use is spelled like that column.
438
+ const output = firstNames.get(name);
439
+ for (const index of indices) {
440
+ this.out.userNames.delete(index);
441
+ if (output)
442
+ this.out.follows.set(index, output.token);
443
+ else if (!this.out.unresolved.has(index))
444
+ this.out.unresolved.set(index, 'after a set operation (UNION, …) this clause reads the columns the first branch puts out, and the first branch puts out no column of this name (it is an alias of a later branch only), so its spelling cannot be placed: give the first branch the same alias');
445
+ }
446
+ }
447
+ }
448
+ selectBlock(from, to, outer, ctes, trailing = false) {
449
+ const clauses = [];
450
+ for (let p = from + 1; p < to; p = this.skip(p)) {
451
+ const word = this.upper(p, to);
452
+ if (clauseWords.has(word))
453
+ clauses.push({ word, at: p });
454
+ }
455
+ const endOf = (index) => clauses[index + 1]?.at ?? to;
456
+ const scope = { sources: [], aliases: new Set(), ...(outer ? { parent: outer } : {}) };
457
+ const deferred = [];
458
+ const fromIndex = clauses.findIndex((clause) => clause.word === 'FROM');
459
+ if (fromIndex !== -1)
460
+ this.fromClause(clauses[fromIndex].at + 1, endOf(fromIndex), outer, ctes, scope, deferred);
461
+ for (const run of deferred)
462
+ run();
463
+ const columns = this.selectList(from + 1, clauses[0]?.at ?? to, scope, ctes);
464
+ // Spark reads a name equal to a select alias as that alias only in the clauses above the
465
+ // projection (ORDER BY, SORT BY, DISTRIBUTE BY, CLUSTER BY, and HAVING, which is read against
466
+ // the aggregate's output first; QUALIFY where the dialect has it); there its uses are recorded. WHERE, GROUP BY (a table column
467
+ // wins over an alias there) and WINDOW read the tables' columns. A GROUP BY name equal to an
468
+ // alias is recorded too: when the alias is renamed as an output column over anything but the
469
+ // column of its own name, which of the two it reads is not known and it is refused (see
470
+ // outputColumn).
471
+ // The ordering clauses are kept apart: after a set operation (in its last branch, `trailing`)
472
+ // they read its output instead, so no name there is placed by this branch's tables.
473
+ scope.aliasUses = new Map();
474
+ const ordering = trailing
475
+ ? {
476
+ sources: [],
477
+ aliases: scope.aliases,
478
+ aliasUses: new Map(),
479
+ plainUses: new Map(),
480
+ ...(outer ? { parent: outer } : {}),
481
+ }
482
+ : { ...scope, aliasUses: new Map() };
483
+ const groupUses = new Map();
484
+ const tablesOnly = { ...scope, aliases: new Set() };
485
+ delete tablesOnly.aliasUses;
486
+ for (const [index, clause] of clauses.entries()) {
487
+ if (clause.word === 'FROM')
488
+ continue;
489
+ const inScope = aliasClauseWords.has(clause.word)
490
+ ? ['HAVING', 'QUALIFY'].includes(clause.word)
491
+ ? scope
492
+ : ordering
493
+ : tablesOnly;
494
+ this.expression(clause.at + 1, endOf(index), inScope, ctes);
495
+ if (clause.word === 'GROUP')
496
+ this.aliasNames(clause.at + 1, endOf(index), scope.aliases, groupUses);
497
+ }
498
+ const orderUses = ordering.aliasUses;
499
+ for (const [name, indices] of orderUses)
500
+ scope.aliasUses.set(name, [...(scope.aliasUses.get(name) ?? []), ...indices]);
501
+ if (scope.aliasUses.size > 0)
502
+ columns.aliasUses = scope.aliasUses;
503
+ if (orderUses.size > 0)
504
+ columns.orderUses = orderUses;
505
+ if (ordering.plainUses && ordering.plainUses.size > 0)
506
+ columns.plainOrderUses = ordering.plainUses;
507
+ if (groupUses.size > 0)
508
+ columns.groupUses = groupUses;
509
+ return columns;
510
+ }
511
+ /**
512
+ * Record the names of a range written alone (no qualifier, no call) that equal a select alias.
513
+ * @param {number} from First position of the range.
514
+ * @param {number} to End of the range (exclusive).
515
+ * @param {ReadonlySet<string>} aliases The select aliases of the block (lowercase).
516
+ * @param {Map<string, number[]>} uses Uses per alias (token indices), changed in place.
517
+ */
518
+ aliasNames(from, to, aliases, uses) {
519
+ for (let p = from; p < to; p = this.isPunct(p, '(', to) && this.holdsQuery(p) ? this.skip(p) : p + 1) {
520
+ if (!this.isName(p, to) ||
521
+ this.isPunct(p - 1, '.') ||
522
+ this.isPunct(p + 1, '.', to) ||
523
+ this.isPunct(p + 1, '(', to))
524
+ continue;
525
+ const name = this.nameAt(p).toLowerCase();
526
+ if (aliases.has(name))
527
+ uses.set(name, [...(uses.get(name) ?? []), this.sig[p]]);
528
+ }
529
+ }
530
+ fromClause(from, to, outer, ctes, scope, deferred) {
531
+ let p = from;
532
+ // LEFT, RIGHT and LATERAL before a parenthesis are a function; the other join words never are.
533
+ const isJoinStart = (q) => joinWords.has(this.upper(q, to)) &&
534
+ (joinOnlyWords.has(this.upper(q, to)) || !this.isPunct(q + 1, '(', to));
535
+ while (p < to) {
536
+ while (isJoinStart(p)) {
537
+ if (this.upper(p, to) === 'LATERAL' && this.upper(p + 1, to) === 'VIEW')
538
+ p++;
539
+ p++;
540
+ }
541
+ if (this.upper(p, to) === 'OUTER')
542
+ p++;
543
+ if (p >= to)
544
+ break;
545
+ const source = { qualifiers: [], columns: () => ({ owns: false }) };
546
+ let tableName;
547
+ if (this.isPunct(p, '(', to)) {
548
+ const close = this.match.get(p);
549
+ if (this.holdsQuery(p)) {
550
+ const columns = this.query(p + 1, close, outer, ctes);
551
+ source.columns = derivedColumns(columns);
552
+ }
553
+ else
554
+ this.fromClause(p + 1, close, outer, ctes, scope, deferred);
555
+ p = close + 1;
556
+ }
557
+ else if (this.isName(p, to) && this.isPunct(p + 1, '(', to)) {
558
+ // A table function: its arguments are expressions, its columns unknown.
559
+ const close = this.match.get(p + 1);
560
+ this.expression(p + 2, close, outer ?? { sources: [], aliases: new Set() }, ctes);
561
+ source.columns = (field) => this.unknownColumn(field);
562
+ p = close + 1;
563
+ }
564
+ else if (this.isName(p, to) && this.isPunct(p + 1, '.', to)) {
565
+ // A table name with a schema: not a Data Cloud object the rules know.
566
+ let q = p;
567
+ while (this.isName(q, to) && this.isPunct(q + 1, '.', to))
568
+ q += 2;
569
+ for (let r = p; r <= q; r += 2)
570
+ if (nameLike(this.nameAt(r)))
571
+ this.refuse(r, 'a table name with a schema in front is not a name the rules place');
572
+ source.refused = true;
573
+ source.columns = () => ({ owns: true, skip: true });
574
+ p = q + 1;
575
+ }
576
+ else if (this.isName(p, to)) {
577
+ tableName = this.nameAt(p);
578
+ this.table(p, tableName, ctes, source);
579
+ p++;
580
+ }
581
+ else {
582
+ p++;
583
+ continue;
584
+ }
585
+ if (tableName !== undefined)
586
+ source.qualifiers.push(tableName.toLowerCase());
587
+ if (this.upper(p, to) === 'AS')
588
+ p++;
589
+ if (this.isName(p, to) &&
590
+ !reservedWords.has(this.upper(p, to)) &&
591
+ !['ON', 'USING', 'TABLESAMPLE'].includes(this.upper(p, to))) {
592
+ source.qualifiers.unshift(this.nameAt(p).toLowerCase());
593
+ // An alias that looks like a name (`FROM ssot__Individual__dlm ssot__Individual__dlm`)
594
+ // cannot be told apart from the table name it qualifies: refused, not kept.
595
+ if (nameLike(this.nameAt(p)))
596
+ this.refuse(p, 'a table alias that looks like an object or field name cannot be told apart from a name to place; use a short alias such as i');
597
+ else
598
+ this.keep(p, true);
599
+ p++;
600
+ if (this.isPunct(p, '(', to)) {
601
+ const close = this.match.get(p);
602
+ const listed = [];
603
+ for (let q = p + 1; q < close; q++)
604
+ if (this.isName(q, close)) {
605
+ listed.push(this.nameAt(q));
606
+ this.keep(q, true);
607
+ }
608
+ source.columns = derivedColumns(listedColumns(listed));
609
+ p = close + 1;
610
+ }
611
+ }
612
+ scope.sources.push(source);
613
+ // Up to the next table: ON and USING conditions, and anything else, are read in scope.
614
+ let end = p;
615
+ while (end < to && !this.isPunct(end, ',', to) && !isJoinStart(end))
616
+ end = this.skip(end);
617
+ const conditionFrom = p;
618
+ deferred.push(() => this.expression(conditionFrom, end, scope, ctes));
619
+ p = this.isPunct(end, ',', to) ? end + 1 : end;
620
+ }
621
+ }
622
+ /**
623
+ * Place a table name of a FROM clause: a WITH block, an object, or another table.
624
+ * @param {number} p Position among the significant tokens.
625
+ * @param {string} name Table name.
626
+ * @param {readonly Cte[]} ctes The WITH blocks visible here.
627
+ * @param {Source} source The table entry to fill in.
628
+ */
629
+ table(p, name, ctes, source) {
630
+ // The latest WITH block of that name hides an earlier one.
631
+ let cte;
632
+ for (const entry of ctes)
633
+ if (entry.name.toLowerCase() === name.toLowerCase())
634
+ cte = entry;
635
+ if (cte) {
636
+ this.keep(p, true);
637
+ source.columns = derivedColumns(cte.columns);
638
+ return;
639
+ }
640
+ if (!objectLike.test(name)) {
641
+ if (nameLike(name))
642
+ this.refuse(p, 'no rule places this table name');
643
+ source.columns = (field) => this.unknownColumn(field);
644
+ return;
645
+ }
646
+ const placed = this.namer.object(name);
647
+ if (placed === 'dlo') {
648
+ this.keep(p);
649
+ source.keeps = true;
650
+ source.objectName = name.toLowerCase();
651
+ source.objectTo = { name };
652
+ source.columns = (field) => ({ owns: true, name: field });
653
+ return;
654
+ }
655
+ if ('reason' in placed) {
656
+ this.refuse(p, placed.reason);
657
+ source.refused = true;
658
+ source.objectName = name.toLowerCase();
659
+ source.columns = () => ({ owns: true, skip: true });
660
+ return;
661
+ }
662
+ this.edit(p, placed);
663
+ source.objectName = name.toLowerCase();
664
+ source.objectTo = { name: placed.name, ...(placed.rule ? { rule: placed.rule } : {}) };
665
+ source.columns = (field) => ({ owns: true, ...this.namer.field(placed.kind, field) });
666
+ }
667
+ unknownColumn(field) {
668
+ const placed = this.namer.anyField(field);
669
+ return 'reason' in placed
670
+ ? {
671
+ owns: true,
672
+ reason: `the table in front of it is not one the rules know (${placed.reason})`,
673
+ }
674
+ : { owns: true, ...placed };
675
+ }
676
+ selectList(from, to, scope, ctes) {
677
+ let p = from;
678
+ while (['DISTINCT', 'ALL'].includes(this.upper(p, to)))
679
+ p++;
680
+ const columns = { named: new Map(), stars: [] };
681
+ const items = [];
682
+ let start = p;
683
+ for (; p < to; p = this.skip(p))
684
+ if (this.isPunct(p, ',', to)) {
685
+ items.push([start, p]);
686
+ start = p + 1;
687
+ }
688
+ if (start < to)
689
+ items.push([start, to]);
690
+ for (const [begin, end] of items) {
691
+ const last = end - 1;
692
+ const before = last - 1;
693
+ const hasAs = before >= begin && this.upper(before, end) === 'AS';
694
+ // Without AS a word is an alias only after a complete operand, not after `NOT`, `OR`, ….
695
+ const operand = this.isPunct(before, ')', end) ||
696
+ ['number', 'string', 'quoted'].includes(this.tok(before).kind) ||
697
+ (this.tok(before).kind === 'word' && !operatorWords.has(this.upper(before, end)));
698
+ const aliased = last > begin &&
699
+ this.isName(last, end) &&
700
+ !this.isPunct(before, '.', end) &&
701
+ (hasAs || (!reservedWords.has(this.upper(last, end)) && operand));
702
+ if (aliased) {
703
+ const alias = this.nameAt(last);
704
+ // Salesforce accepts a name-like alias without AS after a complete operand; it is a user
705
+ // name, but still goes through the leftover check (`COUNT(x) ssot__Bad__c` is refused).
706
+ this.keep(last, hasAs || !nameLike(alias));
707
+ scope.aliases.add(alias.toLowerCase());
708
+ columns.named.set(alias.toLowerCase(), { owns: true, name: alias });
709
+ // `s.Id__c AS Id__c`: the alias names the column of its own name.
710
+ const exprEnd = hasAs ? before : last;
711
+ const columnAt = exprEnd === begin + 1 && this.isName(begin, exprEnd)
712
+ ? begin
713
+ : exprEnd === begin + 3 &&
714
+ this.isName(begin, exprEnd) &&
715
+ this.isPunct(begin + 1, '.', exprEnd) &&
716
+ this.isName(begin + 2, exprEnd)
717
+ ? begin + 2
718
+ : undefined;
719
+ const ownColumn = columnAt !== undefined && this.nameAt(columnAt).toLowerCase() === alias.toLowerCase();
720
+ (columns.names ??= []).push({
721
+ token: this.sig[last],
722
+ aliased: true,
723
+ ...(ownColumn ? { ownColumn: true } : {}),
724
+ });
725
+ this.expression(begin, exprEnd, scope, ctes);
726
+ continue;
727
+ }
728
+ if (this.isPunct(begin, '*', end) && end === begin + 1) {
729
+ columns.stars.push(...scope.sources);
730
+ (columns.starAt ??= []).push({ token: this.sig[begin], sources: [...scope.sources] });
731
+ continue;
732
+ }
733
+ if (end === begin + 3 &&
734
+ this.isName(begin, end) &&
735
+ this.isPunct(begin + 1, '.', end) &&
736
+ this.isPunct(begin + 2, '*', end)) {
737
+ const source = this.qualifier(begin, scope);
738
+ if (source)
739
+ columns.stars.push(source);
740
+ (columns.starAt ??= []).push({ token: this.sig[begin], sources: source ? [source] : [] });
741
+ continue;
742
+ }
743
+ const single = end === begin + 1 && this.isName(begin, end);
744
+ const qualified = end === begin + 3 &&
745
+ this.isName(begin, end) &&
746
+ this.isPunct(begin + 1, '.', end) &&
747
+ this.isName(begin + 2, end);
748
+ if (single || qualified) {
749
+ const fieldAt = single ? begin : begin + 2;
750
+ const field = this.nameAt(fieldAt);
751
+ const answer = single ? this.unqualified(begin, scope) : this.qualified(begin, scope);
752
+ if (answer && answer.owns)
753
+ columns.named.set(field.toLowerCase(), answer);
754
+ (columns.names ??= []).push({ token: this.sig[fieldAt], aliased: false });
755
+ continue;
756
+ }
757
+ this.expression(begin, end, scope, ctes);
758
+ }
759
+ return columns;
760
+ }
761
+ /**
762
+ * The table a qualifier names in this scope or an enclosing one, marking the qualifier.
763
+ * @param {number} p Position among the significant tokens.
764
+ * @param {Scope} scope The query block the names are read in.
765
+ * @returns {Source | undefined} The table, or undefined when no table of the scope has that qualifier.
766
+ */
767
+ qualifier(p, scope) {
768
+ const name = this.nameAt(p);
769
+ for (let current = scope; current; current = current.parent) {
770
+ const source = current.sources.find((entry) => entry.qualifiers.includes(name.toLowerCase()));
771
+ if (!source)
772
+ continue;
773
+ // The table name itself (with or without an alias) is spelled like the table.
774
+ if (source.objectName === name.toLowerCase()) {
775
+ if (source.refused)
776
+ this.refuse(p, 'its table cannot be placed');
777
+ else
778
+ this.edit(p, source.objectTo);
779
+ }
780
+ else
781
+ this.keep(p, true);
782
+ return source;
783
+ }
784
+ if (objectLike.test(name))
785
+ this.refuse(p, 'it names a table that is not in the FROM clause of this query');
786
+ return undefined;
787
+ }
788
+ /**
789
+ * A column written as `qualifier.column`.
790
+ * @param {number} p Position among the significant tokens.
791
+ * @param {Scope} scope The query block the names are read in.
792
+ * @returns {FieldAnswer | undefined} The answer for the column, or undefined when it is not placed.
793
+ */
794
+ qualified(p, scope) {
795
+ const fieldAt = p + 2;
796
+ const field = this.nameAt(fieldAt);
797
+ const source = this.qualifier(p, scope);
798
+ if (!source) {
799
+ if (nameLike(field) || nameLike(this.nameAt(p)))
800
+ this.refuse(fieldAt, `${this.nameAt(p)} names no table of this query, so the object of the column is not known`);
801
+ return undefined;
802
+ }
803
+ const answer = source.columns(field);
804
+ return this.applyAnswer(fieldAt, field, answer, `${this.nameAt(p)}.${field}`);
805
+ }
806
+ /**
807
+ * A column without a table in front.
808
+ * @param {number} p Position among the significant tokens.
809
+ * @param {Scope} scope The query block the names are read in.
810
+ * @returns {FieldAnswer | undefined} The answer for the column, or undefined when it is not placed.
811
+ */
812
+ unqualified(p, scope) {
813
+ const field = this.nameAt(p);
814
+ if (!nameLike(field))
815
+ return undefined;
816
+ if (objectLike.test(field)) {
817
+ // An object name where a column is expected: it is placed by the object rules.
818
+ const placed = this.namer.object(field);
819
+ if (placed === 'dlo')
820
+ this.keep(p);
821
+ else if ('reason' in placed)
822
+ this.refuse(p, placed.reason);
823
+ else
824
+ this.edit(p, placed);
825
+ return undefined;
826
+ }
827
+ const uses = scope.aliasUses;
828
+ if (uses && scope.aliases.has(field.toLowerCase())) {
829
+ // A clause that reads select aliases (ORDER BY): the alias wins over a table column, and
830
+ // the use follows the alias (see translateSql).
831
+ this.keep(p, true);
832
+ uses.set(field.toLowerCase(), [...(uses.get(field.toLowerCase()) ?? []), this.sig[p]]);
833
+ return { owns: true, name: field };
834
+ }
835
+ const plain = scope.plainUses;
836
+ if (plain) {
837
+ // After a set operation: placed by the first branch's columns (see setOrderUses).
838
+ this.keep(p);
839
+ plain.set(field.toLowerCase(), [...(plain.get(field.toLowerCase()) ?? []), this.sig[p]]);
840
+ return { owns: true, name: field };
841
+ }
842
+ const answers = [];
843
+ // In the select list a later item may read an earlier alias (lateral alias) or the table's
844
+ // column of that name: both readings must agree.
845
+ if (scope.aliases.has(field.toLowerCase()))
846
+ answers.push({ owns: true, name: field });
847
+ for (let current = scope; current; current = current.parent)
848
+ for (const source of current.sources)
849
+ answers.push(source.columns(field));
850
+ const answer = agree(answers, field);
851
+ if (!answer.owns) {
852
+ this.refuse(p, 'no table of this query can own this column, so its spelling cannot be placed');
853
+ return undefined;
854
+ }
855
+ if (scope.aliases.has(field.toLowerCase()) && 'name' in answer && answer.name === field)
856
+ this.keep(p, true);
857
+ return this.applyAnswer(p, field, answer, field);
858
+ }
859
+ applyAnswer(p, field, answer, shown) {
860
+ if (!answer.owns) {
861
+ if (nameLike(field))
862
+ this.refuse(p, `${shown}: the WITH block or subquery in front of it puts out no column of that name the rewrite can place`);
863
+ else
864
+ this.keep(p);
865
+ return undefined;
866
+ }
867
+ if ('reason' in answer) {
868
+ this.refuse(p, answer.reason);
869
+ return answer;
870
+ }
871
+ if ('skip' in answer) {
872
+ this.keep(p);
873
+ return answer;
874
+ }
875
+ this.edit(p, answer);
876
+ return answer;
877
+ }
878
+ /**
879
+ * Names in an expression: columns, qualified columns, subqueries.
880
+ * @param {number} from First position of the range.
881
+ * @param {number} to End of the range (exclusive).
882
+ * @param {Scope} scope The query block the names are read in.
883
+ * @param {readonly Cte[]} ctes The WITH blocks visible here.
884
+ */
885
+ expression(from, to, scope, ctes) {
886
+ let p = from;
887
+ while (p < to) {
888
+ if (this.isPunct(p, '(', to) && this.holdsQuery(p)) {
889
+ const close = this.match.get(p);
890
+ this.query(p + 1, close, scope, ctes);
891
+ p = close + 1;
892
+ continue;
893
+ }
894
+ if (!this.isName(p, to)) {
895
+ p++;
896
+ continue;
897
+ }
898
+ if (this.isPunct(p + 1, '.', to) &&
899
+ (this.isName(p + 2, to) || this.isPunct(p + 2, '*', to))) {
900
+ let end = p + 2;
901
+ while (this.isPunct(end + 1, '.', to) && this.isName(end + 2, to))
902
+ end += 2;
903
+ if (end > p + 2) {
904
+ for (let q = p; q <= end; q += 2)
905
+ if (nameLike(this.nameAt(q)))
906
+ this.refuse(q, 'a name of more than two parts is not one the rules place');
907
+ }
908
+ else if (this.isPunct(p + 2, '*', to))
909
+ this.qualifier(p, scope);
910
+ else if (this.isPunct(end + 1, '(', to)) {
911
+ if (nameLike(this.nameAt(p)) || nameLike(this.nameAt(end)))
912
+ this.refuse(p, 'a function call on a name is not something the rules place');
913
+ }
914
+ else
915
+ this.qualified(p, scope);
916
+ p = end + 1;
917
+ continue;
918
+ }
919
+ if (this.isPunct(p + 1, '(', to)) {
920
+ p++;
921
+ continue;
922
+ }
923
+ this.unqualified(p, scope);
924
+ p++;
925
+ }
926
+ }
927
+ }
928
+ /**
929
+ * The columns of a WITH block or alias with a column list: the listed user names.
930
+ * @param {string[]} listed Column names.
931
+ * @returns {Columns} Columns.
932
+ */
933
+ function listedColumns(listed) {
934
+ return {
935
+ named: new Map(listed.map((name) => [name.toLowerCase(), { owns: true, name }])),
936
+ stars: [],
937
+ };
938
+ }
939
+ /**
940
+ * The first HTML character reference outside texts, comments and quoted names. `&#39;` outside a
941
+ * text reads as `&`, `#`, `39`, `;`: the `;` would split the statement and a name meant as text
942
+ * would be renamed. Such SQL is an HTML-escaped copy, not SQL to translate.
943
+ * @param {SqlToken[]} tokens Tokens.
944
+ * @returns {{token: SqlToken; text: string} | undefined} The token it starts in and the reference.
945
+ */
946
+ function entityOutsideTexts(tokens) {
947
+ const code = tokens.map((token) => ['string', 'comment', 'quoted'].includes(token.kind)
948
+ ? ' '.repeat(token.text.length)
949
+ : token.text);
950
+ const entity = htmlEntity.exec(code.join(''));
951
+ if (!entity)
952
+ return undefined;
953
+ let offset = 0;
954
+ const token = tokens.find((_entry, index) => (offset += code[index].length) > entity.index);
955
+ return { token, text: entity[0] };
956
+ }
957
+ /**
958
+ * The first HTML character reference of a SQL text or expression outside texts, comments and
959
+ * quoted names, with its position: such a text is an HTML-escaped copy (`&#39;`, `&gt;`), not SQL
960
+ * Salesforce reads, since it never decodes entities on write. SQL that cannot be tokenized gives
961
+ * none (Salesforce decides).
962
+ * @param {string} sql SQL text.
963
+ * @returns {{line: number; column: number; text: string} | undefined} The reference, or none.
964
+ */
965
+ export function htmlEntityOutsideTexts(sql) {
966
+ const tokens = tokenizeSql(sql);
967
+ if (isSqlTokenProblem(tokens))
968
+ return undefined;
969
+ const entity = entityOutsideTexts(tokens);
970
+ return entity && { line: entity.token.line, column: entity.token.column, text: entity.text };
971
+ }
972
+ /**
973
+ * Rewrite the names of one SQL text into the target data space. Texts in single quotes and
974
+ * comments are never changed; WITH block names, table aliases and column aliases are user names
975
+ * and stay. A table is placed by the object rules, a column by the rules of its table (through
976
+ * its alias, a WITH block or a subquery); a column without a table in front is placed only when
977
+ * every table that could own it spells it the same way. Anything it cannot place exactly is
978
+ * reported with its line and column. Afterwards every name-like token of the result is checked:
979
+ * a name the rewrite did not account for, or one still in the source spelling, is reported too.
980
+ *
981
+ * With `outputField` (a DCSQL transform, whose output columns land in output fields by name) each
982
+ * named column the outermost query of a statement puts out (its first set branch) is checked
983
+ * against the field of its source name: an alias spelled like that field takes the field's target
984
+ * name, and so do its uses in the clauses that read select aliases (ORDER BY, HAVING); a column without an alias is placed only when its name in the target equals the field's
985
+ * target name, or when it changes from no field's name to none.
986
+ * @param {string} sql SQL text.
987
+ * @param {string} label What the positions are reported against (the SQL file name).
988
+ * @param {SqlNamer} namer The rule engine.
989
+ * @param {OutputField} [outputField] The output field of a column name, for a DCSQL transform.
990
+ * @param {string} [item] What the SQL belongs to (`data transform`, `DBT segment`), as the refusal
991
+ * of an HTML-escaped copy names it.
992
+ * @returns {SqlTranslation} Rewritten SQL, its changes and every name it cannot place.
993
+ */
994
+ export function translateSql(sql, label, namer, outputField, item = 'item') {
995
+ const tokens = tokenizeSql(sql);
996
+ if (isSqlTokenProblem(tokens))
997
+ return {
998
+ sql,
999
+ rewrites: [],
1000
+ unresolved: [
1001
+ {
1002
+ at: `${label} line ${tokens.line}:${tokens.column}`,
1003
+ name: label,
1004
+ reason: `the SQL cannot be read exactly: ${tokens.reason}`,
1005
+ },
1006
+ ],
1007
+ };
1008
+ const at = (token) => `${label} line ${token.line}:${token.column}`;
1009
+ const entity = entityOutsideTexts(tokens);
1010
+ if (entity)
1011
+ return {
1012
+ sql,
1013
+ rewrites: [],
1014
+ unresolved: [
1015
+ {
1016
+ at: at(entity.token),
1017
+ name: entity.text,
1018
+ reason: `the SQL holds an HTML entity outside texts and comments, so it is not SQL that can be read exactly: write the character itself in the file. If a fresh retrieve of the ${item} still shows the entity, Salesforce stores the SQL that way; write the character itself in the file, or fix the SQL in Data Cloud`,
1019
+ },
1020
+ ],
1021
+ };
1022
+ const analysis = new SqlAnalysis(tokens, namer);
1023
+ const found = analysis.run();
1024
+ if (typeof found === 'string')
1025
+ return {
1026
+ sql,
1027
+ rewrites: [],
1028
+ unresolved: [
1029
+ { at: `${label} line 1:1`, name: label, reason: `the SQL cannot be read: ${found}` },
1030
+ ],
1031
+ };
1032
+ // A name the rules read in another case (`SSOT__ID__C`, `ssot__Individual__DLM`) is not placed.
1033
+ for (const [index, token] of tokens.entries()) {
1034
+ const name = tokenName(token);
1035
+ if (name === undefined || found.userNames.has(index) || !nameLike(name))
1036
+ continue;
1037
+ const reason = namer.spelling(name);
1038
+ if (reason === undefined)
1039
+ continue;
1040
+ found.unresolved.set(index, reason);
1041
+ found.edits.delete(index);
1042
+ }
1043
+ if (outputField)
1044
+ for (const columns of analysis.statements)
1045
+ for (const { token, aliased, ownColumn } of columns.names ?? []) {
1046
+ if (found.unresolved.has(token))
1047
+ continue;
1048
+ // An alias over the column of its own name: GROUP BY reads that column either way.
1049
+ const reason = outputColumn(token, aliased, tokens, found, outputField, columns.aliasUses, ownColumn ? undefined : columns.groupUses);
1050
+ if (reason === undefined)
1051
+ continue;
1052
+ found.unresolved.set(token, reason);
1053
+ found.edits.delete(token);
1054
+ }
1055
+ // A use after a set operation is spelled like the first-branch column it reads.
1056
+ for (const [use, column] of found.follows) {
1057
+ const edit = found.edits.get(column);
1058
+ if (edit && !found.unresolved.has(use))
1059
+ found.edits.set(use, edit);
1060
+ }
1061
+ const rewrites = [];
1062
+ const unresolved = [];
1063
+ const parts = tokens.map((token, index) => {
1064
+ const edit = found.edits.get(index);
1065
+ if (!edit)
1066
+ return token.text;
1067
+ rewrites.push({
1068
+ at: at(token),
1069
+ from: tokenName(token),
1070
+ to: edit.to,
1071
+ rule: edit.rule ?? 'field-ssot',
1072
+ });
1073
+ return spellToken(token, edit.to);
1074
+ });
1075
+ // eslint-disable-next-line unicorn/no-array-sort -- Sorting a new array within the ES2022 library target.
1076
+ for (const [index, reason] of [...found.unresolved].sort(([left], [right]) => left - right))
1077
+ unresolved.push({ at: at(tokens[index]), name: tokenName(tokens[index]) ?? '', reason });
1078
+ const result = parts.join('');
1079
+ // The coverage check over the result: positions are the same token for token.
1080
+ const after = tokenizeSql(result);
1081
+ if (isSqlTokenProblem(after) || after.length !== tokens.length) {
1082
+ unresolved.push({
1083
+ at: `${label} line 1:1`,
1084
+ name: label,
1085
+ reason: 'the rewritten SQL does not read back token for token',
1086
+ });
1087
+ return { sql, rewrites, unresolved };
1088
+ }
1089
+ for (const [index, token] of after.entries()) {
1090
+ const name = tokenName(token);
1091
+ if (name === undefined || found.unresolved.has(index) || found.userNames.has(index))
1092
+ continue;
1093
+ const leftover = namer.leftover(name);
1094
+ if (leftover !== undefined)
1095
+ unresolved.push({ at: at(tokens[index]), name, reason: leftover });
1096
+ else if (nameLike(name) && !found.seen.has(index))
1097
+ unresolved.push({
1098
+ at: at(tokens[index]),
1099
+ name,
1100
+ reason: 'the rewrite does not cover this name, so it cannot be placed',
1101
+ });
1102
+ }
1103
+ const outputs = { stars: [] };
1104
+ for (const columns of analysis.statements)
1105
+ for (const star of columns.starAt ?? [])
1106
+ outputs.stars.push({
1107
+ at: at(tokens[star.token]),
1108
+ name: tokens[star.token].text,
1109
+ dlo: star.sources.length > 0 && star.sources.every((source) => source.keeps),
1110
+ });
1111
+ return { sql: result, rewrites, unresolved, outputs };
1112
+ }
1113
+ /**
1114
+ * Check one column the outermost query puts out against the output field of its source name (see
1115
+ * translateSql). An alias spelled like the field is rewritten to the field's target name.
1116
+ * @param {number} token Token index of the alias, or of the column without an alias.
1117
+ * @param {boolean} aliased Whether the token is an alias.
1118
+ * @param {SqlToken[]} tokens Tokens.
1119
+ * @param {Collector} found The analysis result, changed in place.
1120
+ * @param {OutputField} outputField The output field of a column name.
1121
+ * @param {ReadonlyMap<string, number[]>} [aliasUses] The uses of each alias in its query block.
1122
+ * @param {ReadonlyMap<string, number[]>} [groupUses] The uses of each alias in its GROUP BY.
1123
+ * @returns {string | undefined} Why the column cannot be placed, or undefined.
1124
+ */
1125
+ function outputColumn(token, aliased, tokens, found, outputField, aliasUses, groupUses) {
1126
+ const from = tokenName(tokens[token]) ?? '';
1127
+ const field = outputField(from);
1128
+ if (aliased) {
1129
+ if (field && field.name.toLowerCase() !== from.toLowerCase()) {
1130
+ // The alias and every use of it in its query block (ORDER BY ssot__Id__c) take the new name.
1131
+ for (const index of [token, ...(aliasUses?.get(from.toLowerCase()) ?? [])])
1132
+ found.edits.set(index, { to: field.name, rule: field.rule });
1133
+ // GROUP BY reads a table column of that name when one exists, else the alias: for an alias
1134
+ // over anything but that column, which one it means is not known, so it cannot follow.
1135
+ for (const index of groupUses?.get(from.toLowerCase()) ?? []) {
1136
+ found.edits.delete(index);
1137
+ if (!found.unresolved.has(index))
1138
+ found.unresolved.set(index, `GROUP BY ${from} reads a table column ${from} when one exists and the select alias ${from} otherwise, while the alias takes the output field's target name ${field.name} in the target data space, so which one it means cannot be placed: group by the expression itself`);
1139
+ }
1140
+ }
1141
+ return undefined;
1142
+ }
1143
+ const to = found.edits.get(token)?.to ?? from;
1144
+ const same = to.toLowerCase() === (field?.name ?? from).toLowerCase();
1145
+ if (same)
1146
+ return undefined;
1147
+ const way = `write the column with AS ${from}, and the alias then takes the output field's target name`;
1148
+ if (!field)
1149
+ return `this column has no alias, so it puts out a column named ${from}, which names no field of the output object; the translation spells it ${to}, which could land it in another field, so it cannot be placed: write the column with AS and the name of the output field it is meant for`;
1150
+ if (to === from)
1151
+ return `this column has no alias, so it puts out a column named ${from} into the output field ${from}; the column keeps its name in the target data space while the field is spelled ${field.name} there, so it cannot be placed: ${way}`;
1152
+ return `this column has no alias, so it puts out a column named ${from} into the output field ${from}; the translation spells the column ${to} while the field is spelled ${field.name} in the target data space, so it cannot be placed: ${way}`;
1153
+ }
1154
+ // A qualified column inside one quoted name, as STL writes it (`"R.Name__c"`).
1155
+ const quotedQualified = /^([A-Za-z_][A-Za-z0-9_]*)\.([^.]+)$/u;
1156
+ /**
1157
+ * Rewrite the column names of one SQL expression (an STL formula or SQL filter: no FROM, no
1158
+ * tables) into the target data space. Texts in single quotes and comments never change; a
1159
+ * function name stays. A column is placed by `namer.column`, alone (`Name__c`) or with its join
1160
+ * side qualifier, unquoted (`R.Name__c`) or inside one quoted name (`"R.Name__c"`). An object
1161
+ * name, a longer dotted chain, or any name-like token it cannot place exactly is reported with
1162
+ * its line and column. Afterwards every name-like token of the result is checked as in
1163
+ * translateSql.
1164
+ * @param {string} sql Expression text (HTML entities already undone).
1165
+ * @param {string} label What the positions are reported against (the JSON path).
1166
+ * @param {ExpressionNamer} namer The rule engine for this node.
1167
+ * @returns {SqlTranslation} Rewritten expression, its changes and every name it cannot place.
1168
+ */
1169
+ export function translateSqlExpression(sql, label, namer) {
1170
+ const tokens = tokenizeSql(sql);
1171
+ if (isSqlTokenProblem(tokens))
1172
+ return {
1173
+ sql,
1174
+ rewrites: [],
1175
+ unresolved: [
1176
+ {
1177
+ at: `${label} line ${tokens.line}:${tokens.column}`,
1178
+ name: label,
1179
+ reason: `the expression cannot be read exactly: ${tokens.reason}`,
1180
+ },
1181
+ ],
1182
+ };
1183
+ const at = (token) => `${label} line ${token.line}:${token.column}`;
1184
+ const entity = entityOutsideTexts(tokens);
1185
+ if (entity)
1186
+ return {
1187
+ sql,
1188
+ rewrites: [],
1189
+ unresolved: [
1190
+ {
1191
+ at: at(entity.token),
1192
+ name: entity.text,
1193
+ reason: 'the expression holds an HTML entity outside texts after its escaping was undone (escaped twice), so it cannot be read exactly',
1194
+ },
1195
+ ],
1196
+ };
1197
+ const edits = new Map();
1198
+ const unresolved = new Map();
1199
+ const seen = new Set();
1200
+ const sig = tokens.flatMap((token, index) => token.kind === 'space' || token.kind === 'comment' ? [] : [index]);
1201
+ const isPunct = (position, text) => tokens[sig[position]]?.kind === 'punct' && tokens[sig[position]].text === text;
1202
+ // Place one column; `whole` spells the qualifier into the same quoted token.
1203
+ const place = (index, field, qualifier, whole = false) => {
1204
+ seen.add(index);
1205
+ if (objectLike.test(field)) {
1206
+ unresolved.set(index, 'an object name inside an expression cannot be placed');
1207
+ return;
1208
+ }
1209
+ if (!nameLike(field))
1210
+ return;
1211
+ const spelling = namer.spelling(field);
1212
+ if (spelling !== undefined) {
1213
+ unresolved.set(index, spelling);
1214
+ return;
1215
+ }
1216
+ const answer = namer.column(field, qualifier);
1217
+ if ('reason' in answer) {
1218
+ unresolved.set(index, answer.reason);
1219
+ return;
1220
+ }
1221
+ const from = whole ? `${qualifier}.${field}` : field;
1222
+ const to = whole ? `${qualifier}.${answer.name}` : answer.name;
1223
+ if (to !== from)
1224
+ edits.set(index, { from, to, rule: answer.rule });
1225
+ };
1226
+ for (let position = 0; position < sig.length; position++) {
1227
+ const index = sig[position];
1228
+ const name = tokenName(tokens[index]);
1229
+ if (name === undefined || seen.has(index))
1230
+ continue;
1231
+ if (isPunct(position + 1, '.')) {
1232
+ // `R.Name__c`: a qualifier and its column; a longer chain is not placed.
1233
+ const fieldIndex = sig[position + 2];
1234
+ const field = fieldIndex === undefined ? undefined : tokenName(tokens[fieldIndex]);
1235
+ if (field === undefined || isPunct(position + 3, '.')) {
1236
+ seen.add(index);
1237
+ unresolved.set(index, 'a dotted name other than <qualifier>.<field> cannot be placed');
1238
+ continue;
1239
+ }
1240
+ seen.add(index);
1241
+ place(fieldIndex, field, name);
1242
+ position += 2;
1243
+ continue;
1244
+ }
1245
+ if (tokens[index].kind === 'word' && isPunct(position + 1, '(')) {
1246
+ if (nameLike(name)) {
1247
+ seen.add(index);
1248
+ unresolved.set(index, 'a function named like a field or object cannot be placed');
1249
+ }
1250
+ continue;
1251
+ }
1252
+ if (tokens[index].kind === 'quoted' && name.includes('.')) {
1253
+ const qualified = quotedQualified.exec(name);
1254
+ if (!qualified) {
1255
+ seen.add(index);
1256
+ unresolved.set(index, 'a dotted name other than <qualifier>.<field> cannot be placed');
1257
+ continue;
1258
+ }
1259
+ place(index, qualified[2], qualified[1], true);
1260
+ continue;
1261
+ }
1262
+ place(index, name);
1263
+ }
1264
+ const rewrites = [];
1265
+ const parts = tokens.map((token, index) => {
1266
+ const edit = edits.get(index);
1267
+ if (!edit || unresolved.has(index))
1268
+ return token.text;
1269
+ rewrites.push({ at: at(token), from: edit.from, to: edit.to, rule: edit.rule ?? 'field-ssot' });
1270
+ return spellToken(token, edit.to);
1271
+ });
1272
+ const result = [];
1273
+ // eslint-disable-next-line unicorn/no-array-sort -- Sorting a new array within the ES2022 library target.
1274
+ for (const [index, reason] of [...unresolved].sort(([left], [right]) => left - right))
1275
+ result.push({ at: at(tokens[index]), name: tokenName(tokens[index]) ?? '', reason });
1276
+ const text = parts.join('');
1277
+ const after = tokenizeSql(text);
1278
+ if (isSqlTokenProblem(after) || after.length !== tokens.length) {
1279
+ result.push({
1280
+ at: `${label} line 1:1`,
1281
+ name: label,
1282
+ reason: 'the rewritten expression does not read back token for token',
1283
+ });
1284
+ return { sql, rewrites, unresolved: result };
1285
+ }
1286
+ for (const [index, token] of after.entries()) {
1287
+ const name = tokenName(token);
1288
+ if (name === undefined || unresolved.has(index))
1289
+ continue;
1290
+ const leftover = namer.leftover(name);
1291
+ if (leftover !== undefined)
1292
+ result.push({ at: at(tokens[index]), name, reason: leftover });
1293
+ else if (nameLike(name) && !seen.has(index))
1294
+ result.push({
1295
+ at: at(tokens[index]),
1296
+ name,
1297
+ reason: 'the rewrite does not cover this name, so it cannot be placed',
1298
+ });
1299
+ }
1300
+ return { sql: text, rewrites, unresolved: result };
1301
+ }