@starci/eslint-canon-be 3.8.20 → 3.9.2

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 (164) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/package.json +1 -1
  3. package/runtime/bundle.json +192 -0
  4. package/runtime/engine/by-code-unit.mjs +6 -6
  5. package/runtime/engine/model-config.mjs +98 -76
  6. package/runtime/engine/orca-config.mjs +22 -17
  7. package/runtime/engine/release-config.mjs +22 -18
  8. package/runtime/engine/removed-vocabulary.mjs +21 -20
  9. package/runtime/engine/resources-config.mjs +42 -35
  10. package/runtime/engine/runtime-root.mjs +11 -13
  11. package/runtime/engine/secrets.mjs +170 -102
  12. package/runtime/engine/sonar-config.mjs +16 -13
  13. package/runtime/engine/temp-root.mjs +3 -9
  14. package/runtime/knowledge/hfs/canon-pins.yaml +10 -10
  15. package/runtime/knowledge/hfs/rules.yaml +6 -6
  16. package/runtime/knowledge/hfs/slots.yaml +2 -2
  17. package/runtime/knowledge/sonar-gate.yaml +1 -1
  18. package/runtime/packages/hfs/templates/app/package-scripts/package.json +1 -1
  19. package/runtime/scripts/api/git/cat-file.mjs +0 -1
  20. package/runtime/scripts/api/git/config-get.mjs +1 -2
  21. package/runtime/scripts/api/git/diff.mjs +0 -1
  22. package/runtime/scripts/api/git/lib.mjs +32 -32
  23. package/runtime/scripts/api/git/ls-files.mjs +0 -1
  24. package/runtime/scripts/api/git/ls-tree.mjs +0 -1
  25. package/runtime/scripts/api/git/merge-base.mjs +2 -3
  26. package/runtime/scripts/api/git/remote.mjs +0 -1
  27. package/runtime/scripts/api/git/rev-parse-query.mjs +0 -1
  28. package/runtime/scripts/api/git/show.mjs +0 -1
  29. package/runtime/scripts/hfs/allows.mjs +37 -38
  30. package/runtime/scripts/hfs/architecture/ast-walks.mjs +180 -163
  31. package/runtime/scripts/hfs/architecture/automatic-gates.mjs +80 -73
  32. package/runtime/scripts/hfs/architecture/backend-app-files.mjs +88 -77
  33. package/runtime/scripts/hfs/architecture/backend.mjs +378 -357
  34. package/runtime/scripts/hfs/architecture/background-unowned.mjs +201 -187
  35. package/runtime/scripts/hfs/architecture/canon-clones.mjs +260 -209
  36. package/runtime/scripts/hfs/architecture/canon-jsx-clones.mjs +149 -116
  37. package/runtime/scripts/hfs/architecture/client-reaches-server.mjs +72 -68
  38. package/runtime/scripts/hfs/architecture/clones.mjs +212 -217
  39. package/runtime/scripts/hfs/architecture/config-unread.mjs +7 -9
  40. package/runtime/scripts/hfs/architecture/config.mjs +302 -268
  41. package/runtime/scripts/hfs/architecture/connection-map.mjs +258 -225
  42. package/runtime/scripts/hfs/architecture/constructor-deps.mjs +80 -71
  43. package/runtime/scripts/hfs/architecture/context-coupling.mjs +82 -77
  44. package/runtime/scripts/hfs/architecture/context-map.mjs +267 -234
  45. package/runtime/scripts/hfs/architecture/context-owner.mjs +73 -61
  46. package/runtime/scripts/hfs/architecture/context-platform-tables.mjs +47 -43
  47. package/runtime/scripts/hfs/architecture/context-transaction.mjs +54 -52
  48. package/runtime/scripts/hfs/architecture/contract-fixture-guard.mjs +113 -104
  49. package/runtime/scripts/hfs/architecture/contracts-readonly.mjs +288 -270
  50. package/runtime/scripts/hfs/architecture/contracts.mjs +408 -393
  51. package/runtime/scripts/hfs/architecture/cross-app-duplicate.mjs +50 -51
  52. package/runtime/scripts/hfs/architecture/dead-exports-bindings.mjs +143 -119
  53. package/runtime/scripts/hfs/architecture/dead-exports.mjs +286 -228
  54. package/runtime/scripts/hfs/architecture/default-deny.mjs +129 -110
  55. package/runtime/scripts/hfs/architecture/doc-language.mjs +24 -19
  56. package/runtime/scripts/hfs/architecture/entity-registry.mjs +20 -22
  57. package/runtime/scripts/hfs/architecture/entrypoint.mjs +47 -45
  58. package/runtime/scripts/hfs/architecture/error-codes.mjs +37 -35
  59. package/runtime/scripts/hfs/architecture/error-masked.mjs +55 -59
  60. package/runtime/scripts/hfs/architecture/fe-slot-allows.mjs +24 -23
  61. package/runtime/scripts/hfs/architecture/feature-shape.mjs +40 -38
  62. package/runtime/scripts/hfs/architecture/framework-pinned.mjs +21 -21
  63. package/runtime/scripts/hfs/architecture/frontend-block-render.mjs +106 -98
  64. package/runtime/scripts/hfs/architecture/frontend-grammar.mjs +153 -150
  65. package/runtime/scripts/hfs/architecture/frontend-routing.mjs +161 -149
  66. package/runtime/scripts/hfs/architecture/frontend-world-render.mjs +343 -305
  67. package/runtime/scripts/hfs/architecture/frontend-world.mjs +340 -294
  68. package/runtime/scripts/hfs/architecture/frontend.mjs +174 -184
  69. package/runtime/scripts/hfs/architecture/function-spec-providers.mjs +124 -106
  70. package/runtime/scripts/hfs/architecture/hfs-graph.mjs +52 -48
  71. package/runtime/scripts/hfs/architecture/hooks-are-hooks.mjs +81 -71
  72. package/runtime/scripts/hfs/architecture/i18n-keys.mjs +155 -141
  73. package/runtime/scripts/hfs/architecture/identity.mjs +141 -125
  74. package/runtime/scripts/hfs/architecture/index.mjs +272 -272
  75. package/runtime/scripts/hfs/architecture/injection-token-exported.mjs +45 -43
  76. package/runtime/scripts/hfs/architecture/jwt-ast.mjs +195 -176
  77. package/runtime/scripts/hfs/architecture/machine-ast.mjs +163 -155
  78. package/runtime/scripts/hfs/architecture/managed-scripts.mjs +19 -20
  79. package/runtime/scripts/hfs/architecture/module-per-transport.mjs +177 -172
  80. package/runtime/scripts/hfs/architecture/next-data-contract.mjs +100 -78
  81. package/runtime/scripts/hfs/architecture/next-data-inference.mjs +170 -154
  82. package/runtime/scripts/hfs/architecture/next-data-key.mjs +311 -275
  83. package/runtime/scripts/hfs/architecture/next-data-symbols.mjs +17 -17
  84. package/runtime/scripts/hfs/architecture/next-data.mjs +351 -334
  85. package/runtime/scripts/hfs/architecture/operation-contract-roots.mjs +39 -37
  86. package/runtime/scripts/hfs/architecture/owners.mjs +97 -98
  87. package/runtime/scripts/hfs/architecture/package-shape.mjs +56 -55
  88. package/runtime/scripts/hfs/architecture/presentation.mjs +138 -130
  89. package/runtime/scripts/hfs/architecture/reachability.mjs +258 -241
  90. package/runtime/scripts/hfs/architecture/register-once.mjs +152 -139
  91. package/runtime/scripts/hfs/architecture/registration.mjs +301 -267
  92. package/runtime/scripts/hfs/architecture/required-files.mjs +172 -167
  93. package/runtime/scripts/hfs/architecture/route-files-thin.mjs +85 -77
  94. package/runtime/scripts/hfs/architecture/schema-owner.mjs +206 -181
  95. package/runtime/scripts/hfs/architecture/server-action.mjs +48 -48
  96. package/runtime/scripts/hfs/architecture/side-boundary.mjs +2 -5
  97. package/runtime/scripts/hfs/architecture/source-names-shape.mjs +261 -259
  98. package/runtime/scripts/hfs/architecture/source-names.mjs +304 -278
  99. package/runtime/scripts/hfs/architecture/sql-keys.mjs +277 -194
  100. package/runtime/scripts/hfs/architecture/sql-owner.mjs +236 -194
  101. package/runtime/scripts/hfs/architecture/sql-returning.mjs +46 -45
  102. package/runtime/scripts/hfs/architecture/sql-token-forms.mjs +86 -74
  103. package/runtime/scripts/hfs/architecture/sql-tokens.mjs +456 -341
  104. package/runtime/scripts/hfs/architecture/staged-consumers.mjs +35 -30
  105. package/runtime/scripts/hfs/architecture/surface.mjs +64 -74
  106. package/runtime/scripts/hfs/architecture/symbols.mjs +209 -216
  107. package/runtime/scripts/hfs/architecture/test-world-files.mjs +165 -155
  108. package/runtime/scripts/hfs/architecture/tiers.mjs +161 -154
  109. package/runtime/scripts/hfs/architecture/transport-owner.mjs +155 -149
  110. package/runtime/scripts/hfs/architecture/type-context.mjs +255 -250
  111. package/runtime/scripts/hfs/architecture/typescript.mjs +358 -318
  112. package/runtime/scripts/hfs/architecture/unit-spec-providers.mjs +110 -92
  113. package/runtime/scripts/hfs/declaration-shape.mjs +140 -103
  114. package/runtime/scripts/hfs/declaration-slots.mjs +64 -61
  115. package/runtime/scripts/hfs/edition-slots.mjs +43 -40
  116. package/runtime/scripts/hfs/linear-text.mjs +20 -20
  117. package/runtime/scripts/hfs/param-names.mjs +6 -11
  118. package/runtime/scripts/hfs/path-findings.mjs +120 -100
  119. package/runtime/scripts/hfs/repo-identity.mjs +55 -42
  120. package/runtime/scripts/hfs/rule-catalog.mjs +353 -257
  121. package/runtime/scripts/hfs/rule-params-shape.mjs +60 -47
  122. package/runtime/scripts/hfs/rules/database-migrations.mjs +428 -388
  123. package/runtime/scripts/hfs/rules/fe-no-tests.mjs +37 -36
  124. package/runtime/scripts/hfs/rules/read.mjs +19 -15
  125. package/runtime/scripts/hfs/rules/secrets.mjs +1 -1
  126. package/runtime/scripts/hfs/rules/spec-placement.mjs +12 -13
  127. package/runtime/scripts/hfs/slot-app-view.mjs +69 -74
  128. package/runtime/scripts/hfs/slot-classify.mjs +42 -38
  129. package/runtime/scripts/hfs/slot-errors.mjs +8 -7
  130. package/runtime/scripts/hfs/slot-imports.mjs +70 -63
  131. package/runtime/scripts/hfs/slot-manifest-shape.mjs +74 -52
  132. package/runtime/scripts/hfs/slot-match.mjs +122 -111
  133. package/runtime/scripts/hfs/slot-path.mjs +0 -2
  134. package/runtime/scripts/hfs/slot-required.mjs +65 -59
  135. package/runtime/scripts/hfs/slot-semantic-problems.mjs +138 -112
  136. package/runtime/scripts/hfs/slot-side-problems.mjs +23 -19
  137. package/runtime/scripts/hfs/slots.mjs +175 -152
  138. package/runtime/scripts/hfs/test-world-slot.mjs +0 -1
  139. package/runtime/scripts/hfs/trailing-slashes.mjs +4 -4
  140. package/runtime/scripts/hfs/typescript-programs.mjs +66 -69
  141. package/runtime/scripts/hfs/view.mjs +38 -40
  142. package/runtime/scripts/lib/dockerfile.mjs +131 -114
  143. package/runtime/scripts/lib/env.mjs +3 -6
  144. package/runtime/scripts/lib/event-contract.mjs +73 -78
  145. package/runtime/scripts/lib/git.mjs +15 -16
  146. package/runtime/scripts/lib/glob.mjs +23 -14
  147. package/runtime/scripts/lib/grammar-lint.mjs +33 -37
  148. package/runtime/scripts/lib/i18n.mjs +32 -35
  149. package/runtime/scripts/lib/in-order.mjs +57 -38
  150. package/runtime/scripts/lib/json-clone.mjs +45 -36
  151. package/runtime/scripts/lib/json.mjs +26 -14
  152. package/runtime/scripts/lib/language.mjs +133 -129
  153. package/runtime/scripts/lib/list.mjs +9 -14
  154. package/runtime/scripts/lib/mutation-fence.mjs +10 -5
  155. package/runtime/scripts/lib/path-key.mjs +53 -38
  156. package/runtime/scripts/lib/read-text.mjs +30 -17
  157. package/runtime/scripts/lib/regex.mjs +1 -2
  158. package/runtime/scripts/lib/same-text.mjs +0 -1
  159. package/runtime/scripts/lib/sops-envelope.mjs +148 -120
  160. package/runtime/scripts/lib/stack-services.mjs +128 -129
  161. package/runtime/scripts/lib/ts-analysis.mjs +28 -26
  162. package/runtime/scripts/lib/ts-ast.mjs +36 -42
  163. package/runtime/scripts/lib/walk.mjs +33 -27
  164. package/runtime/scripts/lib/yaml-cached.mjs +4 -4
