@memberjunction/sql-parser 6.2.0-edge.5 → 6.2.0-edge.7

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,96 @@
1
+ /**
2
+ * Every diagnostic code the MJ Query language reports, with the rule it stands for. Codes are
3
+ * stable: a code is never renamed or reused for another rule. `guides/MJ_QUERY_LANGUAGE.md`
4
+ * documents each one with an example and its fix.
5
+ */
6
+ export declare const MJQueryDiagnosticCodes: {
7
+ /** A `{{`, `{%` or `{#` with no closing `}}`, `%}` or `#}`. */
8
+ readonly UnclosedTag: "MJQ_UNCLOSED_TAG";
9
+ /** A template tag inside a SQL string literal. */
10
+ readonly TagInStringLiteral: "MJQ_TAG_IN_STRING_LITERAL";
11
+ /** A template tag inside a SQL quoted identifier. */
12
+ readonly TagInQuotedIdentifier: "MJQ_TAG_IN_QUOTED_IDENTIFIER";
13
+ /** Info: a template tag inside a SQL comment, which is inert (comments are removed before rendering). */
14
+ readonly ExpressionInComment: "MJQ_EXPRESSION_IN_COMMENT";
15
+ /** An `{% if %}` or `{% for %}` with no `{% endif %}` / `{% endfor %}`. */
16
+ readonly UnclosedBlock: "MJQ_UNCLOSED_BLOCK";
17
+ /** An `{% elif %}`, `{% else %}`, `{% endif %}` or `{% endfor %}` with no block to belong to. */
18
+ readonly UnexpectedTag: "MJQ_UNEXPECTED_TAG";
19
+ /** A tag body that does not parse. */
20
+ readonly Syntax: "MJQ_SYNTAX";
21
+ /** A block tag outside the allow-list (`macro`, `include`, `import`, `extends`, `block`, `call`, `filter`, `raw`, …). */
22
+ readonly UnsupportedTag: "MJQ_UNSUPPORTED_TAG";
23
+ /** A function or method call in an expression. */
24
+ readonly FunctionCall: "MJQ_FUNCTION_CALL";
25
+ /** A subscript (`x[0]`, `x['k']`) in an expression. */
26
+ readonly Subscript: "MJQ_SUBSCRIPT";
27
+ /**
28
+ * No longer reported: the inline `a if b else c` is part of the language. The code is kept
29
+ * so it is never reused for another rule.
30
+ */
31
+ readonly InlineIf: "MJQ_INLINE_IF";
32
+ /** Attribute access other than `Context.<Token>`, `loop.<member>` and `<name>.length`. */
33
+ readonly MemberAccess: "MJQ_MEMBER_ACCESS";
34
+ /** An operator outside the grammar (`in`, `is`, `~`, `**`, `//`, list or object literals). */
35
+ readonly UnsupportedOperator: "MJQ_UNSUPPORTED_OPERATOR";
36
+ /** An operator inside a `{{ }}` hole. */
37
+ readonly ArithmeticInHole: "MJQ_ARITHMETIC_IN_HOLE";
38
+ /** A `{{ }}` hole that does not start from a parameter, a `Context` token or a loop value. */
39
+ readonly HoleNotAValue: "MJQ_HOLE_NOT_A_VALUE";
40
+ /** A filter that is not one of the MJ SQL filters or `default`. */
41
+ readonly UnknownFilter: "MJQ_UNKNOWN_FILTER";
42
+ /** A `default(…)` whose argument is not a literal. */
43
+ readonly DefaultNotLiteral: "MJQ_DEFAULT_NOT_LITERAL";
44
+ /** `loop.<member>` outside a `{% for %}` body, or an unknown loop member. */
45
+ readonly LoopOutsideFor: "MJQ_LOOP_OUTSIDE_FOR";
46
+ /** A `{% for %}` whose iterable is not an array parameter, or that has an unsupported shape. */
47
+ readonly ForIterable: "MJQ_FOR_ITERABLE";
48
+ /** A string, array or date value written into the SQL without an MJ SQL filter. */
49
+ readonly UnfilteredValue: "MJQ_UNFILTERED_VALUE";
50
+ /** A value written without a filter whose type is not known. */
51
+ readonly UnfilteredUntyped: "MJQ_UNFILTERED_UNTYPED";
52
+ /** A `Context.<Token>` that is not one of the defined tokens. */
53
+ readonly UnknownContextToken: "MJQ_UNKNOWN_CONTEXT_TOKEN";
54
+ /** A SQL filter that does not fit the parameter's declared type. */
55
+ readonly FilterTypeMismatch: "MJQ_FILTER_TYPE_MISMATCH";
56
+ /** Two uses of one parameter imply different types. */
57
+ readonly ParameterTypeConflict: "MJQ_PARAMETER_TYPE_CONFLICT";
58
+ /** A `{{query:"…"}}` token whose path or argument list does not parse. */
59
+ readonly CompositionMalformed: "MJQ_COMPOSITION_MALFORMED";
60
+ /** A composition outside a FROM / JOIN / comma table-source position. */
61
+ readonly CompositionPosition: "MJQ_COMPOSITION_POSITION";
62
+ /** The composed query does not exist at that full path. */
63
+ readonly CompositionNotFound: "MJQ_COMPOSITION_NOT_FOUND";
64
+ /**
65
+ * The path names the composed query by part of its category path (a whole-segment suffix of
66
+ * exactly one query's). It runs, with a warning; save refuses it.
67
+ */
68
+ readonly CompositionPartialPath: "MJQ_COMPOSITION_PARTIAL_PATH";
69
+ /** The composed query is not marked Reusable. */
70
+ readonly CompositionNotReusable: "MJQ_COMPOSITION_NOT_REUSABLE";
71
+ /** A required parameter of the composed query is not passed. */
72
+ readonly CompositionMissingArgument: "MJQ_COMPOSITION_MISSING_ARGUMENT";
73
+ /** An unpassed parameter of the composed query has the same name as an outer parameter. */
74
+ readonly CompositionImplicitArgument: "MJQ_COMPOSITION_IMPLICIT_ARGUMENT";
75
+ /** An argument name the composed query does not declare. */
76
+ readonly CompositionUnknownArgument: "MJQ_COMPOSITION_UNKNOWN_ARGUMENT";
77
+ /** The same argument passed twice. */
78
+ readonly CompositionDuplicateArgument: "MJQ_COMPOSITION_DUPLICATE_ARGUMENT";
79
+ /** Compositions that lead back to a query already being composed. */
80
+ readonly CompositionCycle: "MJQ_COMPOSITION_CYCLE";
81
+ /** No resolver was supplied, so the composed queries were not checked. */
82
+ readonly CompositionUnchecked: "MJQ_COMPOSITION_UNCHECKED";
83
+ /** An `@tag` in a `{# #}` doc comment other than `@param` and `@field`. */
84
+ readonly DocUnknownTag: "MJQ_DOC_UNKNOWN_TAG";
85
+ /** An `@param` or `@field` with no name. */
86
+ readonly DocMissingName: "MJQ_DOC_MISSING_NAME";
87
+ /** Two descriptions for the same parameter or field. */
88
+ readonly DocDuplicate: "MJQ_DOC_DUPLICATE";
89
+ /** An `@param` naming something that is not a parameter of the query. */
90
+ readonly DocUnknownParameter: "MJQ_DOC_UNKNOWN_PARAMETER";
91
+ /** A `--:` comment that cannot be attached to exactly one select item. */
92
+ readonly DocTrailingAmbiguous: "MJQ_DOC_TRAILING_AMBIGUOUS";
93
+ };
94
+ /** One of the {@link MJQueryDiagnosticCodes}. */
95
+ export type MJQueryDiagnosticCode = typeof MJQueryDiagnosticCodes[keyof typeof MJQueryDiagnosticCodes];
96
+ //# sourceMappingURL=diagnosticCodes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnosticCodes.d.ts","sourceRoot":"","sources":["../../src/common/diagnosticCodes.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,eAAO,MAAM,sBAAsB;IAE/B,+DAA+D;;IAE/D,kDAAkD;;IAElD,qDAAqD;;IAErD,yGAAyG;;IAIzG,2EAA2E;;IAE3E,iGAAiG;;IAEjG,sCAAsC;;IAEtC,yHAAyH;;IAEzH,kDAAkD;;IAElD,uDAAuD;;IAEvD;;;OAGG;;IAEH,0FAA0F;;IAE1F,8FAA8F;;IAE9F,yCAAyC;;IAEzC,8FAA8F;;IAE9F,mEAAmE;;IAEnE,sDAAsD;;IAEtD,6EAA6E;;IAE7E,gGAAgG;;IAIhG,mFAAmF;;IAEnF,gEAAgE;;IAEhE,iEAAiE;;IAEjE,oEAAoE;;IAEpE,uDAAuD;;IAIvD,0EAA0E;;IAE1E,yEAAyE;;IAEzE,2DAA2D;;IAE3D;;;OAGG;;IAEH,iDAAiD;;IAEjD,gEAAgE;;IAEhE,2FAA2F;;IAE3F,4DAA4D;;IAE5D,sCAAsC;;IAEtC,qEAAqE;;IAErE,0EAA0E;;IAI1E,2EAA2E;;IAE3E,4CAA4C;;IAE5C,wDAAwD;;IAExD,yEAAyE;;IAEzE,0EAA0E;;CAEpE,CAAC;AAEX,iDAAiD;AACjD,MAAM,MAAM,qBAAqB,GAAG,OAAO,sBAAsB,CAAC,MAAM,OAAO,sBAAsB,CAAC,CAAC"}
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Every diagnostic code the MJ Query language reports, with the rule it stands for. Codes are
3
+ * stable: a code is never renamed or reused for another rule. `guides/MJ_QUERY_LANGUAGE.md`
4
+ * documents each one with an example and its fix.
5
+ */
6
+ export const MJQueryDiagnosticCodes = {
7
+ // Lexing
8
+ /** A `{{`, `{%` or `{#` with no closing `}}`, `%}` or `#}`. */
9
+ UnclosedTag: 'MJQ_UNCLOSED_TAG',
10
+ /** A template tag inside a SQL string literal. */
11
+ TagInStringLiteral: 'MJQ_TAG_IN_STRING_LITERAL',
12
+ /** A template tag inside a SQL quoted identifier. */
13
+ TagInQuotedIdentifier: 'MJQ_TAG_IN_QUOTED_IDENTIFIER',
14
+ /** Info: a template tag inside a SQL comment, which is inert (comments are removed before rendering). */
15
+ ExpressionInComment: 'MJQ_EXPRESSION_IN_COMMENT',
16
+ // Template structure
17
+ /** An `{% if %}` or `{% for %}` with no `{% endif %}` / `{% endfor %}`. */
18
+ UnclosedBlock: 'MJQ_UNCLOSED_BLOCK',
19
+ /** An `{% elif %}`, `{% else %}`, `{% endif %}` or `{% endfor %}` with no block to belong to. */
20
+ UnexpectedTag: 'MJQ_UNEXPECTED_TAG',
21
+ /** A tag body that does not parse. */
22
+ Syntax: 'MJQ_SYNTAX',
23
+ /** A block tag outside the allow-list (`macro`, `include`, `import`, `extends`, `block`, `call`, `filter`, `raw`, …). */
24
+ UnsupportedTag: 'MJQ_UNSUPPORTED_TAG',
25
+ /** A function or method call in an expression. */
26
+ FunctionCall: 'MJQ_FUNCTION_CALL',
27
+ /** A subscript (`x[0]`, `x['k']`) in an expression. */
28
+ Subscript: 'MJQ_SUBSCRIPT',
29
+ /**
30
+ * No longer reported: the inline `a if b else c` is part of the language. The code is kept
31
+ * so it is never reused for another rule.
32
+ */
33
+ InlineIf: 'MJQ_INLINE_IF',
34
+ /** Attribute access other than `Context.<Token>`, `loop.<member>` and `<name>.length`. */
35
+ MemberAccess: 'MJQ_MEMBER_ACCESS',
36
+ /** An operator outside the grammar (`in`, `is`, `~`, `**`, `//`, list or object literals). */
37
+ UnsupportedOperator: 'MJQ_UNSUPPORTED_OPERATOR',
38
+ /** An operator inside a `{{ }}` hole. */
39
+ ArithmeticInHole: 'MJQ_ARITHMETIC_IN_HOLE',
40
+ /** A `{{ }}` hole that does not start from a parameter, a `Context` token or a loop value. */
41
+ HoleNotAValue: 'MJQ_HOLE_NOT_A_VALUE',
42
+ /** A filter that is not one of the MJ SQL filters or `default`. */
43
+ UnknownFilter: 'MJQ_UNKNOWN_FILTER',
44
+ /** A `default(…)` whose argument is not a literal. */
45
+ DefaultNotLiteral: 'MJQ_DEFAULT_NOT_LITERAL',
46
+ /** `loop.<member>` outside a `{% for %}` body, or an unknown loop member. */
47
+ LoopOutsideFor: 'MJQ_LOOP_OUTSIDE_FOR',
48
+ /** A `{% for %}` whose iterable is not an array parameter, or that has an unsupported shape. */
49
+ ForIterable: 'MJQ_FOR_ITERABLE',
50
+ // Values and types
51
+ /** A string, array or date value written into the SQL without an MJ SQL filter. */
52
+ UnfilteredValue: 'MJQ_UNFILTERED_VALUE',
53
+ /** A value written without a filter whose type is not known. */
54
+ UnfilteredUntyped: 'MJQ_UNFILTERED_UNTYPED',
55
+ /** A `Context.<Token>` that is not one of the defined tokens. */
56
+ UnknownContextToken: 'MJQ_UNKNOWN_CONTEXT_TOKEN',
57
+ /** A SQL filter that does not fit the parameter's declared type. */
58
+ FilterTypeMismatch: 'MJQ_FILTER_TYPE_MISMATCH',
59
+ /** Two uses of one parameter imply different types. */
60
+ ParameterTypeConflict: 'MJQ_PARAMETER_TYPE_CONFLICT',
61
+ // Composition
62
+ /** A `{{query:"…"}}` token whose path or argument list does not parse. */
63
+ CompositionMalformed: 'MJQ_COMPOSITION_MALFORMED',
64
+ /** A composition outside a FROM / JOIN / comma table-source position. */
65
+ CompositionPosition: 'MJQ_COMPOSITION_POSITION',
66
+ /** The composed query does not exist at that full path. */
67
+ CompositionNotFound: 'MJQ_COMPOSITION_NOT_FOUND',
68
+ /**
69
+ * The path names the composed query by part of its category path (a whole-segment suffix of
70
+ * exactly one query's). It runs, with a warning; save refuses it.
71
+ */
72
+ CompositionPartialPath: 'MJQ_COMPOSITION_PARTIAL_PATH',
73
+ /** The composed query is not marked Reusable. */
74
+ CompositionNotReusable: 'MJQ_COMPOSITION_NOT_REUSABLE',
75
+ /** A required parameter of the composed query is not passed. */
76
+ CompositionMissingArgument: 'MJQ_COMPOSITION_MISSING_ARGUMENT',
77
+ /** An unpassed parameter of the composed query has the same name as an outer parameter. */
78
+ CompositionImplicitArgument: 'MJQ_COMPOSITION_IMPLICIT_ARGUMENT',
79
+ /** An argument name the composed query does not declare. */
80
+ CompositionUnknownArgument: 'MJQ_COMPOSITION_UNKNOWN_ARGUMENT',
81
+ /** The same argument passed twice. */
82
+ CompositionDuplicateArgument: 'MJQ_COMPOSITION_DUPLICATE_ARGUMENT',
83
+ /** Compositions that lead back to a query already being composed. */
84
+ CompositionCycle: 'MJQ_COMPOSITION_CYCLE',
85
+ /** No resolver was supplied, so the composed queries were not checked. */
86
+ CompositionUnchecked: 'MJQ_COMPOSITION_UNCHECKED',
87
+ // Doc comments
88
+ /** An `@tag` in a `{# #}` doc comment other than `@param` and `@field`. */
89
+ DocUnknownTag: 'MJQ_DOC_UNKNOWN_TAG',
90
+ /** An `@param` or `@field` with no name. */
91
+ DocMissingName: 'MJQ_DOC_MISSING_NAME',
92
+ /** Two descriptions for the same parameter or field. */
93
+ DocDuplicate: 'MJQ_DOC_DUPLICATE',
94
+ /** An `@param` naming something that is not a parameter of the query. */
95
+ DocUnknownParameter: 'MJQ_DOC_UNKNOWN_PARAMETER',
96
+ /** A `--:` comment that cannot be attached to exactly one select item. */
97
+ DocTrailingAmbiguous: 'MJQ_DOC_TRAILING_AMBIGUOUS',
98
+ };
99
+ //# sourceMappingURL=diagnosticCodes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnosticCodes.js","sourceRoot":"","sources":["../../src/common/diagnosticCodes.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG;IAClC,SAAS;IACT,+DAA+D;IAC/D,WAAW,EAAE,kBAAkB;IAC/B,kDAAkD;IAClD,kBAAkB,EAAE,2BAA2B;IAC/C,qDAAqD;IACrD,qBAAqB,EAAE,8BAA8B;IACrD,yGAAyG;IACzG,mBAAmB,EAAE,2BAA2B;IAEhD,qBAAqB;IACrB,2EAA2E;IAC3E,aAAa,EAAE,oBAAoB;IACnC,iGAAiG;IACjG,aAAa,EAAE,oBAAoB;IACnC,sCAAsC;IACtC,MAAM,EAAE,YAAY;IACpB,yHAAyH;IACzH,cAAc,EAAE,qBAAqB;IACrC,kDAA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B;IACpC,4CAA4C;IAC5C,cAAc,EAAE,sBAAsB;IACtC,wDAAwD;IACxD,YAAY,EAAE,mBAAmB;IACjC,yEAAyE;IACzE,mBAAmB,EAAE,2BAA2B;IAChD,0EAA0E;IAC1E,oBAAoB,EAAE,4BAA4B;CAC5C,CAAC"}
@@ -0,0 +1,40 @@
1
+ import type { ParserDialect } from '@memberjunction/sql-dialect';
2
+ import type { SqlDocument } from '../sql/sqlDocument.js';
3
+ import type { QueryExpression } from '../sql/sqlNodes.js';
4
+ import type { SqlTransformResult } from './transformSupport.js';
5
+ /**
6
+ * Removes exactly the ORDER BY clause of the document's top-level query expression (or of
7
+ * `target`), and the whitespace before it. Clauses after it (`OFFSET`, `FETCH`, `LIMIT`, `FOR`,
8
+ * `OPTION`) are kept. Not applied when there is no ORDER BY.
9
+ */
10
+ export declare function StripOrderBy(doc: SqlDocument, target?: QueryExpression): SqlTransformResult;
11
+ /**
12
+ * Replaces the select list of a plain select block with `text`, such as `1` for a count body.
13
+ * Not applied to a set operation, a `VALUES` list or a `SELECT DISTINCT`, where the select list
14
+ * decides which rows there are.
15
+ */
16
+ export declare function ReplaceSelectList(doc: SqlDocument, text: string): SqlTransformResult;
17
+ /** The clauses {@link AppendTail} can add. Values are written as given (numbers or parameter text). */
18
+ export interface AppendTailOptions {
19
+ readonly Offset?: number | string;
20
+ readonly Fetch?: number | string;
21
+ readonly Limit?: number | string;
22
+ /** Query hints merged into the dialect's hint clause (`OPTION (…)`), added when there is none. */
23
+ readonly OptionHints?: readonly string[];
24
+ }
25
+ /**
26
+ * Appends row-cap clauses (`OFFSET`, `FETCH`, `LIMIT`) to the top-level query expression, before
27
+ * its `FOR` and `OPTION` clauses, and merges query hints into its hint clause. Adds the ORDER BY
28
+ * the dialect needs for paging (`ORDER BY (SELECT NULL)` on SQL Server) and the `OFFSET 0 ROWS`
29
+ * a lone `FETCH` needs. Not applied when a clause it would add is already there.
30
+ */
31
+ export declare function AppendTail(doc: SqlDocument, dialect: ParserDialect, options: AppendTailOptions): SqlTransformResult;
32
+ /**
33
+ * Caps the rows the query returns at `rows`: tightens a numeric TOP, LIMIT or FETCH the
34
+ * top-level query already has, or adds one by the dialect's grammar: `TOP n` after
35
+ * `SELECT [DISTINCT]`, else a `LIMIT n`, else `OFFSET 0 ROWS FETCH NEXT n ROWS ONLY` (with the
36
+ * ORDER BY the dialect needs). Not applied when the query's own cap is not a plain number
37
+ * (`PERCENT`, `WITH TIES`, a parameter): wrap it as a derived table first.
38
+ */
39
+ export declare function SetRowCap(doc: SqlDocument, dialect: ParserDialect, rows: number): SqlTransformResult;
40
+ //# sourceMappingURL=clauseTransforms.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clauseTransforms.d.ts","sourceRoot":"","sources":["../../src/edit/clauseTransforms.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAM1D,OAAO,KAAK,EAAe,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE7E;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,CAAC,EAAE,eAAe,GAAG,kBAAkB,CAM3F;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,GAAG,kBAAkB,CAQpF;AAED,uGAAuG;AACvG,MAAM,WAAW,iBAAiB;IAC9B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAClC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACjC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACjC,kGAAkG;IAClG,QAAQ,CAAC,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC5C;AAED;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,WAAW,EAAE,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,iBAAiB,GAAG,kBAAkB,CAQnH;AAgDD;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,WAAW,EAAE,OAAO,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,GAAG,kBAAkB,CAWpG"}
@@ -0,0 +1,161 @@
1
+ import { ClauseRemovalSpan, FromEdits, NotApplied, PagingOrderBy, SingleQueryOf, TailInsertionPoint, } from './transformSupport.js';
2
+ /**
3
+ * Removes exactly the ORDER BY clause of the document's top-level query expression (or of
4
+ * `target`), and the whitespace before it. Clauses after it (`OFFSET`, `FETCH`, `LIMIT`, `FOR`,
5
+ * `OPTION`) are kept. Not applied when there is no ORDER BY.
6
+ */
7
+ export function StripOrderBy(doc, target) {
8
+ const query = SingleQueryOf(doc);
9
+ if (typeof query === 'string')
10
+ return NotApplied(doc, 'StripOrderBy', query);
11
+ const owner = target ?? query.Body;
12
+ if (owner.Kind === 'Unknown' || owner.OrderBy === null)
13
+ return NotApplied(doc, 'StripOrderBy', null);
14
+ return FromEdits(doc.Edit().Remove(ClauseRemovalSpan(doc, owner.OrderBy.Span)));
15
+ }
16
+ /**
17
+ * Replaces the select list of a plain select block with `text`, such as `1` for a count body.
18
+ * Not applied to a set operation, a `VALUES` list or a `SELECT DISTINCT`, where the select list
19
+ * decides which rows there are.
20
+ */
21
+ export function ReplaceSelectList(doc, text) {
22
+ const query = SingleQueryOf(doc);
23
+ if (typeof query === 'string')
24
+ return NotApplied(doc, 'ReplaceSelectList', query);
25
+ const body = query.Body;
26
+ if (body.Kind !== 'Select')
27
+ return NotApplied(doc, 'ReplaceSelectList', 'the query is not a single select block');
28
+ if (body.Distinct !== null && body.Distinct.Form !== 'All')
29
+ return NotApplied(doc, 'ReplaceSelectList', 'the select list of a SELECT DISTINCT decides its rows');
30
+ if (body.SelectList.length === 0)
31
+ return NotApplied(doc, 'ReplaceSelectList', 'the select list is empty');
32
+ return FromEdits(doc.Edit().Replace(body.SelectListSpan, text));
33
+ }
34
+ /**
35
+ * Appends row-cap clauses (`OFFSET`, `FETCH`, `LIMIT`) to the top-level query expression, before
36
+ * its `FOR` and `OPTION` clauses, and merges query hints into its hint clause. Adds the ORDER BY
37
+ * the dialect needs for paging (`ORDER BY (SELECT NULL)` on SQL Server) and the `OFFSET 0 ROWS`
38
+ * a lone `FETCH` needs. Not applied when a clause it would add is already there.
39
+ */
40
+ export function AppendTail(doc, dialect, options) {
41
+ const query = SingleQueryOf(doc);
42
+ if (typeof query === 'string')
43
+ return NotApplied(doc, 'AppendTail', query);
44
+ const conflict = appendConflict(query.Body, options, dialect);
45
+ if (conflict !== null)
46
+ return NotApplied(doc, 'AppendTail', conflict);
47
+ let edits = appendCaps(doc.Edit(), query.Body, dialect, options);
48
+ edits = mergeHints(edits, doc, query.Body, dialect, options.OptionHints ?? []);
49
+ return FromEdits(edits);
50
+ }
51
+ function appendConflict(body, options, dialect) {
52
+ if (options.Offset !== undefined && body.Offset !== null)
53
+ return 'the query already has an OFFSET';
54
+ if (options.Fetch !== undefined && (body.Fetch !== null || body.Limit !== null))
55
+ return 'the query already has a FETCH or LIMIT';
56
+ if (options.Limit !== undefined && (body.Limit !== null || body.Fetch !== null))
57
+ return 'the query already has a LIMIT or FETCH';
58
+ if (options.Limit !== undefined && !dialect.Grammar.RowCapForms.includes('limit-offset'))
59
+ return 'the dialect has no LIMIT';
60
+ if (options.Fetch !== undefined && !dialect.Grammar.RowCapForms.includes('offset-fetch'))
61
+ return 'the dialect has no FETCH';
62
+ if ((options.OptionHints ?? []).length > 0 && dialect.Grammar.QueryHintKeyword === null)
63
+ return 'the dialect has no query-hint clause';
64
+ if (body.Kind === 'Select' && body.Top !== null && (options.Offset !== undefined || options.Fetch !== undefined))
65
+ return 'the query has a TOP, which OFFSET and FETCH cannot be combined with';
66
+ return null;
67
+ }
68
+ /** The text of the row-cap clauses to append, ORDER BY and OFFSET 0 included where the dialect needs them. */
69
+ function capText(body, dialect, options) {
70
+ const offsetFetch = dialect.Grammar.RowCapForms.includes('offset-fetch');
71
+ const usesOffsetFetch = options.Fetch !== undefined || (options.Offset !== undefined && options.Limit === undefined && offsetFetch);
72
+ const parts = [];
73
+ const paging = options.Offset !== undefined || options.Fetch !== undefined;
74
+ if (paging && body.OrderBy === null && dialect.Grammar.PagingRequiresOrderBy)
75
+ parts.push(`ORDER BY ${PagingOrderBy(dialect, body)}`);
76
+ if (options.Limit !== undefined)
77
+ parts.push(`LIMIT ${options.Limit}`);
78
+ const offset = options.Offset ?? (options.Fetch !== undefined && body.Offset === null ? 0 : undefined);
79
+ if (offset !== undefined)
80
+ parts.push(usesOffsetFetch ? `OFFSET ${offset} ROWS` : `OFFSET ${offset}`);
81
+ if (options.Fetch !== undefined)
82
+ parts.push(`FETCH NEXT ${options.Fetch} ROWS ONLY`);
83
+ return parts.join(' ');
84
+ }
85
+ function appendCaps(edits, body, dialect, options) {
86
+ const text = capText(body, dialect, options);
87
+ if (text === '')
88
+ return edits;
89
+ if (options.Fetch !== undefined && options.Offset === undefined && body.Offset !== null)
90
+ return edits.InsertAfter(body.Offset, ` ${text}`);
91
+ const point = TailInsertionPoint(body);
92
+ const span = { Start: point.At, End: point.At };
93
+ return point.BeforeClause ? edits.InsertBefore(span, `${text} `) : edits.InsertAfter(span, ` ${text}`);
94
+ }
95
+ function mergeHints(edits, doc, body, dialect, hints) {
96
+ if (hints.length === 0)
97
+ return edits;
98
+ if (body.Option !== null) {
99
+ const close = body.Option.ListSpan.End - 1;
100
+ const separator = body.Option.Hints.IsEmpty ? '' : ', ';
101
+ return edits.InsertBefore({ Start: close, End: close }, `${separator}${hints.join(', ')}`);
102
+ }
103
+ const keyword = (dialect.Grammar.QueryHintKeyword ?? 'OPTION').toUpperCase();
104
+ const end = body.Span.End;
105
+ return edits.InsertAfter({ Start: end, End: end }, `\n${keyword} (${hints.join(', ')})`);
106
+ }
107
+ /**
108
+ * Caps the rows the query returns at `rows`: tightens a numeric TOP, LIMIT or FETCH the
109
+ * top-level query already has, or adds one by the dialect's grammar: `TOP n` after
110
+ * `SELECT [DISTINCT]`, else a `LIMIT n`, else `OFFSET 0 ROWS FETCH NEXT n ROWS ONLY` (with the
111
+ * ORDER BY the dialect needs). Not applied when the query's own cap is not a plain number
112
+ * (`PERCENT`, `WITH TIES`, a parameter): wrap it as a derived table first.
113
+ */
114
+ export function SetRowCap(doc, dialect, rows) {
115
+ const query = SingleQueryOf(doc);
116
+ if (typeof query === 'string')
117
+ return NotApplied(doc, 'SetRowCap', query);
118
+ if (!Number.isInteger(rows) || rows < 0)
119
+ return NotApplied(doc, 'SetRowCap', 'the row count must be a non-negative integer');
120
+ const caps = doc.RowCaps().Value;
121
+ const limiting = caps.filter(c => c.Form !== 'Offset');
122
+ if (limiting.some(c => !c.Numeric) || caps.some(c => c.Form === 'Offset' && !c.Numeric)) {
123
+ return NotApplied(doc, 'SetRowCap', 'the query has a row cap that is not a plain number');
124
+ }
125
+ if (limiting.length > 0)
126
+ return tighten(doc, limiting, rows);
127
+ return addCap(doc, query.Body, dialect, rows);
128
+ }
129
+ function tighten(doc, caps, rows) {
130
+ let edits = doc.Edit();
131
+ for (const cap of caps) {
132
+ if (cap.Rows === null || cap.Rows > rows)
133
+ edits = tightenOne(edits, cap.Node, rows);
134
+ }
135
+ return FromEdits(edits);
136
+ }
137
+ function tightenOne(edits, node, rows) {
138
+ switch (node.Kind) {
139
+ case 'Top':
140
+ return edits.Replace(node.Value, String(rows));
141
+ case 'Limit':
142
+ return node.Value !== null ? edits.Replace(node.Value, String(rows)) : edits.Replace(node, `LIMIT ${rows}`);
143
+ case 'Fetch':
144
+ return node.Value !== null ? edits.Replace(node.Value, String(rows)) : edits.Replace(node, `FETCH NEXT ${rows} ROWS ONLY`);
145
+ default:
146
+ return edits;
147
+ }
148
+ }
149
+ function addCap(doc, body, dialect, rows) {
150
+ const forms = dialect.Grammar.RowCapForms;
151
+ if (body.Kind === 'Select' && forms.includes('top') && body.Offset === null) {
152
+ const anchor = body.Distinct ?? { Span: { Start: body.Span.Start, End: body.Span.Start + 'SELECT'.length } };
153
+ return FromEdits(doc.Edit().InsertAfter(anchor, ` TOP ${rows}`));
154
+ }
155
+ if (forms.includes('limit-offset'))
156
+ return AppendTail(doc, dialect, { Limit: rows });
157
+ if (forms.includes('offset-fetch'))
158
+ return AppendTail(doc, dialect, { Fetch: rows });
159
+ return NotApplied(doc, 'SetRowCap', 'the dialect has no row-cap form');
160
+ }
161
+ //# sourceMappingURL=clauseTransforms.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clauseTransforms.js","sourceRoot":"","sources":["../../src/edit/clauseTransforms.ts"],"names":[],"mappings":"AAKA,OAAO,EACH,iBAAiB,EAAE,SAAS,EAAa,UAAU,EAAE,aAAa,EAAE,aAAa,EAAE,kBAAkB,GACxG,MAAM,uBAAuB,CAAC;AAG/B;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,GAAgB,EAAE,MAAwB;IACnE,MAAM,KAAK,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC;IACjC,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,UAAU,CAAC,GAAG,EAAE,cAAc,EAAE,KAAK,CAAC,CAAC;IAC7E,MAAM,KAAK,GAAG,MAAM,IAAI,KAAK,CAAC,IAAI,CAAC;IACnC,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,OAAO,KAAK,IAAI;QAAE,OAAO,UAAU,CAAC,GAAG,EAAE,cAAc,EAAE,IAAI,CAAC,CAAC;IACrG,OAAO,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,MAAM,CAAC,iBAAiB,CAAC,GAAG,EAAE,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpF,CAAC;AAED;;;;GAIG;AAC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AK,CAAC,QAAQ,CAAC,cAAc,CAAC;QAAE,OAAO,UAAU,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IACrF,OAAO,UAAU,CAAC,GAAG,EAAE,WAAW,EAAE,iCAAiC,CAAC,CAAC;AAC3E,CAAC"}
@@ -0,0 +1,68 @@
1
+ import type { SqlDocument } from '../sql/sqlDocument.js';
2
+ import type { CTEDeclaration, OrderByClause, WithClause } from '../sql/sqlNodes.js';
3
+ import type { SqlTransformResult, TransformDialect } from './transformSupport.js';
4
+ /** One CTE of a leading WITH clause, as written. */
5
+ export interface HoistedCTE {
6
+ /** The name, unquoted. */
7
+ readonly Name: string;
8
+ /** The name exactly as written, quotes included. */
9
+ readonly NameText: string;
10
+ /** The whole definition: name, column list, `AS`, body with parentheses. */
11
+ readonly Text: string;
12
+ /** The body, without its parentheses. */
13
+ readonly Body: string;
14
+ readonly Node: CTEDeclaration;
15
+ }
16
+ /** A statement's leading CTE list, split from the query it feeds. */
17
+ export interface HoistedCTEs {
18
+ /** The leading WITH clause; `null` when there is none. */
19
+ readonly With: WithClause | null;
20
+ readonly Recursive: boolean;
21
+ readonly CTEs: readonly HoistedCTE[];
22
+ /** The definitions as written, from the first CTE to the end of the last (no `WITH` keyword). */
23
+ readonly CTEListText: string;
24
+ /** The query after the WITH clause, to the end of the statement (its `;` excluded). */
25
+ readonly Body: string;
26
+ /** Where {@link Body} starts in the text. */
27
+ readonly BodyStart: number;
28
+ }
29
+ /**
30
+ * Splits the document's single query statement into its leading CTE list and the remaining body,
31
+ * by position, so every part is returned as written. `null` when the document is not a single
32
+ * query statement that was read completely.
33
+ */
34
+ export declare function HoistCTEs(doc: SqlDocument): HoistedCTEs | null;
35
+ /**
36
+ * Renames a CTE: its declaration and every reference the scope analysis binds to it (FROM and
37
+ * JOIN sources, qualifiers such as `Old.ID` and `Old.*` where the source has no alias of its
38
+ * own). String literals, aliases and same-named columns are never touched. The new name is
39
+ * always quoted with the dialect's writer. By default the first CTE named `oldName` is renamed,
40
+ * leading WITH clauses first; pass `cte` to choose one.
41
+ */
42
+ export declare function RenameCTE(doc: SqlDocument, dialect: TransformDialect, oldName: string, newName: string, cte?: CTEDeclaration): SqlTransformResult;
43
+ /** Options for {@link WrapAsDerivedTable}. */
44
+ export interface WrapOptions {
45
+ /** The outer select list; `*` by default. */
46
+ readonly SelectList?: string;
47
+ /**
48
+ * What happens to the query's ORDER BY. `Auto` (the default): it moves to the outer query,
49
+ * or, when the query has its own row cap, stays inside and is copied outside. `Keep`: it stays
50
+ * inside only. `Drop`: it is removed. Moved and copied items name output columns, so their
51
+ * qualifiers are dropped (`a.Name` becomes `Name`).
52
+ */
53
+ readonly OrderBy?: 'Auto' | 'Keep' | 'Drop';
54
+ }
55
+ /**
56
+ * Wraps the query as a derived table, `SELECT * FROM (query) AS alias`. Leading CTEs are hoisted
57
+ * out first (a WITH cannot sit inside a derived table on SQL Server), the query-hint clause moves
58
+ * to the outer query, and the ORDER BY is handled by {@link WrapOptions.OrderBy}. Not applied to
59
+ * a query with `FOR JSON` / `FOR XML` or a row-locking clause.
60
+ */
61
+ export declare function WrapAsDerivedTable(doc: SqlDocument, dialect: TransformDialect, alias: string, options?: WrapOptions): SqlTransformResult;
62
+ /**
63
+ * An ORDER BY's text with every column qualifier dropped, so it can order a query that wraps the
64
+ * original as a derived table: `ORDER BY a.Name, [a] /*c*\/ . [ID]` becomes `ORDER BY Name, [ID]`.
65
+ * Function names keep their schema (`dbo.fnLen(a.Name)` becomes `dbo.fnLen(Name)`).
66
+ */
67
+ export declare function OutputOrderBy(doc: SqlDocument, orderBy: OrderByClause): string;
68
+ //# sourceMappingURL=cteTransforms.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cteTransforms.d.ts","sourceRoot":"","sources":["../../src/edit/cteTransforms.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,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MAAM,CAAC;IAC7B;;;;;OAKG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;CAC/C;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,WAAW,EAAE,OAAO,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,WAAgB,GAAG,kBAAkB,CAc5I;AAYD;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,WAAW,EAAE,OAAO,EAAE,aAAa,GAAG,MAAM,CAY9E"}
@@ -0,0 +1,127 @@
1
+ import { NameKey } from '../sql/sqlScope.js';
2
+ import { ClauseRemovalSpan, FromEdits, FromText, HasOwnCap, NotApplied, SingleQueryOf, } from './transformSupport.js';
3
+ /**
4
+ * Splits the document's single query statement into its leading CTE list and the remaining body,
5
+ * by position, so every part is returned as written. `null` when the document is not a single
6
+ * query statement that was read completely.
7
+ */
8
+ export function HoistCTEs(doc) {
9
+ const query = SingleQueryOf(doc);
10
+ if (typeof query === 'string')
11
+ return null;
12
+ const statement = query.Statement;
13
+ const clause = statement.With;
14
+ const bodyEnd = statement.Terminator?.Start ?? statement.Span.End;
15
+ const ctes = (clause?.CTEs ?? []).map(cte => Object.freeze({
16
+ Name: cte.Name.Value, NameText: doc.Text(cte.Name), Text: doc.Text(cte), Node: cte,
17
+ Body: doc.Text({ Start: cte.BodySpan.Start + 1, End: cte.BodySpan.End - 1 }),
18
+ }));
19
+ const first = clause?.CTEs[0];
20
+ const last = clause?.CTEs[clause.CTEs.length - 1];
21
+ return Object.freeze({
22
+ With: clause, Recursive: clause?.Recursive ?? false, CTEs: Object.freeze(ctes),
23
+ CTEListText: first !== undefined && last !== undefined ? doc.Text({ Start: first.Span.Start, End: last.Span.End }) : '',
24
+ Body: doc.Text({ Start: query.Body.Span.Start, End: bodyEnd }), BodyStart: query.Body.Span.Start,
25
+ });
26
+ }
27
+ /**
28
+ * Renames a CTE: its declaration and every reference the scope analysis binds to it (FROM and
29
+ * JOIN sources, qualifiers such as `Old.ID` and `Old.*` where the source has no alias of its
30
+ * own). String literals, aliases and same-named columns are never touched. The new name is
31
+ * always quoted with the dialect's writer. By default the first CTE named `oldName` is renamed,
32
+ * leading WITH clauses first; pass `cte` to choose one.
33
+ */
34
+ export function RenameCTE(doc, dialect, oldName, newName, cte) {
35
+ if (!doc.IsComplete)
36
+ return NotApplied(doc, 'RenameCTE', 'part of the text could not be read');
37
+ const target = cte ?? findCTE(doc, oldName);
38
+ if (target === null)
39
+ return NotApplied(doc, 'RenameCTE', `there is no CTE named ${oldName}`);
40
+ const quoted = dialect.Writer.QuoteIdentifier(newName);
41
+ return FromEdits(doc.Edit().ReplaceAll(renameSpans(doc, target), quoted));
42
+ }
43
+ function findCTE(doc, name) {
44
+ const all = doc.CTEs().Value;
45
+ const matches = (node) => NameKey(node, doc.Dialect) === NameKey({ ...node, Value: name }, doc.Dialect);
46
+ const leading = all.find(c => c.Leading && matches(c.Name));
47
+ return (leading ?? all.find(c => matches(c.Name)))?.Node ?? null;
48
+ }
49
+ /** The spans to rewrite: the declaration, the referencing table names, and the qualifiers bound through them. */
50
+ function renameSpans(doc, cte) {
51
+ const scope = doc.Scope();
52
+ const references = new Set(scope.ReferencesTo(cte));
53
+ const viaName = (source) => source !== undefined && source.NameIsTableName && source.Source.Kind === 'Table' && references.has(source.Source);
54
+ const spans = new Map([[cte.Name.Span.Start, cte.Name.Span]]);
55
+ for (const reference of references)
56
+ spans.set(reference.Name.Span.Start, reference.Name.Parts[0].Span);
57
+ for (const column of doc.ColumnReferences().Value) {
58
+ const qualifier = column.Qualifier[column.Qualifier.length - 1];
59
+ if (qualifier !== undefined && column.Binding?.Via === 'Qualifier' && viaName(column.Binding.Source))
60
+ spans.set(qualifier.Span.Start, qualifier.Span);
61
+ }
62
+ for (const context of scope.Expressions) {
63
+ for (const star of context.Expression.Stars()) {
64
+ if (star.Qualifier === null)
65
+ continue;
66
+ const binding = scope.ResolveQualifier(star.Qualifier.Parts, context.Scope);
67
+ const part = star.Qualifier.Parts[star.Qualifier.Parts.length - 1];
68
+ if (viaName(binding?.Source))
69
+ spans.set(part.Span.Start, part.Span);
70
+ }
71
+ }
72
+ return [...spans.values()].sort((a, b) => a.Start - b.Start);
73
+ }
74
+ /**
75
+ * Wraps the query as a derived table, `SELECT * FROM (query) AS alias`. Leading CTEs are hoisted
76
+ * out first (a WITH cannot sit inside a derived table on SQL Server), the query-hint clause moves
77
+ * to the outer query, and the ORDER BY is handled by {@link WrapOptions.OrderBy}. Not applied to
78
+ * a query with `FOR JSON` / `FOR XML` or a row-locking clause.
79
+ */
80
+ export function WrapAsDerivedTable(doc, dialect, alias, options = {}) {
81
+ const query = SingleQueryOf(doc);
82
+ if (typeof query === 'string')
83
+ return NotApplied(doc, 'WrapAsDerivedTable', query);
84
+ if (query.Body.For !== null)
85
+ return NotApplied(doc, 'WrapAsDerivedTable', 'the query ends with a FOR clause, which cannot sit in a derived table');
86
+ const mode = options.OrderBy ?? 'Auto';
87
+ const orderBy = query.Body.OrderBy;
88
+ const keepInside = orderBy !== null && (mode === 'Keep' || (mode === 'Auto' && HasOwnCap(query.Body)));
89
+ const outerOrderBy = orderBy !== null && mode === 'Auto' ? OutputOrderBy(doc, orderBy) : null;
90
+ const inner = innerText(doc, query, keepInside ? null : orderBy);
91
+ const withText = query.Statement.With === null ? '' : `${doc.Text(query.Statement.With)}\n`;
92
+ const option = query.Body.Option === null ? '' : `\n${doc.Text(query.Body.Option)}`;
93
+ const ordered = outerOrderBy === null ? '' : `\n${outerOrderBy}`;
94
+ const text = `${withText}SELECT ${options.SelectList ?? '*'} FROM (\n${inner}\n) AS ${dialect.Writer.QuoteIdentifier(alias)}${ordered}${option}`;
95
+ return FromText(doc, text);
96
+ }
97
+ /** The query body's text without its OPTION clause, and without `orderBy` when given. */
98
+ function innerText(doc, query, orderBy) {
99
+ let edits = doc.Edit();
100
+ if (query.Body.Option !== null)
101
+ edits = edits.Remove(ClauseRemovalSpan(doc, query.Body.Option.Span));
102
+ if (orderBy !== null)
103
+ edits = edits.Remove(ClauseRemovalSpan(doc, orderBy.Span));
104
+ const applied = edits.Apply();
105
+ const span = applied.SpanMap.MapSpan(query.Body.Span) ?? { Start: 0, End: applied.Text.length };
106
+ return applied.Text.substring(span.Start, span.End).trimEnd();
107
+ }
108
+ /**
109
+ * An ORDER BY's text with every column qualifier dropped, so it can order a query that wraps the
110
+ * original as a derived table: `ORDER BY a.Name, [a] /*c*\/ . [ID]` becomes `ORDER BY Name, [ID]`.
111
+ * Function names keep their schema (`dbo.fnLen(a.Name)` becomes `dbo.fnLen(Name)`).
112
+ */
113
+ export function OutputOrderBy(doc, orderBy) {
114
+ let edits = doc.Edit();
115
+ for (const item of orderBy.Items) {
116
+ for (const path of item.Expression.Identifiers()) {
117
+ if (path.Parts.length < 2)
118
+ continue;
119
+ const column = path.Parts[path.Parts.length - 1];
120
+ edits = edits.Replace(path.Span, doc.Text(column));
121
+ }
122
+ }
123
+ const applied = edits.Apply();
124
+ const span = applied.SpanMap.MapSpan(orderBy.Span) ?? orderBy.Span;
125
+ return applied.Text.substring(span.Start, span.End);
126
+ }
127
+ //# sourceMappingURL=cteTransforms.js.map