@memberjunction/sql-parser 6.2.0-edge.6 → 6.2.0-edge.8

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 (286) hide show
  1. package/README.md +392 -0
  2. package/dist/aggregateExpression.d.ts +5 -1
  3. package/dist/aggregateExpression.d.ts.map +1 -1
  4. package/dist/aggregateExpression.js +7 -420
  5. package/dist/aggregateExpression.js.map +1 -1
  6. package/dist/common/analysis.d.ts +48 -0
  7. package/dist/common/analysis.d.ts.map +1 -0
  8. package/dist/common/analysis.js +17 -0
  9. package/dist/common/analysis.js.map +1 -0
  10. package/dist/common/diagnosticCodes.d.ts +96 -0
  11. package/dist/common/diagnosticCodes.d.ts.map +1 -0
  12. package/dist/common/diagnosticCodes.js +99 -0
  13. package/dist/common/diagnosticCodes.js.map +1 -0
  14. package/dist/edit/clauseTransforms.d.ts +40 -0
  15. package/dist/edit/clauseTransforms.d.ts.map +1 -0
  16. package/dist/edit/clauseTransforms.js +161 -0
  17. package/dist/edit/clauseTransforms.js.map +1 -0
  18. package/dist/edit/cteTransforms.d.ts +68 -0
  19. package/dist/edit/cteTransforms.d.ts.map +1 -0
  20. package/dist/edit/cteTransforms.js +127 -0
  21. package/dist/edit/cteTransforms.js.map +1 -0
  22. package/dist/edit/editSet.d.ts +83 -0
  23. package/dist/edit/editSet.d.ts.map +1 -0
  24. package/dist/edit/editSet.js +185 -0
  25. package/dist/edit/editSet.js.map +1 -0
  26. package/dist/edit/transformSupport.d.ts +53 -0
  27. package/dist/edit/transformSupport.d.ts.map +1 -0
  28. package/dist/edit/transformSupport.js +67 -0
  29. package/dist/edit/transformSupport.js.map +1 -0
  30. package/dist/index.d.ts +49 -3
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +24 -1
  33. package/dist/index.js.map +1 -1
  34. package/dist/legacy/cteParenScan.d.ts +13 -0
  35. package/dist/legacy/cteParenScan.d.ts.map +1 -0
  36. package/dist/legacy/cteParenScan.js +120 -0
  37. package/dist/legacy/cteParenScan.js.map +1 -0
  38. package/dist/legacy/dialectResolution.d.ts +22 -0
  39. package/dist/legacy/dialectResolution.d.ts.map +1 -0
  40. package/dist/legacy/dialectResolution.js +55 -0
  41. package/dist/legacy/dialectResolution.js.map +1 -0
  42. package/dist/legacy/frozenCTEExtraction.d.ts +10 -0
  43. package/dist/legacy/frozenCTEExtraction.d.ts.map +1 -0
  44. package/dist/legacy/frozenCTEExtraction.js +38 -0
  45. package/dist/legacy/frozenCTEExtraction.js.map +1 -0
  46. package/dist/legacy/legacyExtractors.d.ts +54 -0
  47. package/dist/legacy/legacyExtractors.d.ts.map +1 -0
  48. package/dist/legacy/legacyExtractors.js +245 -0
  49. package/dist/legacy/legacyExtractors.js.map +1 -0
  50. package/dist/legacy/legacyTagContent.d.ts +29 -0
  51. package/dist/legacy/legacyTagContent.d.ts.map +1 -0
  52. package/dist/legacy/legacyTagContent.js +283 -0
  53. package/dist/legacy/legacyTagContent.js.map +1 -0
  54. package/dist/legacy/legacyTemplateExtractors.d.ts +31 -0
  55. package/dist/legacy/legacyTemplateExtractors.d.ts.map +1 -0
  56. package/dist/legacy/legacyTemplateExtractors.js +201 -0
  57. package/dist/legacy/legacyTemplateExtractors.js.map +1 -0
  58. package/dist/legacy/legacyTemplateTokens.d.ts +16 -0
  59. package/dist/legacy/legacyTemplateTokens.d.ts.map +1 -0
  60. package/dist/legacy/legacyTemplateTokens.js +80 -0
  61. package/dist/legacy/legacyTemplateTokens.js.map +1 -0
  62. package/dist/legacy/nodeSqlParserCore.d.ts +34 -0
  63. package/dist/legacy/nodeSqlParserCore.d.ts.map +1 -0
  64. package/dist/legacy/nodeSqlParserCore.js +251 -0
  65. package/dist/legacy/nodeSqlParserCore.js.map +1 -0
  66. package/dist/legacy/nodeSqlRowCap.d.ts +46 -0
  67. package/dist/legacy/nodeSqlRowCap.d.ts.map +1 -0
  68. package/dist/legacy/nodeSqlRowCap.js +72 -0
  69. package/dist/legacy/nodeSqlRowCap.js.map +1 -0
  70. package/dist/legacy/nonQueryReads.d.ts +28 -0
  71. package/dist/legacy/nonQueryReads.d.ts.map +1 -0
  72. package/dist/legacy/nonQueryReads.js +112 -0
  73. package/dist/legacy/nonQueryReads.js.map +1 -0
  74. package/dist/legacy/templateSqlViews.d.ts +32 -0
  75. package/dist/legacy/templateSqlViews.d.ts.map +1 -0
  76. package/dist/legacy/templateSqlViews.js +176 -0
  77. package/dist/legacy/templateSqlViews.js.map +1 -0
  78. package/dist/lexer/sqlTokenTypes.d.ts +67 -0
  79. package/dist/lexer/sqlTokenTypes.d.ts.map +1 -0
  80. package/dist/lexer/sqlTokenTypes.js +2 -0
  81. package/dist/lexer/sqlTokenTypes.js.map +1 -0
  82. package/dist/lexer/sqlTokens.d.ts +53 -0
  83. package/dist/lexer/sqlTokens.d.ts.map +1 -0
  84. package/dist/lexer/sqlTokens.js +267 -0
  85. package/dist/lexer/sqlTokens.js.map +1 -0
  86. package/dist/lexer/templateTagScanner.d.ts +32 -0
  87. package/dist/lexer/templateTagScanner.d.ts.map +1 -0
  88. package/dist/lexer/templateTagScanner.js +69 -0
  89. package/dist/lexer/templateTagScanner.js.map +1 -0
  90. package/dist/orderByAnalyzer.d.ts +5 -0
  91. package/dist/orderByAnalyzer.d.ts.map +1 -1
  92. package/dist/orderByAnalyzer.js +5 -0
  93. package/dist/orderByAnalyzer.js.map +1 -1
  94. package/dist/pagingShape.d.ts +4 -1
  95. package/dist/pagingShape.d.ts.map +1 -1
  96. package/dist/pagingShape.js +4 -1
  97. package/dist/pagingShape.js.map +1 -1
  98. package/dist/sql/analyses/analysisTypes.d.ts +124 -0
  99. package/dist/sql/analyses/analysisTypes.d.ts.map +1 -0
  100. package/dist/sql/analyses/analysisTypes.js +2 -0
  101. package/dist/sql/analyses/analysisTypes.js.map +1 -0
  102. package/dist/sql/analyses/columnAnalyses.d.ts +18 -0
  103. package/dist/sql/analyses/columnAnalyses.d.ts.map +1 -0
  104. package/dist/sql/analyses/columnAnalyses.js +138 -0
  105. package/dist/sql/analyses/columnAnalyses.js.map +1 -0
  106. package/dist/sql/analyses/structureAnalyses.d.ts +31 -0
  107. package/dist/sql/analyses/structureAnalyses.d.ts.map +1 -0
  108. package/dist/sql/analyses/structureAnalyses.js +201 -0
  109. package/dist/sql/analyses/structureAnalyses.js.map +1 -0
  110. package/dist/sql/parser/fromParser.d.ts +45 -0
  111. package/dist/sql/parser/fromParser.d.ts.map +1 -0
  112. package/dist/sql/parser/fromParser.js +342 -0
  113. package/dist/sql/parser/fromParser.js.map +1 -0
  114. package/dist/sql/parser/parseContext.d.ts +72 -0
  115. package/dist/sql/parser/parseContext.d.ts.map +1 -0
  116. package/dist/sql/parser/parseContext.js +197 -0
  117. package/dist/sql/parser/parseContext.js.map +1 -0
  118. package/dist/sql/parser/queryParser.d.ts +45 -0
  119. package/dist/sql/parser/queryParser.d.ts.map +1 -0
  120. package/dist/sql/parser/queryParser.js +267 -0
  121. package/dist/sql/parser/queryParser.js.map +1 -0
  122. package/dist/sql/parser/selectParser.d.ts +47 -0
  123. package/dist/sql/parser/selectParser.d.ts.map +1 -0
  124. package/dist/sql/parser/selectParser.js +353 -0
  125. package/dist/sql/parser/selectParser.js.map +1 -0
  126. package/dist/sql/parser/tailParser.d.ts +25 -0
  127. package/dist/sql/parser/tailParser.d.ts.map +1 -0
  128. package/dist/sql/parser/tailParser.js +180 -0
  129. package/dist/sql/parser/tailParser.js.map +1 -0
  130. package/dist/sql/sqlDiagnosticCodes.d.ts +27 -0
  131. package/dist/sql/sqlDiagnosticCodes.d.ts.map +1 -0
  132. package/dist/sql/sqlDiagnosticCodes.js +25 -0
  133. package/dist/sql/sqlDiagnosticCodes.js.map +1 -0
  134. package/dist/sql/sqlDocument.d.ts +103 -0
  135. package/dist/sql/sqlDocument.d.ts.map +1 -0
  136. package/dist/sql/sqlDocument.js +178 -0
  137. package/dist/sql/sqlDocument.js.map +1 -0
  138. package/dist/sql/sqlExpression.d.ts +74 -0
  139. package/dist/sql/sqlExpression.d.ts.map +1 -0
  140. package/dist/sql/sqlExpression.js +313 -0
  141. package/dist/sql/sqlExpression.js.map +1 -0
  142. package/dist/sql/sqlKeywords.d.ts +38 -0
  143. package/dist/sql/sqlKeywords.d.ts.map +1 -0
  144. package/dist/sql/sqlKeywords.js +85 -0
  145. package/dist/sql/sqlKeywords.js.map +1 -0
  146. package/dist/sql/sqlNodes.d.ts +360 -0
  147. package/dist/sql/sqlNodes.d.ts.map +1 -0
  148. package/dist/sql/sqlNodes.js +2 -0
  149. package/dist/sql/sqlNodes.js.map +1 -0
  150. package/dist/sql/sqlScope.d.ts +108 -0
  151. package/dist/sql/sqlScope.d.ts.map +1 -0
  152. package/dist/sql/sqlScope.js +307 -0
  153. package/dist/sql/sqlScope.js.map +1 -0
  154. package/dist/sql/sqlWalker.d.ts +17 -0
  155. package/dist/sql/sqlWalker.d.ts.map +1 -0
  156. package/dist/sql/sqlWalker.js +113 -0
  157. package/dist/sql/sqlWalker.js.map +1 -0
  158. package/dist/sql/tokenTable.d.ts +58 -0
  159. package/dist/sql/tokenTable.d.ts.map +1 -0
  160. package/dist/sql/tokenTable.js +158 -0
  161. package/dist/sql/tokenTable.js.map +1 -0
  162. package/dist/sql-parser.d.ts +146 -194
  163. package/dist/sql-parser.d.ts.map +1 -1
  164. package/dist/sql-parser.js +173 -1272
  165. package/dist/sql-parser.js.map +1 -1
  166. package/dist/sqlLexer.d.ts +18 -13
  167. package/dist/sqlLexer.d.ts.map +1 -1
  168. package/dist/sqlLexer.js +152 -50
  169. package/dist/sqlLexer.js.map +1 -1
  170. package/dist/sqlShape.d.ts +11 -2
  171. package/dist/sqlShape.d.ts.map +1 -1
  172. package/dist/sqlShape.js +64 -8
  173. package/dist/sqlShape.js.map +1 -1
  174. package/dist/strict/aggregateRenderer.d.ts +28 -0
  175. package/dist/strict/aggregateRenderer.d.ts.map +1 -0
  176. package/dist/strict/aggregateRenderer.js +451 -0
  177. package/dist/strict/aggregateRenderer.js.map +1 -0
  178. package/dist/strict/statementReads.d.ts +34 -0
  179. package/dist/strict/statementReads.d.ts.map +1 -0
  180. package/dist/strict/statementReads.js +252 -0
  181. package/dist/strict/statementReads.js.map +1 -0
  182. package/dist/strict/strictDialect.d.ts +12 -0
  183. package/dist/strict/strictDialect.d.ts.map +1 -0
  184. package/dist/strict/strictDialect.js +37 -0
  185. package/dist/strict/strictDialect.js.map +1 -0
  186. package/dist/strict/strictFragmentValidator.d.ts +68 -0
  187. package/dist/strict/strictFragmentValidator.d.ts.map +1 -0
  188. package/dist/strict/strictFragmentValidator.js +156 -0
  189. package/dist/strict/strictFragmentValidator.js.map +1 -0
  190. package/dist/strict/strictTypes.d.ts +116 -0
  191. package/dist/strict/strictTypes.d.ts.map +1 -0
  192. package/dist/strict/strictTypes.js +2 -0
  193. package/dist/strict/strictTypes.js.map +1 -0
  194. package/dist/strict/treeFacts.d.ts +28 -0
  195. package/dist/strict/treeFacts.d.ts.map +1 -0
  196. package/dist/strict/treeFacts.js +162 -0
  197. package/dist/strict/treeFacts.js.map +1 -0
  198. package/dist/structuralParser.d.ts +2 -0
  199. package/dist/structuralParser.d.ts.map +1 -1
  200. package/dist/structuralParser.js +6 -4
  201. package/dist/structuralParser.js.map +1 -1
  202. package/dist/template/branchEvaluator.d.ts +51 -0
  203. package/dist/template/branchEvaluator.d.ts.map +1 -0
  204. package/dist/template/branchEvaluator.js +194 -0
  205. package/dist/template/branchEvaluator.js.map +1 -0
  206. package/dist/template/branchVariants.d.ts +79 -0
  207. package/dist/template/branchVariants.d.ts.map +1 -0
  208. package/dist/template/branchVariants.js +273 -0
  209. package/dist/template/branchVariants.js.map +1 -0
  210. package/dist/template/compositionParser.d.ts +18 -0
  211. package/dist/template/compositionParser.d.ts.map +1 -0
  212. package/dist/template/compositionParser.js +131 -0
  213. package/dist/template/compositionParser.js.map +1 -0
  214. package/dist/template/compositionPathMatch.d.ts +46 -0
  215. package/dist/template/compositionPathMatch.d.ts.map +1 -0
  216. package/dist/template/compositionPathMatch.js +50 -0
  217. package/dist/template/compositionPathMatch.js.map +1 -0
  218. package/dist/template/compositionReferences.d.ts +26 -0
  219. package/dist/template/compositionReferences.d.ts.map +1 -0
  220. package/dist/template/compositionReferences.js +21 -0
  221. package/dist/template/compositionReferences.js.map +1 -0
  222. package/dist/template/compositionRules.d.ts +42 -0
  223. package/dist/template/compositionRules.d.ts.map +1 -0
  224. package/dist/template/compositionRules.js +132 -0
  225. package/dist/template/compositionRules.js.map +1 -0
  226. package/dist/template/docComments.d.ts +45 -0
  227. package/dist/template/docComments.d.ts.map +1 -0
  228. package/dist/template/docComments.js +115 -0
  229. package/dist/template/docComments.js.map +1 -0
  230. package/dist/template/expressionLexer.d.ts +28 -0
  231. package/dist/template/expressionLexer.d.ts.map +1 -0
  232. package/dist/template/expressionLexer.js +85 -0
  233. package/dist/template/expressionLexer.js.map +1 -0
  234. package/dist/template/expressionParser.d.ts +106 -0
  235. package/dist/template/expressionParser.d.ts.map +1 -0
  236. package/dist/template/expressionParser.js +419 -0
  237. package/dist/template/expressionParser.js.map +1 -0
  238. package/dist/template/expressionTypes.d.ts +111 -0
  239. package/dist/template/expressionTypes.d.ts.map +1 -0
  240. package/dist/template/expressionTypes.js +25 -0
  241. package/dist/template/expressionTypes.js.map +1 -0
  242. package/dist/template/parameterAnalysis.d.ts +81 -0
  243. package/dist/template/parameterAnalysis.d.ts.map +1 -0
  244. package/dist/template/parameterAnalysis.js +130 -0
  245. package/dist/template/parameterAnalysis.js.map +1 -0
  246. package/dist/template/queryLanguage.d.ts +33 -0
  247. package/dist/template/queryLanguage.d.ts.map +1 -0
  248. package/dist/template/queryLanguage.js +56 -0
  249. package/dist/template/queryLanguage.js.map +1 -0
  250. package/dist/template/queryTemplate.d.ts +72 -0
  251. package/dist/template/queryTemplate.d.ts.map +1 -0
  252. package/dist/template/queryTemplate.js +147 -0
  253. package/dist/template/queryTemplate.js.map +1 -0
  254. package/dist/template/sqlPosition.d.ts +24 -0
  255. package/dist/template/sqlPosition.d.ts.map +1 -0
  256. package/dist/template/sqlPosition.js +93 -0
  257. package/dist/template/sqlPosition.js.map +1 -0
  258. package/dist/template/templateNodes.d.ts +114 -0
  259. package/dist/template/templateNodes.d.ts.map +1 -0
  260. package/dist/template/templateNodes.js +38 -0
  261. package/dist/template/templateNodes.js.map +1 -0
  262. package/dist/template/templateTreeBuilder.d.ts +56 -0
  263. package/dist/template/templateTreeBuilder.d.ts.map +1 -0
  264. package/dist/template/templateTreeBuilder.js +302 -0
  265. package/dist/template/templateTreeBuilder.js.map +1 -0
  266. package/dist/template/templateWalker.d.ts +62 -0
  267. package/dist/template/templateWalker.d.ts.map +1 -0
  268. package/dist/template/templateWalker.js +122 -0
  269. package/dist/template/templateWalker.js.map +1 -0
  270. package/dist/template/trailingDocComments.d.ts +35 -0
  271. package/dist/template/trailingDocComments.d.ts.map +1 -0
  272. package/dist/template/trailingDocComments.js +146 -0
  273. package/dist/template/trailingDocComments.js.map +1 -0
  274. package/dist/template/validationTypes.d.ts +77 -0
  275. package/dist/template/validationTypes.d.ts.map +1 -0
  276. package/dist/template/validationTypes.js +2 -0
  277. package/dist/template/validationTypes.js.map +1 -0
  278. package/dist/template/valueRules.d.ts +55 -0
  279. package/dist/template/valueRules.d.ts.map +1 -0
  280. package/dist/template/valueRules.js +238 -0
  281. package/dist/template/valueRules.js.map +1 -0
  282. package/package.json +2 -2
  283. package/dist/ASTDialectAdapter.d.ts +0 -60
  284. package/dist/ASTDialectAdapter.d.ts.map +0 -1
  285. package/dist/ASTDialectAdapter.js +0 -117
  286. package/dist/ASTDialectAdapter.js.map +0 -1