@@ -6,234 +6,300 @@
6
6
  * one is counted as dynamic and judged by nobody.
7
7
  */
8
8
  import { depths, equalityColumns, isName, isWord, matching, nameOf, scalarCastAt } from './sql-token-forms.mjs';
9
-
10
9
  export const HOLE = '';
11
-
12
- const isSpace = char => /\s/u.test(char);
13
- const isWordStart = char => /[\p{L}_]/u.test(char);
14
- const isWordPart = char => /[\p{L}\p{N}_$]/u.test(char);
15
-
10
+ const tokenAt = (tokens, index) => tokens[index];
11
+ /** The upper-cased spelling of a word token ('' for a token that has none). */
12
+ const upOf = (token) => token?.up ?? '';
13
+ const isSpace = (char) => /\s/u.test(char);
14
+ const isWordStart = (char) => /[\p{L}_]/u.test(char);
15
+ const isWordPart = (char) => /[\p{L}\p{N}_$]/u.test(char);
16
16
  const commentEnd = (text, index) => {
17
- if (text[index] === '-' && text[index + 1] === '-') {
18
- while (index < text.length && text[index] !== '\n') index += 1;
19
- return index;
20
- }
21
- if (text[index] !== '/' || text[index + 1] !== '*') return null;
22
- const end = text.indexOf('*/', index + 2);
23
- return end === -1 ? text.length : end + 2;
17
+ if (text[index] === '-' && text[index + 1] === '-') {
18
+ while (index < text.length && text[index] !== '\n')
19
+ index += 1;
20
+ return index;
21
+ }
22
+ if (text[index] !== '/' || text[index + 1] !== '*')
23
+ return null;
24
+ const end = text.indexOf('*/', index + 2);
25
+ return end === -1 ? text.length : end + 2;
24
26
  };
25
-
26
27
  const singleQuotedEnd = (text, index, push) => {
27
- if (text[index] !== "'") return null;
28
- index += 1;
29
- while (index < text.length) {
30
- if (text[index] === "'" && text[index + 1] === "'") { index += 2; continue; }
31
- if (text[index] === "'") break;
28
+ if (text[index] !== "'")
29
+ return null;
32
30
  index += 1;
33
- }
34
- push('string', '');
35
- return index + 1;
31
+ while (index < text.length) {
32
+ if (text[index] === "'" && text[index + 1] === "'") {
33
+ index += 2;
34
+ continue;
35
+ }
36
+ if (text[index] === "'")
37
+ break;
38
+ index += 1;
39
+ }
40
+ push('string', '');
41
+ return index + 1;
36
42
  };
37
-
38
43
  const quotedIdentifierEnd = (text, index, push) => {
39
- if (text[index] !== '"') return null;
40
- let value = '';
41
- index += 1;
42
- while (index < text.length) {
43
- if (text[index] === '"' && text[index + 1] === '"') { value += '"'; index += 2; continue; }
44
- if (text[index] === '"') break;
45
- value += text[index];
44
+ if (text[index] !== '"')
45
+ return null;
46
+ let value = '';
46
47
  index += 1;
47
- }
48
- push('ident', value);
49
- return index + 1;
48
+ while (index < text.length) {
49
+ if (text[index] === '"' && text[index + 1] === '"') {
50
+ value += '"';
51
+ index += 2;
52
+ continue;
53
+ }
54
+ if (text[index] === '"')
55
+ break;
56
+ value += text[index];
57
+ index += 1;
58
+ }
59
+ push('ident', value);
60
+ return index + 1;
50
61
  };
51
-
52
62
  const dollarTokenEnd = (text, index, push) => {
53
- if (text[index] !== '$') return null;
54
- const param = /^\$(\d+)/u.exec(text.slice(index, index + 12));
55
- if (param) { push('param', param[0]); return index + param[0].length; }
56
- const tag = /^\$([\p{L}_][\p{L}\p{N}_]*)?\$/u.exec(text.slice(index));
57
- if (!tag) return null;
58
- const end = text.indexOf(tag[0], index + tag[0].length);
59
- push('string', '');
60
- return end === -1 ? text.length : end + tag[0].length;
63
+ if (text[index] !== '$')
64
+ return null;
65
+ const param = /^\$(\d+)/u.exec(text.slice(index, index + 12));
66
+ if (param) {
67
+ push('param', param[0]);
68
+ return index + param[0].length;
69
+ }
70
+ const tag = /^\$([\p{L}_][\p{L}\p{N}_]*)?\$/u.exec(text.slice(index));
71
+ if (!tag)
72
+ return null;
73
+ const end = text.indexOf(tag[0], index + tag[0].length);
74
+ push('string', '');
75
+ return end === -1 ? text.length : end + tag[0].length;
61
76
  };
62
-
63
77
  const numberEnd = (text, index, push) => {
64
- if (!/\d/u.test(text[index])) return null;
65
- let end = index;
66
- while (end < text.length && /[\d.]/u.test(text[end])) end += 1;
67
- push('number', text.slice(index, end));
68
- return end;
78
+ if (!/\d/u.test(text[index]))
79
+ return null;
80
+ let end = index;
81
+ while (end < text.length && /[\d.]/u.test(text[end]))
82
+ end += 1;
83
+ push('number', text.slice(index, end));
84
+ return end;
69
85
  };
70
-
71
86
  const wordEnd = (text, index, push) => {
72
- if (!isWordStart(text[index])) return null;
73
- let end = index;
74
- while (end < text.length && isWordPart(text[end])) end += 1;
75
- const word = text.slice(index, end);
76
- if (text[end] !== "'" || !/^[EeBbXxNn]$/u.test(word)) { push('word', word); return end; }
77
- const escaped = /^[Ee]$/u.test(word);
78
- end += 1;
79
- while (end < text.length) {
80
- if (escaped && text[end] === '\\') { end += 2; continue; }
81
- if (text[end] === "'" && text[end + 1] === "'") { end += 2; continue; }
82
- if (text[end] === "'") break;
87
+ if (!isWordStart(text[index]))
88
+ return null;
89
+ let end = index;
90
+ while (end < text.length && isWordPart(text[end]))
91
+ end += 1;
92
+ const word = text.slice(index, end);
93
+ if (text[end] !== "'" || !/^[EeBbXxNn]$/u.test(word)) {
94
+ push('word', word);
95
+ return end;
96
+ }
97
+ const escaped = /^[Ee]$/u.test(word);
83
98
  end += 1;
84
- }
85
- push('string', '');
86
- return end + 1;
99
+ while (end < text.length) {
100
+ if (escaped && text[end] === '\\') {
101
+ end += 2;
102
+ continue;
103
+ }
104
+ if (text[end] === "'" && text[end + 1] === "'") {
105
+ end += 2;
106
+ continue;
107
+ }
108
+ if (text[end] === "'")
109
+ break;
110
+ end += 1;
111
+ }
112
+ push('string', '');
113
+ return end + 1;
87
114
  };
88
-
89
115
  const punctuationEnd = (text, index, push) => {
90
- const two = text.slice(index, index + 2);
91
- if (['::', '<=', '>=', '<>', '!=', '||', '->'].includes(two)) { push('punct', two); return index + 2; }
92
- push('punct', text[index]);
93
- return index + 1;
116
+ const two = text.slice(index, index + 2);
117
+ if (['::', '<=', '>=', '<>', '!=', '||', '->'].includes(two)) {
118
+ push('punct', two);
119
+ return index + 2;
120
+ }
121
+ push('punct', text[index]);
122
+ return index + 1;
94
123
  };
95
-
96
124
  function consumeToken(text, index, push) {
97
- const comment = commentEnd(text, index);
98
- if (comment !== null) return comment;
99
- if (text[index] === HOLE) { push('hole', HOLE); return index + 1; }
100
- const singleQuoted = singleQuotedEnd(text, index, push);
101
- if (singleQuoted !== null) return singleQuoted;
102
- const identifier = quotedIdentifierEnd(text, index, push);
103
- if (identifier !== null) return identifier;
104
- const dollarToken = dollarTokenEnd(text, index, push);
105
- if (dollarToken !== null) return dollarToken;
106
- const number = numberEnd(text, index, push);
107
- if (number !== null) return number;
108
- const word = wordEnd(text, index, push);
109
- return word ?? punctuationEnd(text, index, push);
125
+ const comment = commentEnd(text, index);
126
+ if (comment !== null)
127
+ return comment;
128
+ if (text[index] === HOLE) {
129
+ push('hole', HOLE);
130
+ return index + 1;
131
+ }
132
+ const singleQuoted = singleQuotedEnd(text, index, push);
133
+ if (singleQuoted !== null)
134
+ return singleQuoted;
135
+ const identifier = quotedIdentifierEnd(text, index, push);
136
+ if (identifier !== null)
137
+ return identifier;
138
+ const dollarToken = dollarTokenEnd(text, index, push);
139
+ if (dollarToken !== null)
140
+ return dollarToken;
141
+ const number = numberEnd(text, index, push);
142
+ if (number !== null)
143
+ return number;
144
+ const word = wordEnd(text, index, push);
145
+ return word ?? punctuationEnd(text, index, push);
110
146
  }
111
-
112
147
  /** Tokens: {t: 'word'|'ident'|'string'|'number'|'param'|'hole'|'punct', v, up?} (`up` is the uppercase word). */