@@ -0,0 +1,252 @@
1
+ import { LexSQL } from '../sqlLexer.js';
2
+ /** The table name a fragment's parse wrapper reads. */
3
+ export const CLAUSE_WRAPPER_TABLE = '__mj_clause_screen';
4
+ /**
5
+ * Every FROM item in a parsed statement, and the number of SELECT nodes. The walk visits every
6
+ * property of every node, so it finds a FROM list wherever the grammar puts one: a subquery in a
7
+ * CASE branch, HAVING, a window's ORDER BY or PARTITION BY, a function argument, IN, EXISTS, a
8
+ * set operation or a CTE body. Every FROM item is kept, even when its alias repeats. Names the
9
+ * fallback parse renamed are read back through {@link ReadableParse.IdentifierAliases}, which
10
+ * holds only names the parser put in the tree. `skip` is a FROM item node of the tree to leave out.
11
+ *
12
+ * Each FROM item records whether it reads a CTE in scope there. A WITH covers its own SELECT,
13
+ * everything below it, and the following set-operation branches unless its SELECT is a
14
+ * parenthesized branch. A CTE body sees the CTEs before it, itself on SQL Server, and every CTE of
15
+ * a PostgreSQL WITH RECURSIVE list. Names match by the dialect's identifier rules. The walk keeps a
16
+ * count of the CTEs of each name in scope as it goes, so its time is linear in the tree.
17
+ */
18
+ export function CollectReads(parser, skip) {
19
+ const aliases = parser.IdentifierAliases;
20
+ const walk = {
21
+ Reads: { Relations: [], SelectCount: 0 },
22
+ Visited: new WeakSet(),
23
+ Aliases: aliases,
24
+ Names: cteNameRules(parser, aliases),
25
+ Skip: skip,
26
+ InScope: new Map(),
27
+ };
28
+ visitNode(walk, parser.AST);
29
+ return walk.Reads;
30
+ }
31
+ /** The FROM item of a fragment's parse wrapper: the root statement's only FROM item, when it is the wrapper table. */
32
+ export function WrapperFromItem(ast) {
33
+ const root = Array.isArray(ast) ? ast[0] : ast;
34
+ const from = root && typeof root === 'object' ? root.from : undefined;
35
+ if (!Array.isArray(from) || from.length !== 1 || !from[0] || typeof from[0] !== 'object')
36
+ return undefined;
37
+ const item = from[0];
38
+ const isWrapper = identifierText(item.table, null).toLowerCase() === CLAUSE_WRAPPER_TABLE &&
39
+ !identifierText(item.db, null) &&
40
+ !identifierText(item.schema, null);
41
+ return isWrapper ? item : undefined;
42
+ }
43
+ /** Removes the bracket, double-quote or backtick quoting around one identifier. */
44
+ export function StripIdentifierQuoting(name) {
45
+ if (!name)
46
+ return '';
47
+ return name.replace(/^\[|\]$/g, '').replace(/^"|"$/g, '').replace(/^`|`$/g, '');
48
+ }
49
+ /** Visits one node of the parse tree. */
50
+ function visitNode(walk, node) {
51
+ if (!node || typeof node !== 'object' || walk.Visited.has(node))
52
+ return;
53
+ walk.Visited.add(node);
54
+ if (Array.isArray(node)) {
55
+ node.forEach((child) => visitNode(walk, child));
56
+ return;
57
+ }
58
+ const record = node;
59
+ if (record.type === 'select') {
60
+ visitSelect(walk, record);
61
+ return;
62
+ }
63
+ Object.values(record).forEach((child) => visitNode(walk, child));
64
+ }
65
+ /**
66
+ * Visits a SELECT node: counts it, adds its FROM items, and visits its CTE bodies and every
67
+ * other property with the CTE names each one can see. The CTEs of its WITH are in scope from
68
+ * their place in the list until the walk leaves the SELECT.
69
+ */
70
+ function visitSelect(walk, select) {
71
+ walk.Reads.SelectCount++;
72
+ const ctes = Array.isArray(select.with) ? select.with : [];
73
+ const declared = ctes.map((cte) => walk.Names.DeclaredName(cteNameNode(cte)));
74
+ enterScope(walk, declared);
75
+ addFromItems(walk, select.from);
76
+ leaveScope(walk, declared);
77
+ visitCTEBodies(walk, ctes, declared);
78
+ const ownBranchOnly = ctes.length > 0 && select.parentheses_symbol === true;
79
+ for (const [key, child] of Object.entries(select)) {
80
+ if (key === 'with')
81
+ continue;
82
+ const outsideWith = key === '_next' && ownBranchOnly;
83
+ if (outsideWith)
84
+ leaveScope(walk, declared);
85
+ visitNode(walk, child);
86
+ if (outsideWith)
87
+ enterScope(walk, declared);
88
+ }
89
+ leaveScope(walk, declared);
90
+ }
91
+ /**
92
+ * Visits the bodies of one WITH list, whose CTE names are `declared`. Body `i` sees the CTEs
93
+ * before it, itself too on SQL Server, and every CTE of a RECURSIVE list. Each CTE comes into
94
+ * scope once, at its place in the list, and all of them are in scope afterwards.
95
+ */
96
+ function visitCTEBodies(walk, ctes, declared) {
97
+ const recursive = ctes.some((cte) => isRecursiveCTE(cte));
98
+ let entered = 0;
99
+ ctes.forEach((cte, i) => {
100
+ const visible = recursive ? ctes.length : walk.Names.BodySeesItself ? i + 1 : i;
101
+ for (; entered < visible; entered++)
102
+ countName(walk, declared[entered], 1);
103
+ visitNode(walk, cte);
104
+ });
105
+ for (; entered < ctes.length; entered++)
106
+ countName(walk, declared[entered], 1);
107
+ }
108
+ /** Adds the relation each FROM item names, marking an unqualified reference to a CTE in scope. */
109
+ function addFromItems(walk, from) {
110
+ const items = Array.isArray(from) ? from : from ? [from] : [];
111
+ for (const item of items) {
112
+ if (!item || typeof item !== 'object' || item === walk.Skip)
113
+ continue;
114
+ const relation = relationOf(item, walk.Aliases);
115
+ if (!relation)
116
+ continue;
117
+ const name = relation.TableName && !relation.SchemaName ? walk.Names.ReferenceName(relation.TableName) : null;
118
+ relation.IsCTEReference = name !== null && (walk.InScope.get(name) ?? 0) > 0;
119
+ walk.Reads.Relations.push(relation);
120
+ }
121
+ }
122
+ /** Brings each readable name among `names` into scope once more. */
123
+ function enterScope(walk, names) {
124
+ for (const name of names)
125
+ countName(walk, name, 1);
126
+ }
127
+ /** Takes each readable name among `names` out of scope once. */
128
+ function leaveScope(walk, names) {
129
+ for (const name of names)
130
+ countName(walk, name, -1);
131
+ }
132
+ /**
133
+ * Adds `delta` to the in-scope count of `name` when it is readable. A count that drops to zero
134
+ * stays in the map: in V8, each delete of a key leaves an entry that later lookups of that key
135
+ * step over until the map is rebuilt.
136
+ */
137
+ function countName(walk, name, delta) {
138
+ if (name)
139
+ walk.InScope.set(name, (walk.InScope.get(name) ?? 0) + delta);
140
+ }
141
+ /** The name node of one item of a `with` list. */
142
+ function cteNameNode(cte) {
143
+ return cte && typeof cte === 'object' ? cte.name : undefined;
144
+ }
145
+ /** True for the item of a `with` list that carries RECURSIVE (the parser marks the first). */
146
+ function isRecursiveCTE(cte) {
147
+ return !!cte && typeof cte === 'object' && cte.recursive === true;
148
+ }
149
+ /**
150
+ * How the parser's dialect matches a FROM item to a CTE. SQL Server ignores case, and a CTE
151
+ * body reads its own CTE. PostgreSQL folds an unquoted name to lower case and matches a quoted
152
+ * one exactly ({@link postgresNameRules}). A dialect that quotes identifiers any other way
153
+ * matches no CTE.
154
+ */
155
+ function cteNameRules(parser, aliases) {
156
+ const quote = parser.Dialect.QuoteIdentifier('x');
157
+ if (quote.startsWith('[')) {
158
+ return {
159
+ DeclaredName: (node) => asciiLower(identifierText(node, aliases)) || null,
160
+ ReferenceName: (text) => asciiLower(text) || null,
161
+ BodySeesItself: true,
162
+ };
163
+ }
164
+ if (quote.startsWith('"'))
165
+ return postgresNameRules(parser, aliases);
166
+ return { DeclaredName: () => null, ReferenceName: () => null, BodySeesItself: false };
167
+ }
168
+ /**
169
+ * PostgreSQL's CTE name rules. A CTE name node says whether it was quoted. A FROM item's name
170
+ * does not, so its quoting comes from the SQL's tokens: a name with upper-case letters that the
171
+ * SQL writes only quoted is exact, one it writes only unquoted folds to lower case, and one it
172
+ * writes both ways, or not as a token at all, matches no CTE.
173
+ */
174
+ function postgresNameRules(parser, aliases) {
175
+ const quoted = new Set();
176
+ const bare = new Set();
177
+ for (const token of LexSQL(parser.SQL, parser.Dialect)) {
178
+ if (token.Kind === 'word')
179
+ bare.add(token.Text);
180
+ else if (token.Kind === 'identifier' && token.Text.startsWith('"'))
181
+ quoted.add(token.Text.slice(1, -1).split('""').join('"'));
182
+ }
183
+ const referenceName = (text) => {
184
+ const folded = asciiLower(text);
185
+ if (folded === text)
186
+ return text || null;
187
+ if (quoted.has(text) && !bare.has(text))
188
+ return text;
189
+ if (bare.has(text) && !quoted.has(text))
190
+ return folded;
191
+ return null;
192
+ };
193
+ const declaredName = (node) => {
194
+ const name = node && typeof node === 'object' ? node : null;
195
+ if (typeof name?.value === 'string' && name.type === 'double_quote_string')
196
+ return name.value || null;
197
+ if (typeof name?.value === 'string' && name.type === 'default')
198
+ return asciiLower(name.value) || null;
199
+ return referenceName(identifierText(node, aliases));
200
+ };
201
+ return { DeclaredName: declaredName, ReferenceName: referenceName, BodySeesItself: false };
202
+ }
203
+ /** `text` with ASCII upper-case letters in lower case: PostgreSQL's folding of an unquoted name. */
204
+ function asciiLower(text) {
205
+ return text.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
206
+ }
207
+ /**
208
+ * The relation one FROM item names. A derived table and a VALUES list name none; the walk
209
+ * reaches any subquery inside them.
210
+ */
211
+ function relationOf(item, aliases) {
212
+ const table = identifierText(item.table, aliases);
213
+ if (table) {
214
+ const database = identifierText(item.db, aliases);
215
+ const schema = identifierText(item.schema, aliases);
216
+ return { SchemaName: schema ? `${database}.${schema}` : database, TableName: table, FunctionName: '', IsCTEReference: false };
217
+ }
218
+ const expr = item.expr && typeof item.expr === 'object' ? item.expr : null;
219
+ if (expr?.ast || expr?.type === 'values')
220
+ return null;
221
+ if (expr?.type === 'function')
222
+ return functionRelation(expr.name, aliases);
223
+ return { SchemaName: '', TableName: '', FunctionName: '', IsCTEReference: false };
224
+ }
225
+ /** The relation a table function names. Leading name parts join the schema, so a qualified name never matches a built-in. */
226
+ function functionRelation(name, aliases) {
227
+ if (typeof name === 'string')
228
+ return { SchemaName: '', TableName: '', FunctionName: name, IsCTEReference: false };
229
+ const record = name && typeof name === 'object' ? name : {};
230
+ const parts = Array.isArray(record.name) ? record.name.map((part) => identifierText(part, aliases)) : [];
231
+ const qualifiers = [identifierText(record.schema, aliases), ...parts.slice(0, -1)].filter(Boolean);
232
+ return { SchemaName: qualifiers.join('.'), TableName: '', FunctionName: parts[parts.length - 1] ?? '', IsCTEReference: false };
233
+ }
234
+ /**
235
+ * The text of an identifier node (a string, or the PostgreSQL grammar's `{ value }` node), with
236
+ * a name the fallback parse renamed read back from `aliases`; empty when unreadable.
237
+ */
238
+ function identifierText(value, aliases) {
239
+ let text = '';
240
+ if (typeof value === 'string') {
241
+ text = value;
242
+ }
243
+ else if (value && typeof value === 'object') {
244
+ const node = value;
245
+ if (typeof node.value === 'string')
246
+ text = node.value;
247
+ else if (node.expr)
248
+ return identifierText(node.expr, aliases);
249
+ }
250
+ return StripIdentifierQuoting(aliases?.get(text) ?? text);
251
+ }
252
+ //# sourceMappingURL=statementReads.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"statementReads.js","s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AAE,OAA2C;IAC/E,IAAI,IAAI,GAAG,EAAE,CAAC;IACd,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC5B,IAAI,GAAG,KAAK,CAAC;IACjB,CAAC;SAAM,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC5C,MAAM,IAAI,GAAG,KAA4C,CAAC;QAC1D,IAAI,OAAO,IAAI,CAAC,KAAK,KAAK,QAAQ;YAAE,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC;aACjD,IAAI,IAAI,CAAC,IAAI;YAAE,OAAO,cAAc,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;IACD,OAAO,sBAAsB,CAAC,OAAO,EAAE,GAAG,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC;AAC9D,CAAC"}
@@ -0,0 +1,12 @@
1
+ import type { SQLParserDialect } from '@memberjunction/sql-dialect';
2
+ /**
3
+ * The strict parser's grammar for a dialect: its grammar facet's `ParserGrammar` when it has the
4
+ * facet, otherwise its `ParserDialect` string as given. `null` when the facet names no grammar.
5
+ */
6
+ export declare function StrictGrammarOf(dialect: SQLParserDialect): string | null;
7
+ /**
8
+ * The dialect the parser reads with for `grammar`: `dialect` itself when it already names that
9
+ * grammar, otherwise a view of it that names `grammar` and delegates every other member.
10
+ */
11
+ export declare function StrictParsingDialect(dialect: SQLParserDialect, grammar: string): SQLParserDialect;
12
+ //# sourceMappingURL=strictDialect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strictDialect.d.ts","sourceRoot":"","sources":["../../src/strict/strictDialect.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAkB,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAYpF;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,gBAAgB,GAAG,MAAM,GAAG,IAAI,CAMxE;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,GAAG,gBAAgB,CAYjG"}
@@ -0,0 +1,37 @@
1
+ /** True when `dialect` carries a grammar facet that names its parser grammar (or `null`). */
2
+ function hasGrammarFacet(dialect) {
3
+ if (!('Grammar' in dialect))
4
+ return false;
5
+ const grammar = dialect.Grammar;
6
+ return typeof grammar === 'object' && grammar !== null && 'ParserGrammar' in grammar;
7
+ }
8
+ /**
9
+ * The strict parser's grammar for a dialect: its grammar facet's `ParserGrammar` when it has the
10
+ * facet, otherwise its `ParserDialect` string as given. `null` when the facet names no grammar.
11
+ */
12
+ export function StrictGrammarOf(dialect) {
13
+ if (hasGrammarFacet(dialect)) {
14
+ const grammar = dialect.Grammar.ParserGrammar;
15
+ return typeof grammar === 'string' && grammar.length > 0 ? grammar : null;
16
+ }
17
+ return dialect.ParserDialect;
18
+ }
19
+ /**
20
+ * The dialect the parser reads with for `grammar`: `dialect` itself when it already names that
21
+ * grammar, otherwise a view of it that names `grammar` and delegates every other member.
22
+ */
23
+ export function StrictParsingDialect(dialect, grammar) {
24
+ if (dialect.ParserDialect === grammar)
25
+ return dialect;
26
+ return {
27
+ ParserDialect: grammar,
28
+ QuoteIdentifier: (name) => dialect.QuoteIdentifier(name),
29
+ AllowsOrderByInCTE: dialect.AllowsOrderByInCTE,
30
+ DefaultPagingOrderBy: dialect.DefaultPagingOrderBy,
31
+ SupportsEscapeStringLiterals: dialect.SupportsEscapeStringLiterals,
32
+ SupportsDollarQuotedStrings: dialect.SupportsDollarQuotedStrings,
33
+ QueryHintKeyword: dialect.QueryHintKeyword,
34
+ CallerSQLForbiddenFunctions: dialect.CallerSQLForbiddenFunctions,
35
+ };
36
+ }
37
+ //# sourceMappingURL=strictDialect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strictDialect.js","sourceRoot":"","sources":["../../src/strict/strictDialect.ts"],"names":[],"mappings":"AAKA,6FAA6F;AAC7F,SAAS,eAAe,CAAC,OAAyB;IAC9C,IAAI,CAAC,CAAC,SAAS,IAAI,OAAO,CAAC;QAAE,OAAO,KAAK,CAAC;IAC1C,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;IAChC,OAAO,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI,IAAI,eAAe,IAAI,OAAO,CAAC;AACzF,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,eAAe,CAAC,OAAyB;IACrD,IAAI,eAAe,CAAC,OAAO,CAAC,EAAE,CAAC;QAC3B,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC;QAC9C,OAAO,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;IAC9E,CAAC;IACD,OAAO,OAAO,CAAC,aAAa,CAAC;AACjC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAAC,OAAyB,EAAE,OAAe;IAC3E,IAAI,OAAO,CAAC,aAAa,KAAK,OAAO;QAAE,OAAO,OAAO,CAAC;IACtD,OAAO;QACH,aAAa,EAAE,OAAO;QACtB,eAAe,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,OAAO,CAAC,eAAe,CAAC,IAAI,CAAC;QAChE,kBAAkB,EAAE,OAAO,CAAC,kBAAkB;QAC9C,oBAAoB,EAAE,OAAO,CAAC,oBAAoB;QAClD,4BAA4B,EAAE,OAAO,CAAC,4BAA4B;QAClE,2BAA2B,EAAE,OAAO,CAAC,2BAA2B;QAChE,gBAAgB,EAAE,OAAO,CAAC,gBAAgB;QAC1C,2BAA2B,EAAE,OAAO,CAAC,2BAA2B;KACnE,CAAC;AACN,CAAC"}
@@ -0,0 +1,68 @@
1
+ import type { SQLParserDialect } from '@memberjunction/sql-dialect';
2
+ import { SQLParser } from '../sql-parser.js';
3
+ import type { StrictAggregateResult, StrictFilterOptions, StrictParseOptions, StrictStatementReads, StrictValidationResult } from './strictTypes.js';
4
+ /**
5
+ * SECURITY — the strict, fail-closed reader for SQL that untrusted callers supply: a WHERE or
6
+ * ORDER BY fragment, an aggregate expression, or a whole read statement. Text the dialect's grammar
7
+ * cannot read is refused, never guessed at, so use it only where refusing unparseable input is
8
+ * correct, and never to rewrite SQL MJ owns.
9
+ *
10
+ * The grammar is the dialect's grammar facet (`Grammar.ParserGrammar`: TransactSQL, PostgresQL,
11
+ * MySQL, Snowflake, Hive), or the `ParserDialect` of a dialect without the facet. A dialect whose
12
+ * facet names no grammar is refused (`'NoGrammar'`).
13
+ *
14
+ * Every result carries the facts a screen decides on (statement kind, top-level and nested
15
+ * writes, the relations read, the column references) as plain MJ types, so a caller never reads
16
+ * a parse tree.
17
+ */
18
+ export declare class StrictFragmentValidator {
19
+ /**
20
+ * Reads a WHERE fragment as the predicate of `SELECT 1 FROM __mj_clause_screen WHERE …`. With
21
+ * {@link StrictParseOptions.CollectReads}, the reads leave out that wrapper's own FROM item.
22
+ */
23
+ static ValidateFilter(filter: string, dialect: SQLParserDialect, options?: StrictFilterOptions): StrictValidationResult;
24
+ /**
25
+ * Reads an ORDER BY list as the ORDER BY of `SELECT 1 FROM __mj_clause_screen ORDER BY …`.
26
+ * With {@link StrictParseOptions.CollectReads}, the reads leave out that wrapper's own FROM item.
27
+ */
28
+ static ValidateOrderBy(orderBy: string, dialect: SQLParserDialect, options?: StrictParseOptions): StrictValidationResult;
29
+ /** Reads a whole statement, which is valid when it is one plain read-only SELECT. */
30
+ static ValidateReadOnlyStatement(sql: string, dialect: SQLParserDialect, options?: StrictParseOptions): StrictValidationResult;
31
+ /**
32
+ * Whether `expression` may be placed as one item of an aggregate SELECT list —
33
+ * `SELECT <expression> AS [Agg_0] FROM <entity view> WHERE …` — for an entity whose columns are
34
+ * `columns`, and the SQL to run for it: exactly one aggregate call (COUNT, SUM, AVG, MIN, MAX,
35
+ * STDEV, VAR, STRING_AGG, …) over the given columns, constants, operators, CASE, CAST and a
36
+ * fixed set of pure scalar functions. The caller's text is never run:
37
+ * {@link StrictAggregateResult.SQL} is rebuilt from the checked parse tree with the dialect's
38
+ * quoting, so the database runs exactly the expression that was checked.
39
+ */
40
+ static ValidateAggregateExpression(expression: string, dialect: SQLParserDialect, columns: Iterable<string>): StrictAggregateResult;
41
+ /**
42
+ * Every FROM item an already-parsed statement reads, and the number of SELECTs in its tree,
43
+ * walking the whole tree with CTE scope. `skip` is a FROM item node of `parser`'s own tree to
44
+ * leave out.
45
+ */
46
+ static CollectStatementReads(parser: SQLParser, skip?: object): StrictStatementReads;
47
+ /**
48
+ * True when a parse tree (such as `SQLParser.AST`) holds a write, DDL or DCL statement at any
49
+ * depth. Any other value holds none.
50
+ */
51
+ static ContainsWriteNode(tree: unknown): boolean;
52
+ /** Validates a fragment already placed in its parse wrapper, whose own FROM item the reads leave out. */
53
+ private static validateWrapped;
54
+ /**
55
+ * Parses `sql` with the dialect's grammar: through a `SQLParser`, with its fallbacks, or, when
56
+ * fallbacks are not allowed, with the single direct reading `SQLParser.ParseSQL` makes.
57
+ */
58
+ private static parse;
59
+ /** The direct reading of `sql`, with no fallback; null when it does not parse. */
60
+ private static directTree;
61
+ /** The result for one parse; `skipWrapper` leaves the fragment wrapper's FROM item out of the reads. */
62
+ private static resultOf;
63
+ /** The first refusal a parsed text earns, in the order {@link StrictRefusal} lists them. */
64
+ private static refusalOf;
65
+ /** The result for text that did not parse. */
66
+ private static unparsed;
67
+ }
68
+ //# sourceMappingURL=strictFragmentValidator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strictFragmentValidator.d.ts","sourceRoot":"","sources":["../../src/strict/strictFragmentValidator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,EAAE,SAAS,EAAyB,MAAM,kBAAkB,CAAC;AAIpE,OAAO,KAAK,EACR,qBAAqB,EACrB,mBAAmB,EACnB,kBAAkB,EAElB,oBAAoB,EACpB,sBAAsB,EACzB,MAAM,kBAAkB,CAAC;AA2B1B;;;;;;;;;;;;;GAaG;AACH,qBAAa,uBAAuB;IAChC;;;OAGG;WACW,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,sBAAsB;IAK9H;;;OAGG;WACW,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,OAAO,CAAC,EAAE,kBAAkB,GAAG,sBAAsB;IAI/H,qFAAqF;WACvE,yBAAyB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,OAAO,CAAC,EAAE,kBAAkB,GAAG,sBAAsB;IAIrI;;;;;;;;OAQG;WACW,2BAA2B,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,qBAAqB;IAI1I;;;;OAIG;WACW,qBAAqB,CAAC,MAAM,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,oBAAoB;IAI3F;;;OAGG;WACW,iBAAiB,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO;IAIvD,yGAAyG;IACzG,OAAO,CAAC,MAAM,CAAC,eAAe;IAI9B;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,KAAK;IAQpB,kFAAkF;IAClF,OAAO,CAAC,MAAM,CAAC,UAAU;IAazB,wGAAwG;IACxG,OAAO,CAAC,MAAM,CAAC,QAAQ;IAuBvB,4FAA4F;IAC5F,OAAO,CAAC,MAAM,CAAC,SAAS;IAOxB,8CAA8C;IAC9C,OAAO,CAAC,MAAM,CAAC,QAAQ;CAe1B"}
@@ -0,0 +1,156 @@
1
+ import { SQLParser } from '../sql-parser.js';
2
+ import { RenderAggregateExpression } from './aggregateRenderer.js';
3
+ import { CLAUSE_WRAPPER_TABLE, CollectReads, WrapperFromItem } from './statementReads.js';
4
+ import { StrictGrammarOf, StrictParsingDialect } from './strictDialect.js';
5
+ import { IsSingleTypedStatement, TopLevelHasWriteStatement, TopLevelStatementKind, TreeContainsWriteNode, WhereColumnReferences, } from './treeFacts.js';
6
+ /** The sentence each refusal reports. */
7
+ const REFUSAL_REASONS = {
8
+ NoGrammar: 'the dialect has no grammar to check the SQL with',
9
+ Unparseable: 'the SQL could not be parsed',
10
+ WriteStatement: 'the SQL contains a write, DDL or permission statement',
11
+ NotPlainSelect: 'the SQL is not a single plain SELECT',
12
+ NestedWrite: 'the SQL contains a write or DDL statement nested in a CTE or subquery',
13
+ };
14
+ /**
15
+ * SECURITY — the strict, fail-closed reader for SQL that untrusted callers supply: a WHERE or
16
+ * ORDER BY fragment, an aggregate expression, or a whole read statement. Text the dialect's grammar
17
+ * cannot read is refused, never guessed at, so use it only where refusing unparseable input is
18
+ * correct, and never to rewrite SQL MJ owns.
19
+ *
20
+ * The grammar is the dialect's grammar facet (`Grammar.ParserGrammar`: TransactSQL, PostgresQL,
21
+ * MySQL, Snowflake, Hive), or the `ParserDialect` of a dialect without the facet. A dialect whose
22
+ * facet names no grammar is refused (`'NoGrammar'`).
23
+ *
24
+ * Every result carries the facts a screen decides on (statement kind, top-level and nested
25
+ * writes, the relations read, the column references) as plain MJ types, so a caller never reads
26
+ * a parse tree.
27
+ */
28
+ export class StrictFragmentValidator {
29
+ /**
30
+ * Reads a WHERE fragment as the predicate of `SELECT 1 FROM __mj_clause_screen WHERE …`. With
31
+ * {@link StrictParseOptions.CollectReads}, the reads leave out that wrapper's own FROM item.
32
+ */
33
+ static ValidateFilter(filter, dialect, options) {
34
+ const body = options?.Placement === 'AsWritten' ? filter : `(${filter})`;
35
+ return StrictFragmentValidator.validateWrapped(`SELECT 1 FROM ${CLAUSE_WRAPPER_TABLE} WHERE ${body}`, dialect, options);
36
+ }
37
+ /**
38
+ * Reads an ORDER BY list as the ORDER BY of `SELECT 1 FROM __mj_clause_screen ORDER BY …`.
39
+ * With {@link StrictParseOptions.CollectReads}, the reads leave out that wrapper's own FROM item.
40
+ */
41
+ static ValidateOrderBy(orderBy, dialect, options) {
42
+ return StrictFragmentValidator.validateWrapped(`SELECT 1 FROM ${CLAUSE_WRAPPER_TABLE} ORDER BY ${orderBy}`, dialect, options);
43
+ }
44
+ /** Reads a whole statement, which is valid when it is one plain read-only SELECT. */
45
+ static ValidateReadOnlyStatement(sql, dialect, options) {
46
+ return StrictFragmentValidator.resultOf(StrictFragmentValidator.parse(sql, dialect, options), options, false);
47
+ }
48
+ /**
49
+ * Whether `expression` may be placed as one item of an aggregate SELECT list —
50
+ * `SELECT <expression> AS [Agg_0] FROM <entity view> WHERE …` — for an entity whose columns are
51
+ * `columns`, and the SQL to run for it: exactly one aggregate call (COUNT, SUM, AVG, MIN, MAX,
52
+ * STDEV, VAR, STRING_AGG, …) over the given columns, constants, operators, CASE, CAST and a
53
+ * fixed set of pure scalar functions. The caller's text is never run:
54
+ * {@link StrictAggregateResult.SQL} is rebuilt from the checked parse tree with the dialect's
55
+ * quoting, so the database runs exactly the expression that was checked.
56
+ */
57
+ static ValidateAggregateExpression(expression, dialect, columns) {
58
+ return RenderAggregateExpression(expression, dialect, columns);
59
+ }
60
+ /**
61
+ * Every FROM item an already-parsed statement reads, and the number of SELECTs in its tree,
62
+ * walking the whole tree with CTE scope. `skip` is a FROM item node of `parser`'s own tree to
63
+ * leave out.
64
+ */
65
+ static CollectStatementReads(parser, skip) {
66
+ return CollectReads(parser, skip);
67
+ }
68
+ /**
69
+ * True when a parse tree (such as `SQLParser.AST`) holds a write, DDL or DCL statement at any
70
+ * depth. Any other value holds none.
71
+ */
72
+ static ContainsWriteNode(tree) {
73
+ return TreeContainsWriteNode(tree);
74
+ }
75
+ /** Validates a fragment already placed in its parse wrapper, whose own FROM item the reads leave out. */
76
+ static validateWrapped(wrapped, dialect, options) {
77
+ return StrictFragmentValidator.resultOf(StrictFragmentValidator.parse(wrapped, dialect, options), options, true);
78
+ }
79
+ /**
80
+ * Parses `sql` with the dialect's grammar: through a `SQLParser`, with its fallbacks, or, when
81
+ * fallbacks are not allowed, with the single direct reading `SQLParser.ParseSQL` makes.
82
+ */
83
+ static parse(sql, dialect, options) {
84
+ const grammar = StrictGrammarOf(dialect);
85
+ if (grammar === null)
86
+ return { SQL: sql, Tree: null, Refusal: 'NoGrammar' };
87
+ const parsing = StrictParsingDialect(dialect, grammar);
88
+ const tree = options?.AllowFallbackParse === false ? StrictFragmentValidator.directTree(sql, parsing) : new SQLParser(sql, parsing);
89
+ return tree && tree.AST !== null ? { SQL: sql, Tree: tree, Refusal: null } : { SQL: sql, Tree: null, Refusal: 'Unparseable' };
90
+ }
91
+ /** The direct reading of `sql`, with no fallback; null when it does not parse. */
92
+ static directTree(sql, dialect) {
93
+ const ast = SQLParser.ParseSQL(sql, dialect);
94
+ if (ast === null)
95
+ return null;
96
+ return {
97
+ AST: ast,
98
+ IdentifierAliases: null,
99
+ Dialect: dialect,
100
+ SQL: sql,
101
+ StatementKind: TopLevelStatementKind(ast),
102
+ HasWriteStatement: TopLevelHasWriteStatement(ast),
103
+ };
104
+ }
105
+ /** The result for one parse; `skipWrapper` leaves the fragment wrapper's FROM item out of the reads. */
106
+ static resultOf(parse, options, skipWrapper) {
107
+ if (parse.Tree === null)
108
+ return StrictFragmentValidator.unparsed(parse.SQL, parse.Refusal);
109
+ const tree = parse.Tree;
110
+ const facts = {
111
+ StatementKind: tree.StatementKind,
112
+ HasWriteStatement: tree.HasWriteStatement,
113
+ ContainsNestedWrite: TreeContainsWriteNode(tree.AST),
114
+ IsSingleTypedStatement: IsSingleTypedStatement(tree.AST),
115
+ };
116
+ const refusal = StrictFragmentValidator.refusalOf(facts.HasWriteStatement, facts.StatementKind === 'select', facts.ContainsNestedWrite);
117
+ const collectReads = refusal === null && options?.CollectReads === true;
118
+ return {
119
+ IsValid: refusal === null,
120
+ Refusal: refusal,
121
+ Reason: refusal === null ? null : REFUSAL_REASONS[refusal],
122
+ ParsedSQL: parse.SQL,
123
+ Parsed: true,
124
+ ...facts,
125
+ Reads: collectReads ? CollectReads(tree, skipWrapper ? WrapperFromItem(tree.AST) : undefined) : null,
126
+ ColumnReferences: options?.CollectColumnReferences === true ? WhereColumnReferences(tree.AST) : null,
127
+ };
128
+ }
129
+ /** The first refusal a parsed text earns, in the order {@link StrictRefusal} lists them. */
130
+ static refusalOf(hasWrite, isPlainSelect, nestedWrite) {
131
+ if (hasWrite)
132
+ return 'WriteStatement';
133
+ if (!isPlainSelect)
134
+ return 'NotPlainSelect';
135
+ if (nestedWrite)
136
+ return 'NestedWrite';
137
+ return null;
138
+ }
139
+ /** The result for text that did not parse. */
140
+ static unparsed(sql, refusal) {
141
+ return {
142
+ IsValid: false,
143
+ Refusal: refusal,
144
+ Reason: REFUSAL_REASONS[refusal],
145
+ ParsedSQL: sql,
146
+ Parsed: false,
147
+ StatementKind: 'other',
148
+ HasWriteStatement: false,
149
+ ContainsNestedWrite: false,
150
+ IsSingleTypedStatement: false,
151
+ Reads: null,
152
+ ColumnReferences: null,
153
+ };
154
+ }
155
+ }
156
+ //# sourceMappingURL=strictFragmentValidator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strictFragmentValidator.js","sourceRoot":"","sources":["../../src/strict/strictFragmentValidator.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAyB,MAAM,kBAAkB,CAAC;AACpE,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,YAAY,EAAE,eAAe,EAAsB,MAAM,qBAAqB,CAAC;AAC9G,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAS3E,OAAO,EACH,sBAAsB,EACtB,yBAAyB,EACzB,qBAAqB,EACrB,qBAAqB,EACrB,qBAAqB,GACxB,MAAM,gBAAgB,CAAC;AAExB,yCAAyC;AACzC,MAAM,eAAe,GAA4C;IAC7D,SAAS,EAAE,kD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