113
148
  export function tokenizeSql(text) {
114
- const tokens = [];
115
- let i = 0;
116
- const push = (t, v) => tokens.push(t === 'word' ? { t, v, up: v.toUpperCase() } : { t, v });
117
- while (i < text.length) {
118
- const char = text[i];
119
- if (isSpace(char)) { i += 1; continue; }
120
- i = consumeToken(text, i, push);
121
- }
122
- return tokens;
149
+ const tokens = [];
150
+ let i = 0;
151
+ const push = (t, v) => tokens.push(t === 'word' ? { t, v, up: v.toUpperCase() } : { t, v });
152
+ while (i < text.length) {
153
+ const char = text[i];
154
+ if (isSpace(char)) {
155
+ i += 1;
156
+ continue;
157
+ }
158
+ i = consumeToken(text, i, push);
159
+ }
160
+ return tokens;
123
161
  }
124
-
125
162
  const CLAUSE_WORDS = new Set(['WHERE', 'JOIN', 'INNER', 'LEFT', 'RIGHT', 'FULL', 'CROSS', 'NATURAL', 'ON', 'USING', 'GROUP', 'ORDER', 'LIMIT', 'OFFSET',
126
- 'HAVING', 'UNION', 'INTERSECT', 'EXCEPT', 'WINDOW', 'FOR', 'RETURNING', 'SET', 'VALUES', 'SELECT', 'FETCH', 'OUTER', 'TABLESAMPLE', 'WITH', 'AS']);
163
+ 'HAVING', 'UNION', 'INTERSECT', 'EXCEPT', 'WINDOW', 'FOR', 'RETURNING', 'SET', 'VALUES', 'SELECT', 'FETCH', 'OUTER', 'TABLESAMPLE', 'WITH', 'AS']);
127
164
  // PostgreSQL aggregate function names, kept as one string so they read as words, not as failure codes.
128
165
  const AGGREGATES = new Set('COUNT SUM AVG MIN MAX BOOL_AND BOOL_OR EVERY ARRAY_AGG STRING_AGG JSON_AGG JSONB_AGG JSON_OBJECT_AGG JSONB_OBJECT_AGG BIT_AND BIT_OR STDDEV VARIANCE'.split(' '));
129
166
  const FROM_INSIDE = new Set(['EXTRACT', 'SUBSTRING', 'TRIM', 'OVERLAY', 'POSITION']);
130
167
  const NOT_A_WRITE_BEFORE_UPDATE = new Set(['FOR', 'DO', 'ON', 'KEY', 'SHARE', 'OF']);
131
168
  const WHERE_END = new Set(['GROUP', 'ORDER', 'HAVING', 'LIMIT', 'OFFSET', 'UNION', 'INTERSECT', 'EXCEPT', 'FOR', 'WINDOW', 'RETURNING', 'FETCH']);
132
169
  const SYSTEM_SCHEMAS = new Set(['pg_catalog', 'information_schema']);
133
-
134
170
  /**
135
171
  * The table reference at `start`: {parts, table, alias, next}, {dynamic: true}, or null (a subquery, a function, nothing).
136
172
  * `next` is the index after the reference and its alias.
137
173
  */
138
174
  function tableNameAt(tokens, start) {
139
- let i = start;
140
- while (isWord(tokens[i], 'ONLY') || isWord(tokens[i], 'LATERAL')) i += 1;
141
- const first = tokens[i];
142
- if (first?.t === 'hole') return { dynamic: true, next: i + 1 };
143
- if (!isName(first) || (first.t === 'word' && CLAUSE_WORDS.has(first.up) && first.up !== 'AS')) return null;
144
- const parts = [nameOf(first)];
145
- i += 1;
146
- while (tokens[i]?.v === '.' && isName(tokens[i + 1])) { parts.push(nameOf(tokens[i + 1])); i += 2; }
147
- return { parts, next: i };
175
+ let i = start;
176
+ while (isWord(tokens[i], 'ONLY') || isWord(tokens[i], 'LATERAL'))
177
+ i += 1;
178
+ const first = tokens[i];
179
+ if (first?.t === 'hole')
180
+ return { dynamic: true, next: i + 1 };
181
+ if (!isName(first) || (first.t === 'word' && CLAUSE_WORDS.has(upOf(first)) && first.up !== 'AS'))
182
+ return null;
183
+ const parts = [nameOf(first)];
184
+ i += 1;
185
+ for (;;) {
186
+ const part = tokens[i + 1];
187
+ if (!(tokens[i]?.v === '.' && isName(part)))
188
+ break;
189
+ parts.push(nameOf(part));
190
+ i += 2;
191
+ }
192
+ return { parts, next: i };
148
193
  }
149
-
150
194
  function tableAliasAt(tokens, index) {
151
- if (isWord(tokens[index], 'AS') && isName(tokens[index + 1])) return { alias: nameOf(tokens[index + 1]), next: index + 2 };
152
- if (isName(tokens[index]) && !(tokens[index].t === 'word' && CLAUSE_WORDS.has(tokens[index].up))) return { alias: nameOf(tokens[index]), next: index + 1 };
153
- return { alias: null, next: index };
195
+ const current = tokens[index];
196
+ const after = tokens[index + 1];
197
+ if (isWord(current, 'AS') && isName(after))
198
+ return { alias: nameOf(after), next: index + 2 };
199
+ if (isName(current) && !(current.t === 'word' && CLAUSE_WORDS.has(upOf(current))))
200
+ return { alias: nameOf(current), next: index + 1 };
201
+ return { alias: null, next: index };
154
202
  }
155
-
156
203
  function columnListEnd(tokens, start) {
157
- let i = start;
158
- let depth = 0;
159
- do {
160
- if (tokens[i].v === '(') depth += 1;
161
- else if (tokens[i].v === ')') depth -= 1;
162
- i += 1;
163
- } while (i < tokens.length && depth > 0);
164
- return i;
204
+ let i = start;
205
+ let depth = 0;
206
+ do {
207
+ if (tokenAt(tokens, i).v === '(')
208
+ depth += 1;
209
+ else if (tokenAt(tokens, i).v === ')')
210
+ depth -= 1;
211
+ i += 1;
212
+ } while (i < tokens.length && depth > 0);
213
+ return i;
165
214
  }
166
-
167
215
  function tableRef(tokens, start, { columns = false } = {}) {
168
- const reference = tableNameAt(tokens, start);
169
- if (!reference) return null;
170
- if (reference.dynamic) return reference;
171
- const { parts } = reference;
172
- let i = reference.next;
173
- if (tokens[i]?.v === '(' && !columns) return null;
174
- const { alias, next } = tableAliasAt(tokens, i);
175
- i = next;
176
- if (alias && tokens[i]?.v === '(') i = columnListEnd(tokens, i);
177
- return { parts, table: parts.at(-1), schema: parts.length > 1 ? parts.at(-2) : null, alias, next: i };
216
+ const reference = tableNameAt(tokens, start);
217
+ if (!reference)
218
+ return null;
219
+ if (reference.dynamic)
220
+ return reference;
221
+ const { parts } = reference;
222
+ let i = reference.next;
223
+ if (tokens[i]?.v === '(' && !columns)
224
+ return null;
225
+ const { alias, next } = tableAliasAt(tokens, i);
226
+ i = next;
227
+ if (alias && tokens[i]?.v === '(')
228
+ i = columnListEnd(tokens, i);
229
+ return { parts, table: parts.at(-1), schema: parts.length > 1 ? parts.at(-2) : null, alias, next: i };
178
230
  }
179
-
180
231
  function statementsOf(tokens) {
181
- const statements = [];
182
- let current = [];
183
- let depth = 0;
184
- for (const token of tokens) {
185
- if (token.t === 'punct' && token.v === '(') depth += 1;
186
- if (token.t === 'punct' && token.v === ')') depth -= 1;
187
- if (token.t === 'punct' && token.v === ';' && depth <= 0) { if (current.length) { statements.push(current); } current = []; continue; }
188
- current.push(token);
189
- }
190
- if (current.length) statements.push(current);
191
- return statements;
232
+ const statements = [];
233
+ let current = [];
234
+ let depth = 0;
235
+ for (const token of tokens) {
236
+ if (token.t === 'punct' && token.v === '(')
237
+ depth += 1;
238
+ if (token.t === 'punct' && token.v === ')')
239
+ depth -= 1;
240
+ if (token.t === 'punct' && token.v === ';' && depth <= 0) {
241
+ if (current.length) {
242
+ statements.push(current);
243
+ }
244
+ current = [];
245
+ continue;
246
+ }
247
+ current.push(token);
248
+ }
249
+ if (current.length)
250
+ statements.push(current);
251
+ return statements;
192
252
  }
193
-
194
253
  function cteNameBefore(tokens, index) {
195
- let afterAs = index + 1;
196
- if (isWord(tokens[afterAs], 'NOT')) afterAs += 1;
197
- if (isWord(tokens[afterAs], 'MATERIALIZED')) afterAs += 1;
198
- if (tokens[afterAs]?.v !== '(') return null;
199
- let nameIndex = index - 1;
200
- if (tokens[nameIndex]?.v === ')') {
201
- let depth = 0;
202
- do {
203
- if (tokens[nameIndex].v === ')') depth += 1;
204
- else if (tokens[nameIndex].v === '(') depth -= 1;
205
- nameIndex -= 1;
206
- } while (nameIndex >= 0 && depth > 0);
207
- }
208
- const before = tokens[nameIndex - 1];
209
- if (isName(tokens[nameIndex]) && (isWord(before, 'WITH') || isWord(before, 'RECURSIVE') || before?.v === ',')) return nameOf(tokens[nameIndex]);
210
- return null;
254
+ let afterAs = index + 1;
255
+ if (isWord(tokens[afterAs], 'NOT'))
256
+ afterAs += 1;
257
+ if (isWord(tokens[afterAs], 'MATERIALIZED'))
258
+ afterAs += 1;
259
+ if (tokens[afterAs]?.v !== '(')
260
+ return null;
261
+ let nameIndex = index - 1;
262
+ if (tokens[nameIndex]?.v === ')') {
263
+ let depth = 0;
264
+ do {
265
+ if (tokenAt(tokens, nameIndex).v === ')')
266
+ depth += 1;
267
+ else if (tokenAt(tokens, nameIndex).v === '(')
268
+ depth -= 1;
269
+ nameIndex -= 1;
270
+ } while (nameIndex >= 0 && depth > 0);
271
+ }
272
+ const before = tokens[nameIndex - 1];
273
+ const named = tokens[nameIndex];
274
+ if (isName(named) && (isWord(before, 'WITH') || isWord(before, 'RECURSIVE') || before?.v === ','))
275
+ return nameOf(named);
276
+ return null;
211
277
  }
212
-
213
278
  /** The CTE names a statement declares: `name [(cols)] AS [NOT] [MATERIALIZED] (`. */
214
279
  function cteNames(tokens) {
215
- const names = new Set();
216
- for (let i = 1; i < tokens.length; i += 1) {
217
- if (!isWord(tokens[i], 'AS')) continue;
218
- const name = cteNameBefore(tokens, i);
219
- if (name !== null) names.add(name);
220
- }
221
- return names;
280
+ const names = new Set();
281
+ for (let i = 1; i < tokens.length; i += 1) {
282
+ if (!isWord(tokens[i], 'AS'))
283
+ continue;
284
+ const name = cteNameBefore(tokens, i);
285
+ if (name !== null)
286
+ names.add(name);
287
+ }
288
+ return names;
222
289
  }
223
-
224
290
  function isAggregateItem(item) {
225
- for (let i = 0; i < item.length; i += 1) {
226
- if (item[i].t === 'word' && AGGREGATES.has(item[i].up) && item[i + 1]?.v === '(') {
227
- const close = matching(item, i + 1);
228
- if (!isWord(item[close + 1], 'OVER')) return true;
291
+ for (let i = 0; i < item.length; i += 1) {
292
+ const token = tokenAt(item, i);
293
+ if (token.t === 'word' && AGGREGATES.has(upOf(token)) && item[i + 1]?.v === '(') {
294
+ const close = matching(item, i + 1);
295
+ if (!isWord(item[close + 1], 'OVER'))
296
+ return true;
297
+ }
229
298
  }
230
- }
231
- return false;
299
+ return false;
232
300
  }
233
-
234
301
  /** The unique-key columns `columns` (lowercase Set of `=`-constrained column names) satisfy for one of `uniqueSets`. */
235
302
  const covers = (uniqueSets, columns) => uniqueSets.some(set => set.length > 0 && set.every(column => columns.has(column)));
236
-
237
303
  /**
238
304
  * Judge one statement that reads rows (no INSERT/UPDATE/DELETE/MERGE at its own depth): `{bounded, basis}`. Bounded is
239
305
  * a LIMIT/FETCH at the statement depth, no FROM at all (one row), only aggregates without GROUP BY, or an equality on
@@ -241,72 +307,88 @@ const covers = (uniqueSets, columns) => uniqueSets.some(set => set.length > 0 &&
241
307
  * multiply rows even when that relation contributes at most one, so they need an explicit statement bound.
242
308
  */
243
309
  function aggregateSelectItems(tokens, level, select, from) {
244
- const items = [];
245
- let item = [];
246
- for (let i = select + 1; i < from; i += 1) {
247
- if (level[i] === 0 && tokens[i].v === ',' && tokens[i].t === 'punct') { items.push(item); item = []; continue; }
248
- if (!(items.length === 0 && item.length === 0 && (isWord(tokens[i], 'DISTINCT') || isWord(tokens[i], 'ALL')))) item.push(tokens[i]);
249
- }
250
- items.push(item);
251
- return items;
310
+ const items = [];
311
+ let item = [];
312
+ for (let i = select + 1; i < from; i += 1) {
313
+ const token = tokenAt(tokens, i);
314
+ if (level[i] === 0 && token.v === ',' && token.t === 'punct') {
315
+ items.push(item);
316
+ item = [];
317
+ continue;
318
+ }
319
+ if (!(items.length === 0 && item.length === 0 && (isWord(token, 'DISTINCT') || isWord(token, 'ALL'))))
320
+ item.push(token);
321
+ }
322
+ items.push(item);
323
+ return items;
252
324
  }
253
-
254
325
  function whereRegion(tokens, level, where) {
255
- const region = [];
256
- for (let i = where + 1; i < tokens.length; i += 1) {
257
- if (level[i] === 0 && tokens[i].t === 'word' && WHERE_END.has(tokens[i].up)) break;
258
- region.push({ token: tokens[i], level: level[i] });
259
- }
260
- return region;
326
+ const region = [];
327
+ for (let i = where + 1; i < tokens.length; i += 1) {
328
+ const token = tokenAt(tokens, i);
329
+ if (level[i] === 0 && token.t === 'word' && WHERE_END.has(upOf(token)))
330
+ break;
331
+ region.push({ token, level: level[i] });
332
+ }
333
+ return region;
261
334
  }
262
-
263
335
  /** The tokens of a WHERE region split at its top-level AND; the AND of a BETWEEN stays inside its conjunct. */
264
336
  function splitConjuncts(region) {
265
- const conjuncts = [[]];
266
- let between = false;
267
- for (const entry of region) {
268
- const top = entry.level === 0;
269
- if (top && isWord(entry.token, 'BETWEEN')) between = true;
270
- const isAnd = top && isWord(entry.token, 'AND');
271
- if (isAnd && !between) { conjuncts.push([]); continue; }
272
- if (isAnd) between = false;
273
- conjuncts.at(-1).push(entry.token);
274
- }
275
- return conjuncts;
337
+ const conjuncts = [[]];
338
+ let between = false;
339
+ for (const entry of region) {
340
+ const top = entry.level === 0;
341
+ if (top && isWord(entry.token, 'BETWEEN'))
342
+ between = true;
343
+ const isAnd = top && isWord(entry.token, 'AND');
344
+ if (isAnd && !between) {
345
+ conjuncts.push([]);
346
+ continue;
347
+ }
348
+ if (isAnd)
349
+ between = false;
350
+ conjuncts.at(-1).push(entry.token);
351
+ }
352
+ return conjuncts;
276
353
  }
277
-
278
354
  function uniqueWhereColumns(region, primary) {
279
- if (region.some(entry => entry.level === 0 && isWord(entry.token, 'OR'))) return null;
280
- const conjuncts = splitConjuncts(region);
281
- const qualifiers = new Set([primary.table, primary.alias].filter(Boolean));
282
- const columns = new Set();
283
- for (const conjunct of conjuncts) for (const column of equalityColumns(conjunct, qualifiers)) columns.add(column);
284
- return columns;
355
+ if (region.some(entry => entry.level === 0 && isWord(entry.token, 'OR')))
356
+ return null;
357
+ const conjuncts = splitConjuncts(region);
358
+ const qualifiers = new Set([primary.table, primary.alias].filter((name) => Boolean(name)));
359
+ const columns = new Set();
360
+ for (const conjunct of conjuncts)
361
+ for (const column of equalityColumns(conjunct, qualifiers))
362
+ columns.add(column);
363
+ return columns;
285
364
  }
286
-
287
365
  function findTopWord(tokens, level, up, from = 0) {
288
- for (let i = from; i < tokens.length; i += 1) { if (level[i] === 0 && isWord(tokens[i], up)) return i; }
289
- return -1;
366
+ for (let i = from; i < tokens.length; i += 1) {
367
+ if (level[i] === 0 && isWord(tokens[i], up))
368
+ return i;
369
+ }
370
+ return -1;
290
371
  }
291
-
292
372
  const hasTopGroupBy = (tokens, level) => tokens.some((token, i) => level[i] === 0 && isWord(token, 'GROUP') && isWord(tokens[i + 1], 'BY'));
293
-
294
373
  function isUniqueBounded(tokens, level, from, primary, uniqueSets) {
295
- const where = findTopWord(tokens, level, 'WHERE', from);
296
- if (!uniqueSets?.length || where < 0) return false;
297
- const columns = uniqueWhereColumns(whereRegion(tokens, level, where), primary);
298
- return Boolean(columns) && covers(uniqueSets, columns);
374
+ const where = findTopWord(tokens, level, 'WHERE', from);
375
+ if (!uniqueSets?.length || where < 0)
376
+ return false;
377
+ const columns = uniqueWhereColumns(whereRegion(tokens, level, where), primary);
378
+ return columns !== null && covers(uniqueSets, columns);
299
379
  }
300
-
301
380
  function singleFromRelation(tokens, level, from) {
302
- for (let index = from + 1; index < tokens.length; index += 1) {
303
- if (level[index] !== 0) continue;
304
- if (isWord(tokens[index], 'WHERE') || (tokens[index].t === 'word' && WHERE_END.has(tokens[index].up))) break;
305
- if (isWord(tokens[index], 'JOIN') || (tokens[index].t === 'punct' && tokens[index].v === ',')) return false;
306
- }
307
- return true;
381
+ for (let index = from + 1; index < tokens.length; index += 1) {
382
+ if (level[index] !== 0)
383
+ continue;
384
+ const token = tokenAt(tokens, index);
385
+ if (isWord(token, 'WHERE') || (token.t === 'word' && WHERE_END.has(upOf(token))))
386
+ break;
387
+ if (isWord(token, 'JOIN') || (token.t === 'punct' && token.v === ','))
388
+ return false;
389
+ }
390
+ return true;
308
391
  }
309
-
310
392
  // Functions that return a set of rows when they stand in a select list. A select list holding one multiplies the rows.
311
393
  const SET_RETURNING = new Set(`GENERATE_SERIES GENERATE_SUBSCRIPTS UNNEST REGEXP_MATCHES REGEXP_SPLIT_TO_TABLE STRING_TO_TABLE
312
394
  JSON_EACH JSONB_EACH JSON_EACH_TEXT JSONB_EACH_TEXT JSON_ARRAY_ELEMENTS JSONB_ARRAY_ELEMENTS JSON_ARRAY_ELEMENTS_TEXT JSONB_ARRAY_ELEMENTS_TEXT
@@ -316,157 +398,190 @@ JSONB_PATH_QUERY JSONB_PATH_QUERY_TZ JSON_TABLE PG_LS_DIR PG_LS_WALDIR PG_LS_LOG
316
398
  const SCALAR_CALLS = new Set(`COALESCE NULLIF GREATEST LEAST ROUND CEIL CEILING FLOOR ABS TRUNC EXTRACT DATE_PART DATE_TRUNC TO_CHAR LOWER UPPER LENGTH CONCAT
317
399
  JSONB_BUILD_OBJECT JSONB_BUILD_ARRAY JSON_BUILD_OBJECT JSON_BUILD_ARRAY TO_JSONB TO_JSON`.split(/\s+/u));
318
400
  const NOT_A_CALL = new Set(['IN', 'ANY', 'ALL', 'SOME', 'AND', 'OR', 'NOT', 'FILTER', 'EXISTS', 'CASE', 'WHEN', 'THEN', 'ELSE', 'AS', 'ON', 'DISTINCT', 'BETWEEN', 'LIKE', 'ILIKE', 'IS', 'WITHIN', 'FROM']);
319
-
320
- const callAt = (tokens, index) => isName(tokens[index]) && tokens[index + 1]?.v === '(' && !(tokens[index].t === 'word' && (NOT_A_CALL.has(tokens[index].up) || CLAUSE_WORDS.has(tokens[index].up)));
321
-
401
+ const callAt = (tokens, index) => {
402
+ const token = tokens[index];
403
+ return isName(token) && tokens[index + 1]?.v === '(' && !(token.t === 'word' && (NOT_A_CALL.has(upOf(token)) || CLAUSE_WORDS.has(upOf(token))));
404
+ };
322
405
  /** A call to a set-returning function anywhere in the statement (conservative: nested positions count). */
323
- const hasSetReturningCall = tokens => tokens.some((token, index) => callAt(tokens, index) && token.t === 'word' && SET_RETURNING.has(token.up));
324
-
325
- const hasWindow = tokens => tokens.some(token => isWord(token, 'OVER'));
326
-
406
+ const hasSetReturningCall = (tokens) => tokens.some((token, index) => callAt(tokens, index) && token.t === 'word' && SET_RETURNING.has(upOf(token)));
407
+ const hasWindow = (tokens) => tokens.some(token => isWord(token, 'OVER'));
327
408
  /** Plain known aggregate calls and known scalar builtins are scalar; other calls, including wrappers around aggregates, may return sets. */
328
409
  function unprovenProjectionCall(tokens, level, select, from) {
329
- const end = from < 0 ? tokens.length : from;
330
- for (let index = select + 1; index < end; index += 1) {
331
- const token = tokens[index];
332
- if (level[index] === 0 && (isWord(token, 'WHERE') || (token.t === 'word' && WHERE_END.has(token.up)))) break;
333
- if (!callAt(tokens, index)) continue;
334
- if (scalarCastAt(tokens, index)) continue;
335
- const known = token.t === 'word' && tokens[index - 1]?.v !== '.' && (AGGREGATES.has(token.up) || SCALAR_CALLS.has(token.up));
336
- if (!known) return true;
337
- }
338
- return false;
410
+ const end = from < 0 ? tokens.length : from;
411
+ for (let index = select + 1; index < end; index += 1) {
412
+ const token = tokenAt(tokens, index);
413
+ if (level[index] === 0 && (isWord(token, 'WHERE') || (token.t === 'word' && WHERE_END.has(upOf(token)))))
414
+ break;
415
+ if (!callAt(tokens, index))
416
+ continue;
417
+ if (scalarCastAt(tokens, index))
418
+ continue;
419
+ const known = token.t === 'word' && tokens[index - 1]?.v !== '.' && (AGGREGATES.has(upOf(token)) || SCALAR_CALLS.has(upOf(token)));
420
+ if (!known)
421
+ return true;
422
+ }
423
+ return false;
339
424
  }
340
-
341
425
  /**
342
426
  * A SELECT that returns at most one row by construction: it has no FROM (one row, unless a set-returning function multiplies it),
343
427
  * or it selects only aggregates (plain or inside known scalar calls and casts) with no GROUP BY, window or set-returning function.
344
428
  */
345
429
  function singleRowBound(tokens, level, select, from, grouped) {
346
- if (hasSetReturningCall(tokens) || hasWindow(tokens)) return null;
347
- if (from < 0) return grouped ? null : { bounded: true, basis: 'no from' };
348
- if (!grouped && !unprovenProjectionCall(tokens, level, select, from) && aggregateSelectItems(tokens, level, select, from).every(isAggregateItem)) return { bounded: true, basis: 'aggregate' };
349
- return null;
430
+ if (hasSetReturningCall(tokens) || hasWindow(tokens))
431
+ return null;
432
+ if (from < 0)
433
+ return grouped ? null : { bounded: true, basis: 'no from' };
434
+ if (!grouped && !unprovenProjectionCall(tokens, level, select, from) && aggregateSelectItems(tokens, level, select, from).every(isAggregateItem))
435
+ return { bounded: true, basis: 'aggregate' };
436
+ return null;
350
437
  }
351
-
352
438
  function selectBound(tokens, level, uniqueSetsOf, cte) {
353
- if (findTopWord(tokens, level, 'LIMIT') >= 0 || findTopWord(tokens, level, 'FETCH') >= 0) return { bounded: true, basis: 'limit' };
354
- const select = findTopWord(tokens, level, 'SELECT');
355
- const from = findTopWord(tokens, level, 'FROM', select);
356
- const primary = from < 0 ? null : tableRef(tokens, from + 1);
357
- const unbounded = { bounded: false, basis: 'unbounded', table: primary?.table ?? null };
358
- const grouped = hasTopGroupBy(tokens, level);
359
- if (tokens.some((token, index) => level[index] === 0 && (isWord(token, 'UNION') || isWord(token, 'INTERSECT') || isWord(token, 'EXCEPT')))) return unbounded;
360
- const single = singleRowBound(tokens, level, select, from, grouped);
361
- if (single) return single;
362
- if (unprovenProjectionCall(tokens, level, select, from) || hasSetReturningCall(tokens)) return unbounded;
363
- if (grouped || from < 0 || !primary || primary.dynamic || cte.has(primary.table) || !singleFromRelation(tokens, level, from)) return unbounded;
364
- if (isUniqueBounded(tokens, level, from, primary, uniqueSetsOf(primary.table, primary.schema))) return { bounded: true, basis: 'unique' };
365
- return unbounded;
439
+ if (findTopWord(tokens, level, 'LIMIT') >= 0 || findTopWord(tokens, level, 'FETCH') >= 0)
440
+ return { bounded: true, basis: 'limit' };
441
+ const select = findTopWord(tokens, level, 'SELECT');
442
+ const from = findTopWord(tokens, level, 'FROM', select);
443
+ const primary = from < 0 ? null : tableRef(tokens, from + 1);
444
+ const unbounded = { bounded: false, basis: 'unbounded', table: primary && !primary.dynamic ? primary.table : null };
445
+ const grouped = hasTopGroupBy(tokens, level);
446
+ if (tokens.some((token, index) => level[index] === 0 && (isWord(token, 'UNION') || isWord(token, 'INTERSECT') || isWord(token, 'EXCEPT'))))
447
+ return unbounded;
448
+ const single = singleRowBound(tokens, level, select, from, grouped);
449
+ if (single)
450
+ return single;
451
+ if (unprovenProjectionCall(tokens, level, select, from) || hasSetReturningCall(tokens))
452
+ return unbounded;
453
+ if (grouped || from < 0 || !primary || primary.dynamic || cte.has(primary.table) || !singleFromRelation(tokens, level, from))
454
+ return unbounded;
455
+ if (isUniqueBounded(tokens, level, from, primary, uniqueSetsOf(primary.table, primary.schema)))
456
+ return { bounded: true, basis: 'unique' };
457
+ return unbounded;
366
458
  }
367
-
368
459
  function recordSqlReference(list, ref, reads, cte, state) {
369
- if (!ref) return;
370
- if (ref.dynamic) { state.dynamic += 1; return; }
371
- if (ref.schema && SYSTEM_SCHEMAS.has(ref.schema)) return;
372
- if (ref.table.startsWith('pg_')) return;
373
- if (list === reads && !ref.schema && cte.has(ref.table)) return;
374
- list.push({ table: ref.table, schema: ref.schema });
460
+ if (!ref)
461
+ return;
462
+ if (ref.dynamic) {
463
+ state.dynamic += 1;
464
+ return;
465
+ }
466
+ if (ref.schema && SYSTEM_SCHEMAS.has(ref.schema))
467
+ return;
468
+ if (ref.table.startsWith('pg_'))
469
+ return;
470
+ if (list === reads && !ref.schema && cte.has(ref.table))
471
+ return;
472
+ list.push({ table: ref.table, schema: ref.schema });
375
473
  }
376
-
377
474
  function recordTableList(tokens, start, list, record, commaIsPunctuation) {
378
- let i = start;
379
- for (;;) {
380
- const ref = tableRef(tokens, i);
381
- record(list, ref);
382
- if (ref && tokens[ref.next]?.v === ',' && (!commaIsPunctuation || tokens[ref.next].t === 'punct')) { i = ref.next + 1; continue; }
383
- break;
384
- }
475
+ let i = start;
476
+ for (;;) {
477
+ const ref = tableRef(tokens, i);
478
+ record(list, ref);
479
+ if (ref && tokens[ref.next]?.v === ',' && (!commaIsPunctuation || tokenAt(tokens, ref.next).t === 'punct')) {
480
+ i = ref.next + 1;
481
+ continue;
482
+ }
483
+ break;
484
+ }
385
485
  }
386
-
387
486
  // Where the table reference of a write verb starts (an offset from the verb) and whether it may carry a column list; null for any other token.
388
487
  function writeTarget(token, next, previous) {
389
- if (token.up === 'INSERT' && isWord(next, 'INTO')) return { offset: 2, columns: true };
390
- if (token.up === 'UPDATE' && !(previous?.t === 'word' && NOT_A_WRITE_BEFORE_UPDATE.has(previous.up))) return { offset: 1, columns: false };
391
- if ((token.up === 'DELETE' && isWord(next, 'FROM')) || (token.up === 'MERGE' && isWord(next, 'INTO'))) return { offset: 2, columns: false };
392
- return null;
488
+ if (token.up === 'INSERT' && isWord(next, 'INTO'))
489
+ return { offset: 2, columns: true };
490
+ if (token.up === 'UPDATE' && !(previous?.t === 'word' && NOT_A_WRITE_BEFORE_UPDATE.has(upOf(previous))))
491
+ return { offset: 1, columns: false };
492
+ if ((token.up === 'DELETE' && isWord(next, 'FROM')) || (token.up === 'MERGE' && isWord(next, 'INTO')))
493
+ return { offset: 2, columns: false };
494
+ return null;
393
495
  }
394
-
395
496
  function processWriteToken(tokens, level, index, token, record, state) {
396
- const target = writeTarget(token, tokens[index + 1], state.previous);
397
- if (target) {
398
- if (level[index] === 0) state.hasWriteVerb = true;
399
- record(state.writes, tableRef(tokens, index + target.offset, { columns: target.columns }));
497
+ const target = writeTarget(token, tokens[index + 1], state.previous);
498
+ if (target) {
499
+ if (level[index] === 0)
500
+ state.hasWriteVerb = true;
501
+ record(state.writes, tableRef(tokens, index + target.offset, { columns: target.columns }));
502
+ return true;
503
+ }
504
+ if (token.up !== 'TRUNCATE')
505
+ return false;
506
+ let start = index + 1;
507
+ if (isWord(tokens[start], 'TABLE'))
508
+ start += 1;
509
+ recordTableList(tokens, start, state.writes, record, false);
400
510
  return true;
401
- }
402
- if (token.up !== 'TRUNCATE') return false;
403
- let start = index + 1;
404
- if (isWord(tokens[start], 'TABLE')) start += 1;
405
- recordTableList(tokens, start, state.writes, record, false);
406
- return true;
407
511
  }
408
-
409
512
  function processReadToken(tokens, index, token, record, state, mergeOrDelete) {
410
- if (token.up === 'FROM' && !isWord(state.previous, 'DISTINCT') && !isWord(state.previous, 'DELETE') && state.parens.at(-1) !== true) {
411
- recordTableList(tokens, index + 1, state.reads, record, true);
412
- return;
413
- }
414
- if (token.up === 'JOIN') { record(state.reads, tableRef(tokens, index + 1)); return; }
415
- if (token.up === 'USING' && mergeOrDelete && tokens[index + 1]?.v !== '(') record(state.reads, tableRef(tokens, index + 1));
513
+ if (token.up === 'FROM' && !isWord(state.previous, 'DISTINCT') && !isWord(state.previous, 'DELETE') && state.parens.at(-1) !== true) {
514
+ recordTableList(tokens, index + 1, state.reads, record, true);
515
+ return;
516
+ }
517
+ if (token.up === 'JOIN') {
518
+ record(state.reads, tableRef(tokens, index + 1));
519
+ return;
520
+ }
521
+ if (token.up === 'USING' && mergeOrDelete && tokens[index + 1]?.v !== '(')
522
+ record(state.reads, tableRef(tokens, index + 1));
416
523
  }
417
-
418
524
  function trackParenthesis(tokens, index, state) {
419
- const token = tokens[index];
420
- if (token.t !== 'punct') return false;
421
- if (token.v === '(') { state.parens.push(index > 0 && tokens[index - 1].t === 'word' && FROM_INSIDE.has(tokens[index - 1].up)); return true; }
422
- if (token.v !== ')') return false;
423
- state.parens.pop();
424
- return true;
525
+ const token = tokenAt(tokens, index);
526
+ if (token.t !== 'punct')
527
+ return false;
528
+ if (token.v === '(') {
529
+ const before = tokens[index - 1];
530
+ state.parens.push(index > 0 && before !== undefined && before.t === 'word' && FROM_INSIDE.has(upOf(before)));
531
+ return true;
532
+ }
533
+ if (token.v !== ')')
534
+ return false;
535
+ state.parens.pop();
536
+ return true;
425
537
  }
426
-
427
538
  function statementReferences(tokens, level, cte) {
428
- const state = { writes: [], reads: [], parens: [], dynamic: 0, hasWriteVerb: false };
429
- const record = (list, ref) => recordSqlReference(list, ref, state.reads, cte, state);
430
- const mergeOrDelete = tokens.some(token => isWord(token, 'MERGE')) || tokens.some(token => isWord(token, 'DELETE'));
431
- for (let i = 0; i < tokens.length; i += 1) {
432
- const token = tokens[i];
433
- if (trackParenthesis(tokens, i, state) || token.t !== 'word') continue;
434
- state.previous = tokens[i - 1];
435
- if (processWriteToken(tokens, level, i, token, record, state)) {
436
- if (token.up === 'DELETE') i += 1;
437
- continue;
539
+ const state = { writes: [], reads: [], parens: [], dynamic: 0, hasWriteVerb: false };
540
+ const record = (list, ref) => recordSqlReference(list, ref, state.reads, cte, state);
541
+ const mergeOrDelete = tokens.some(token => isWord(token, 'MERGE')) || tokens.some(token => isWord(token, 'DELETE'));
542
+ for (let i = 0; i < tokens.length; i += 1) {
543
+ const token = tokenAt(tokens, i);
544
+ if (trackParenthesis(tokens, i, state) || token.t !== 'word')
545
+ continue;
546
+ state.previous = tokens[i - 1];
547
+ if (processWriteToken(tokens, level, i, token, record, state)) {
548
+ if (token.up === 'DELETE')
549
+ i += 1;
550
+ continue;
551
+ }
552
+ processReadToken(tokens, i, token, record, state, mergeOrDelete);
438
553
  }
439
- processReadToken(tokens, i, token, record, state, mergeOrDelete);
440
- }
441
- return state;
554
+ return state;
442
555
  }
443
-
444
556
  function statementAnalysis(tokens, uniqueSetsOf) {
445
- const cte = cteNames(tokens);
446
- const level = depths(tokens);
447
- const references = statementReferences(tokens, level, cte);
448
- const selects = [];
449
- const hasSelect = tokens.some((candidate, i) => level[i] === 0 && isWord(candidate, 'SELECT'));
450
- if (hasSelect && !references.hasWriteVerb) selects.push(selectBound(tokens, level, uniqueSetsOf, cte));
451
- return { ...references, selects };
557
+ const cte = cteNames(tokens);
558
+ const level = depths(tokens);
559
+ const references = statementReferences(tokens, level, cte);
560
+ const selects = [];
561
+ const hasSelect = tokens.some((candidate, i) => level[i] === 0 && isWord(candidate, 'SELECT'));
562
+ if (hasSelect && !references.hasWriteVerb)
563
+ selects.push(selectBound(tokens, level, uniqueSetsOf, cte));
564
+ return { ...references, selects };
452
565
  }
453
-
454
566
  /**
455
567
  * Read one SQL text. `uniqueSetsOf(table, schema)` returns the unique-key column sets (each a lowercase column list)
456
568
  * proven for that relation by its declared schema authority, or null when no key is known.
457
569
  * Returns {writes: [{table, schema}], reads: [{table, schema}], selects: [{bounded, basis, table}], dynamic}.
458
570
  */
459
571
  export function analyzeSql(text, { uniqueSetsOf = () => null } = {}) {
460
- const writes = [];
461
- const reads = [];
462
- const selects = [];
463
- let dynamic = 0;
464
- for (const tokens of statementsOf(tokenizeSql(text))) {
465
- const statement = statementAnalysis(tokens, uniqueSetsOf);
466
- for (const write of statement.writes) writes.push(write);
467
- for (const read of statement.reads) reads.push(read);
468
- for (const select of statement.selects) selects.push(select);
469
- dynamic += statement.dynamic;
470
- }
471
- return { writes, reads, selects, dynamic };
572
+ const writes = [];
573
+ const reads = [];
574
+ const selects = [];
575
+ let dynamic = 0;
576
+ for (const tokens of statementsOf(tokenizeSql(text))) {
577
+ const statement = statementAnalysis(tokens, uniqueSetsOf);
578
+ for (const write of statement.writes)
579
+ writes.push(write);
580
+ for (const read of statement.reads)
581
+ reads.push(read);
582
+ for (const select of statement.selects)
583
+ selects.push(select);
584
+ dynamic += statement.dynamic;
585
+ }
586
+ return { writes, reads, selects, dynamic };
472
587
  }