@memberjunction/sql-parser 6.2.0-edge.6 → 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.
- package/README.md +392 -0
- package/dist/aggregateExpression.d.ts +5 -1
- package/dist/aggregateExpression.d.ts.map +1 -1
- package/dist/aggregateExpression.js +7 -420
- package/dist/aggregateExpression.js.map +1 -1
- package/dist/common/analysis.d.ts +48 -0
- package/dist/common/analysis.d.ts.map +1 -0
- package/dist/common/analysis.js +17 -0
- package/dist/common/analysis.js.map +1 -0
- package/dist/common/diagnosticCodes.d.ts +96 -0
- package/dist/common/diagnosticCodes.d.ts.map +1 -0
- package/dist/common/diagnosticCodes.js +99 -0
- package/dist/common/diagnosticCodes.js.map +1 -0
- package/dist/edit/clauseTransforms.d.ts +40 -0
- package/dist/edit/clauseTransforms.d.ts.map +1 -0
- package/dist/edit/clauseTransforms.js +161 -0
- package/dist/edit/clauseTransforms.js.map +1 -0
- package/dist/edit/cteTransforms.d.ts +68 -0
- package/dist/edit/cteTransforms.d.ts.map +1 -0
- package/dist/edit/cteTransforms.js +127 -0
- package/dist/edit/cteTransforms.js.map +1 -0
- package/dist/edit/editSet.d.ts +83 -0
- package/dist/edit/editSet.d.ts.map +1 -0
- package/dist/edit/editSet.js +185 -0
- package/dist/edit/editSet.js.map +1 -0
- package/dist/edit/transformSupport.d.ts +53 -0
- package/dist/edit/transformSupport.d.ts.map +1 -0
- package/dist/edit/transformSupport.js +67 -0
- package/dist/edit/transformSupport.js.map +1 -0
- package/dist/index.d.ts +49 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +24 -1
- package/dist/index.js.map +1 -1
- package/dist/legacy/cteParenScan.d.ts +13 -0
- package/dist/legacy/cteParenScan.d.ts.map +1 -0
- package/dist/legacy/cteParenScan.js +120 -0
- package/dist/legacy/cteParenScan.js.map +1 -0
- package/dist/legacy/dialectResolution.d.ts +22 -0
- package/dist/legacy/dialectResolution.d.ts.map +1 -0
- package/dist/legacy/dialectResolution.js +55 -0
- package/dist/legacy/dialectResolution.js.map +1 -0
- package/dist/legacy/frozenCTEExtraction.d.ts +10 -0
- package/dist/legacy/frozenCTEExtraction.d.ts.map +1 -0
- package/dist/legacy/frozenCTEExtraction.js +38 -0
- package/dist/legacy/frozenCTEExtraction.js.map +1 -0
- package/dist/legacy/legacyExtractors.d.ts +54 -0
- package/dist/legacy/legacyExtractors.d.ts.map +1 -0
- package/dist/legacy/legacyExtractors.js +245 -0
- package/dist/legacy/legacyExtractors.js.map +1 -0
- package/dist/legacy/legacyTagContent.d.ts +29 -0
- package/dist/legacy/legacyTagContent.d.ts.map +1 -0
- package/dist/legacy/legacyTagContent.js +283 -0
- package/dist/legacy/legacyTagContent.js.map +1 -0
- package/dist/legacy/legacyTemplateExtractors.d.ts +31 -0
- package/dist/legacy/legacyTemplateExtractors.d.ts.map +1 -0
- package/dist/legacy/legacyTemplateExtractors.js +201 -0
- package/dist/legacy/legacyTemplateExtractors.js.map +1 -0
- package/dist/legacy/legacyTemplateTokens.d.ts +16 -0
- package/dist/legacy/legacyTemplateTokens.d.ts.map +1 -0
- package/dist/legacy/legacyTemplateTokens.js +80 -0
- package/dist/legacy/legacyTemplateTokens.js.map +1 -0
- package/dist/legacy/nodeSqlParserCore.d.ts +34 -0
- package/dist/legacy/nodeSqlParserCore.d.ts.map +1 -0
- package/dist/legacy/nodeSqlParserCore.js +251 -0
- package/dist/legacy/nodeSqlParserCore.js.map +1 -0
- package/dist/legacy/nodeSqlRowCap.d.ts +46 -0
- package/dist/legacy/nodeSqlRowCap.d.ts.map +1 -0
- package/dist/legacy/nodeSqlRowCap.js +72 -0
- package/dist/legacy/nodeSqlRowCap.js.map +1 -0
- package/dist/legacy/nonQueryReads.d.ts +28 -0
- package/dist/legacy/nonQueryReads.d.ts.map +1 -0
- package/dist/legacy/nonQueryReads.js +112 -0
- package/dist/legacy/nonQueryReads.js.map +1 -0
- package/dist/legacy/templateSqlViews.d.ts +32 -0
- package/dist/legacy/templateSqlViews.d.ts.map +1 -0
- package/dist/legacy/templateSqlViews.js +176 -0
- package/dist/legacy/templateSqlViews.js.map +1 -0
- package/dist/lexer/sqlTokenTypes.d.ts +67 -0
- package/dist/lexer/sqlTokenTypes.d.ts.map +1 -0
- package/dist/lexer/sqlTokenTypes.js +2 -0
- package/dist/lexer/sqlTokenTypes.js.map +1 -0
- package/dist/lexer/sqlTokens.d.ts +53 -0
- package/dist/lexer/sqlTokens.d.ts.map +1 -0
- package/dist/lexer/sqlTokens.js +267 -0
- package/dist/lexer/sqlTokens.js.map +1 -0
- package/dist/lexer/templateTagScanner.d.ts +32 -0
- package/dist/lexer/templateTagScanner.d.ts.map +1 -0
- package/dist/lexer/templateTagScanner.js +69 -0
- package/dist/lexer/templateTagScanner.js.map +1 -0
- package/dist/orderByAnalyzer.d.ts +5 -0
- package/dist/orderByAnalyzer.d.ts.map +1 -1
- package/dist/orderByAnalyzer.js +5 -0
- package/dist/orderByAnalyzer.js.map +1 -1
- package/dist/pagingShape.d.ts +4 -1
- package/dist/pagingShape.d.ts.map +1 -1
- package/dist/pagingShape.js +4 -1
- package/dist/pagingShape.js.map +1 -1
- package/dist/sql/analyses/analysisTypes.d.ts +124 -0
- package/dist/sql/analyses/analysisTypes.d.ts.map +1 -0
- package/dist/sql/analyses/analysisTypes.js +2 -0
- package/dist/sql/analyses/analysisTypes.js.map +1 -0
- package/dist/sql/analyses/columnAnalyses.d.ts +18 -0
- package/dist/sql/analyses/columnAnalyses.d.ts.map +1 -0
- package/dist/sql/analyses/columnAnalyses.js +138 -0
- package/dist/sql/analyses/columnAnalyses.js.map +1 -0
- package/dist/sql/analyses/structureAnalyses.d.ts +31 -0
- package/dist/sql/analyses/structureAnalyses.d.ts.map +1 -0
- package/dist/sql/analyses/structureAnalyses.js +201 -0
- package/dist/sql/analyses/structureAnalyses.js.map +1 -0
- package/dist/sql/parser/fromParser.d.ts +45 -0
- package/dist/sql/parser/fromParser.d.ts.map +1 -0
- package/dist/sql/parser/fromParser.js +342 -0
- package/dist/sql/parser/fromParser.js.map +1 -0
- package/dist/sql/parser/parseContext.d.ts +72 -0
- package/dist/sql/parser/parseContext.d.ts.map +1 -0
- package/dist/sql/parser/parseContext.js +197 -0
- package/dist/sql/parser/parseContext.js.map +1 -0
- package/dist/sql/parser/queryParser.d.ts +45 -0
- package/dist/sql/parser/queryParser.d.ts.map +1 -0
- package/dist/sql/parser/queryParser.js +267 -0
- package/dist/sql/parser/queryParser.js.map +1 -0
- package/dist/sql/parser/selectParser.d.ts +47 -0
- package/dist/sql/parser/selectParser.d.ts.map +1 -0
- package/dist/sql/parser/selectParser.js +353 -0
- package/dist/sql/parser/selectParser.js.map +1 -0
- package/dist/sql/parser/tailParser.d.ts +25 -0
- package/dist/sql/parser/tailParser.d.ts.map +1 -0
- package/dist/sql/parser/tailParser.js +180 -0
- package/dist/sql/parser/tailParser.js.map +1 -0
- package/dist/sql/sqlDiagnosticCodes.d.ts +27 -0
- package/dist/sql/sqlDiagnosticCodes.d.ts.map +1 -0
- package/dist/sql/sqlDiagnosticCodes.js +25 -0
- package/dist/sql/sqlDiagnosticCodes.js.map +1 -0
- package/dist/sql/sqlDocument.d.ts +103 -0
- package/dist/sql/sqlDocument.d.ts.map +1 -0
- package/dist/sql/sqlDocument.js +178 -0
- package/dist/sql/sqlDocument.js.map +1 -0
- package/dist/sql/sqlExpression.d.ts +74 -0
- package/dist/sql/sqlExpression.d.ts.map +1 -0
- package/dist/sql/sqlExpression.js +313 -0
- package/dist/sql/sqlExpression.js.map +1 -0
- package/dist/sql/sqlKeywords.d.ts +38 -0
- package/dist/sql/sqlKeywords.d.ts.map +1 -0
- package/dist/sql/sqlKeywords.js +85 -0
- package/dist/sql/sqlKeywords.js.map +1 -0
- package/dist/sql/sqlNodes.d.ts +360 -0
- package/dist/sql/sqlNodes.d.ts.map +1 -0
- package/dist/sql/sqlNodes.js +2 -0
- package/dist/sql/sqlNodes.js.map +1 -0
- package/dist/sql/sqlScope.d.ts +108 -0
- package/dist/sql/sqlScope.d.ts.map +1 -0
- package/dist/sql/sqlScope.js +307 -0
- package/dist/sql/sqlScope.js.map +1 -0
- package/dist/sql/sqlWalker.d.ts +17 -0
- package/dist/sql/sqlWalker.d.ts.map +1 -0
- package/dist/sql/sqlWalker.js +113 -0
- package/dist/sql/sqlWalker.js.map +1 -0
- package/dist/sql/tokenTable.d.ts +58 -0
- package/dist/sql/tokenTable.d.ts.map +1 -0
- package/dist/sql/tokenTable.js +158 -0
- package/dist/sql/tokenTable.js.map +1 -0
- package/dist/sql-parser.d.ts +146 -194
- package/dist/sql-parser.d.ts.map +1 -1
- package/dist/sql-parser.js +173 -1272
- package/dist/sql-parser.js.map +1 -1
- package/dist/sqlLexer.d.ts +18 -13
- package/dist/sqlLexer.d.ts.map +1 -1
- package/dist/sqlLexer.js +152 -50
- package/dist/sqlLexer.js.map +1 -1
- package/dist/sqlShape.d.ts +11 -2
- package/dist/sqlShape.d.ts.map +1 -1
- package/dist/sqlShape.js +64 -8
- package/dist/sqlShape.js.map +1 -1
- package/dist/strict/aggregateRenderer.d.ts +28 -0
- package/dist/strict/aggregateRenderer.d.ts.map +1 -0
- package/dist/strict/aggregateRenderer.js +451 -0
- package/dist/strict/aggregateRenderer.js.map +1 -0
- package/dist/strict/statementReads.d.ts +34 -0
- package/dist/strict/statementReads.d.ts.map +1 -0
- package/dist/strict/statementReads.js +252 -0
- package/dist/strict/statementReads.js.map +1 -0
- package/dist/strict/strictDialect.d.ts +12 -0
- package/dist/strict/strictDialect.d.ts.map +1 -0
- package/dist/strict/strictDialect.js +37 -0
- package/dist/strict/strictDialect.js.map +1 -0
- package/dist/strict/strictFragmentValidator.d.ts +68 -0
- package/dist/strict/strictFragmentValidator.d.ts.map +1 -0
- package/dist/strict/strictFragmentValidator.js +156 -0
- package/dist/strict/strictFragmentValidator.js.map +1 -0
- package/dist/strict/strictTypes.d.ts +116 -0
- package/dist/strict/strictTypes.d.ts.map +1 -0
- package/dist/strict/strictTypes.js +2 -0
- package/dist/strict/strictTypes.js.map +1 -0
- package/dist/strict/treeFacts.d.ts +28 -0
- package/dist/strict/treeFacts.d.ts.map +1 -0
- package/dist/strict/treeFacts.js +162 -0
- package/dist/strict/treeFacts.js.map +1 -0
- package/dist/structuralParser.d.ts +2 -0
- package/dist/structuralParser.d.ts.map +1 -1
- package/dist/structuralParser.js +6 -4
- package/dist/structuralParser.js.map +1 -1
- package/dist/template/branchEvaluator.d.ts +51 -0
- package/dist/template/branchEvaluator.d.ts.map +1 -0
- package/dist/template/branchEvaluator.js +194 -0
- package/dist/template/branchEvaluator.js.map +1 -0
- package/dist/template/branchVariants.d.ts +79 -0
- package/dist/template/branchVariants.d.ts.map +1 -0
- package/dist/template/branchVariants.js +273 -0
- package/dist/template/branchVariants.js.map +1 -0
- package/dist/template/compositionParser.d.ts +18 -0
- package/dist/template/compositionParser.d.ts.map +1 -0
- package/dist/template/compositionParser.js +131 -0
- package/dist/template/compositionParser.js.map +1 -0
- package/dist/template/compositionPathMatch.d.ts +46 -0
- package/dist/template/compositionPathMatch.d.ts.map +1 -0
- package/dist/template/compositionPathMatch.js +50 -0
- package/dist/template/compositionPathMatch.js.map +1 -0
- package/dist/template/compositionReferences.d.ts +26 -0
- package/dist/template/compositionReferences.d.ts.map +1 -0
- package/dist/template/compositionReferences.js +21 -0
- package/dist/template/compositionReferences.js.map +1 -0
- package/dist/template/compositionRules.d.ts +42 -0
- package/dist/template/compositionRules.d.ts.map +1 -0
- package/dist/template/compositionRules.js +132 -0
- package/dist/template/compositionRules.js.map +1 -0
- package/dist/template/docComments.d.ts +45 -0
- package/dist/template/docComments.d.ts.map +1 -0
- package/dist/template/docComments.js +115 -0
- package/dist/template/docComments.js.map +1 -0
- package/dist/template/expressionLexer.d.ts +28 -0
- package/dist/template/expressionLexer.d.ts.map +1 -0
- package/dist/template/expressionLexer.js +85 -0
- package/dist/template/expressionLexer.js.map +1 -0
- package/dist/template/expressionParser.d.ts +106 -0
- package/dist/template/expressionParser.d.ts.map +1 -0
- package/dist/template/expressionParser.js +419 -0
- package/dist/template/expressionParser.js.map +1 -0
- package/dist/template/expressionTypes.d.ts +111 -0
- package/dist/template/expressionTypes.d.ts.map +1 -0
- package/dist/template/expressionTypes.js +25 -0
- package/dist/template/expressionTypes.js.map +1 -0
- package/dist/template/parameterAnalysis.d.ts +81 -0
- package/dist/template/parameterAnalysis.d.ts.map +1 -0
- package/dist/template/parameterAnalysis.js +130 -0
- package/dist/template/parameterAnalysis.js.map +1 -0
- package/dist/template/queryLanguage.d.ts +33 -0
- package/dist/template/queryLanguage.d.ts.map +1 -0
- package/dist/template/queryLanguage.js +56 -0
- package/dist/template/queryLanguage.js.map +1 -0
- package/dist/template/queryTemplate.d.ts +72 -0
- package/dist/template/queryTemplate.d.ts.map +1 -0
- package/dist/template/queryTemplate.js +147 -0
- package/dist/template/queryTemplate.js.map +1 -0
- package/dist/template/sqlPosition.d.ts +24 -0
- package/dist/template/sqlPosition.d.ts.map +1 -0
- package/dist/template/sqlPosition.js +93 -0
- package/dist/template/sqlPosition.js.map +1 -0
- package/dist/template/templateNodes.d.ts +114 -0
- package/dist/template/templateNodes.d.ts.map +1 -0
- package/dist/template/templateNodes.js +38 -0
- package/dist/template/templateNodes.js.map +1 -0
- package/dist/template/templateTreeBuilder.d.ts +56 -0
- package/dist/template/templateTreeBuilder.d.ts.map +1 -0
- package/dist/template/templateTreeBuilder.js +302 -0
- package/dist/template/templateTreeBuilder.js.map +1 -0
- package/dist/template/templateWalker.d.ts +62 -0
- package/dist/template/templateWalker.d.ts.map +1 -0
- package/dist/template/templateWalker.js +122 -0
- package/dist/template/templateWalker.js.map +1 -0
- package/dist/template/trailingDocComments.d.ts +35 -0
- package/dist/template/trailingDocComments.d.ts.map +1 -0
- package/dist/template/trailingDocComments.js +146 -0
- package/dist/template/trailingDocComments.js.map +1 -0
- package/dist/template/validationTypes.d.ts +77 -0
- package/dist/template/validationTypes.d.ts.map +1 -0
- package/dist/template/validationTypes.js +2 -0
- package/dist/template/validationTypes.js.map +1 -0
- package/dist/template/valueRules.d.ts +55 -0
- package/dist/template/valueRules.d.ts.map +1 -0
- package/dist/template/valueRules.js +238 -0
- package/dist/template/valueRules.js.map +1 -0
- package/package.json +2 -2
- package/dist/ASTDialectAdapter.d.ts +0 -60
- package/dist/ASTDialectAdapter.d.ts.map +0 -1
- package/dist/ASTDialectAdapter.js +0 -117
- package/dist/ASTDialectAdapter.js.map +0 -1
package/dist/sql-parser.js
CHANGED
|
@@ -15,28 +15,12 @@
|
|
|
15
15
|
import NodeSqlParser from 'node-sql-parser';
|
|
16
16
|
const { Parser } = NodeSqlParser;
|
|
17
17
|
import { MJLexer } from './mj-lexer.js';
|
|
18
|
-
import { ReplaceVariableInTag, VARIABLE_READING_TAGS } from './templateTagVariables.js';
|
|
19
18
|
import { MJPlaceholderSubstitution } from './mj-placeholder.js';
|
|
20
|
-
import {
|
|
21
|
-
import { GetASTDialectAdapter } from './ASTDialectAdapter.js';
|
|
19
|
+
import { ClearRowCap, ReadRowCap, RowCapFieldFor, WriteRowCap } from './legacy/nodeSqlRowCap.js';
|
|
22
20
|
import { IsKeyword, LexSQL, SignificantTokens } from './sqlLexer.js';
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
const POSTGRES_LEXING = new PostgreSQLDialect();
|
|
27
|
-
/**
|
|
28
|
-
* Standard SQL niladic user functions written without parentheses in T-SQL and PostgreSQL
|
|
29
|
-
* (`SELECT CURRENT_USER`, `SELECT SESSION_USER`, `SELECT SYSTEM_USER`). node-sql-parser's
|
|
30
|
-
* T-SQL and PostgreSQL grammars require `()` on these three keywords even though the
|
|
31
|
-
* databases themselves reject `()`.
|
|
32
|
-
*/
|
|
33
|
-
const NILADIC_USER_FUNCTIONS = new Set([
|
|
34
|
-
'CURRENT_USER',
|
|
35
|
-
'SESSION_USER',
|
|
36
|
-
'SYSTEM_USER',
|
|
37
|
-
]);
|
|
38
|
-
/** The FOR XML modes node-sql-parser knows. */
|
|
39
|
-
const FOR_XML_DIRECTIVES = ['PATH', 'RAW', 'AUTO', 'EXPLICIT'];
|
|
21
|
+
import { FixMaxTypeSerialization, NodeSqlParse } from './legacy/nodeSqlParserCore.js';
|
|
22
|
+
import { LegacyCTEExtraction, LegacyColumnReferencesChecked, LegacyParse, LegacySelectColumnsChecked, LegacyTableReferences, } from './legacy/legacyExtractors.js';
|
|
23
|
+
import { LegacyCompositionRefs, LegacyConditionalBlocks, LegacyParameterInfo, LegacyTemplateExpressions, RebuildLegacyTemplateExpr, ReplaceLegacyTemplateVariable, } from './legacy/legacyTemplateExtractors.js';
|
|
40
24
|
// ═══════════════════════════════════════════════════
|
|
41
25
|
// SQLParser class
|
|
42
26
|
// ═══════════════════════════════════════════════════
|
|
@@ -69,13 +53,14 @@ export class SQLParser {
|
|
|
69
53
|
* transparently restores both transforms.
|
|
70
54
|
*
|
|
71
55
|
* Never throws on unparseable SQL — check {@link IsValid}.
|
|
56
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect)` to read a statement, and `StrictFragmentValidator` to screen untrusted SQL.
|
|
72
57
|
*/
|
|
73
58
|
constructor(sql, dialect) {
|
|
74
59
|
this._sql = sql;
|
|
75
60
|
this._dialect = dialect;
|
|
76
|
-
this.
|
|
61
|
+
this._rowCapField = RowCapFieldFor(dialect);
|
|
77
62
|
// Fast path: direct parse (matches the old static ParseSQL contract).
|
|
78
|
-
const direct =
|
|
63
|
+
const direct = NodeSqlParse(sql, dialect.ParserDialect);
|
|
79
64
|
if (direct) {
|
|
80
65
|
this._ast = direct;
|
|
81
66
|
this._aliasMap = null;
|
|
@@ -88,11 +73,17 @@ export class SQLParser {
|
|
|
88
73
|
this._aliasMap = pre.aliasMap;
|
|
89
74
|
this._trailingOption = pre.trailingOption;
|
|
90
75
|
}
|
|
91
|
-
/**
|
|
76
|
+
/**
|
|
77
|
+
* Whether the SQL parsed into an AST (directly or via preprocessing).
|
|
78
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect).IsComplete`, or `StrictFragmentValidator` to screen untrusted SQL.
|
|
79
|
+
*/
|
|
92
80
|
get IsValid() {
|
|
93
81
|
return this._ast !== null;
|
|
94
82
|
}
|
|
95
|
-
/**
|
|
83
|
+
/**
|
|
84
|
+
* The raw AST. Prefer the typed accessors; this is an escape hatch.
|
|
85
|
+
* @deprecated Kept unchanged, node-sql-parser AST included, for callers that walk that tree; new code reads SQL with `SqlDocument.Parse(sql, dialect)`.
|
|
86
|
+
*/
|
|
96
87
|
get AST() {
|
|
97
88
|
return this._ast;
|
|
98
89
|
}
|
|
@@ -101,6 +92,7 @@ export class SQLParser {
|
|
|
101
92
|
* original bracketed text (for example `[My CTE]`). Null when the direct parse succeeded, so
|
|
102
93
|
* every identifier in the tree is as written. A name in this map is in the tree only where the
|
|
103
94
|
* fallback put it: no such name occurs in the SQL, and none runs into the text next to it.
|
|
95
|
+
* @deprecated Kept unchanged, node-sql-parser AST included, for callers that walk that tree; new code reads SQL with `SqlDocument.Parse(sql, dialect)`.
|
|
104
96
|
*/
|
|
105
97
|
get IdentifierAliases() {
|
|
106
98
|
return this._aliasMap;
|
|
@@ -109,25 +101,24 @@ export class SQLParser {
|
|
|
109
101
|
* True when `name` has the form of a name the fallback parse gives a renamed bracket
|
|
110
102
|
* identifier ({@link IdentifierAliases}), ignoring case: `_mjid_<n>`, or `_mjid<k>_<n>` when
|
|
111
103
|
* the SQL already contains `_mjid_`.
|
|
104
|
+
* @deprecated Kept unchanged, node-sql-parser AST included, for callers that walk that tree; new code reads SQL with `SqlDocument.Parse(sql, dialect)`.
|
|
112
105
|
*/
|
|
113
106
|
static IsIdentifierAliasName(name) {
|
|
114
107
|
return SQLParser.ALIAS_NAME.test(name);
|
|
115
108
|
}
|
|
116
|
-
/**
|
|
109
|
+
/**
|
|
110
|
+
* The dialect supplied at construction.
|
|
111
|
+
* @deprecated Use `SqlDocument.Dialect`.
|
|
112
|
+
*/
|
|
117
113
|
get Dialect() {
|
|
118
114
|
return this._dialect;
|
|
119
115
|
}
|
|
120
|
-
/** The SQL supplied at construction, as written. */
|
|
121
|
-
get SQL() {
|
|
122
|
-
return this._sql;
|
|
123
|
-
}
|
|
124
116
|
/**
|
|
125
|
-
*
|
|
126
|
-
*
|
|
127
|
-
* and VARBINARY — all SQL Server types that accept (MAX).
|
|
117
|
+
* The SQL supplied at construction, as written.
|
|
118
|
+
* @deprecated Use `SqlDocument.Text()`.
|
|
128
119
|
*/
|
|
129
|
-
|
|
130
|
-
return
|
|
120
|
+
get SQL() {
|
|
121
|
+
return this._sql;
|
|
131
122
|
}
|
|
132
123
|
// ─── Core Pipeline ─────────────────────────────────
|
|
133
124
|
/**
|
|
@@ -140,12 +131,13 @@ export class SQLParser {
|
|
|
140
131
|
*
|
|
141
132
|
* @param sql The MJ SQL string to parse
|
|
142
133
|
* @param dialect SQL dialect ('TransactSQL' | 'PostgresQL', default: 'TransactSQL')
|
|
134
|
+
* @deprecated Kept unchanged, node-sql-parser AST included, for callers that walk that tree; new code reads SQL with `SqlDocument.Parse(sql, dialect)`.
|
|
143
135
|
*/
|
|
144
136
|
static Astify(sql, dialect) {
|
|
145
137
|
const parserDialect = dialect.ParserDialect;
|
|
146
138
|
const mjParse = MJLexer.Parse(sql);
|
|
147
139
|
if (!mjParse.hasMJExtensions) {
|
|
148
|
-
const ast =
|
|
140
|
+
const ast = NodeSqlParse(sql, parserDialect);
|
|
149
141
|
return {
|
|
150
142
|
ast,
|
|
151
143
|
mjParse,
|
|
@@ -157,7 +149,7 @@ export class SQLParser {
|
|
|
157
149
|
};
|
|
158
150
|
}
|
|
159
151
|
const { cleanSQL, positionMap, strippedTokens } = MJPlaceholderSubstitution.Substitute(sql);
|
|
160
|
-
const ast =
|
|
152
|
+
const ast = NodeSqlParse(cleanSQL, parserDialect);
|
|
161
153
|
return {
|
|
162
154
|
ast,
|
|
163
155
|
mjParse,
|
|
@@ -173,13 +165,14 @@ export class SQLParser {
|
|
|
173
165
|
*
|
|
174
166
|
* For plain SQL: uses node-sql-parser's sqlify for normalized output.
|
|
175
167
|
* For MJ SQL: reconstructs from tokens, preserving all Nunjucks and composition syntax verbatim.
|
|
168
|
+
* @deprecated Kept unchanged, node-sql-parser AST included, for callers that walk that tree; new code reads SQL with `SqlDocument.Parse(sql, dialect)`.
|
|
176
169
|
*/
|
|
177
170
|
static Sqlify(result) {
|
|
178
171
|
if (!result.mjParse.hasMJExtensions && result.ast) {
|
|
179
172
|
const parser = new Parser();
|
|
180
173
|
const astToSqlify = Array.isArray(result.ast) ? result.ast[0] : result.ast;
|
|
181
174
|
const sql = parser.sqlify(astToSqlify, { database: result.dialect });
|
|
182
|
-
return
|
|
175
|
+
return FixMaxTypeSerialization(sql);
|
|
183
176
|
}
|
|
184
177
|
return result.mjParse.tokens.map(t => t.raw).join('');
|
|
185
178
|
}
|
|
@@ -188,31 +181,34 @@ export class SQLParser {
|
|
|
188
181
|
* Parse plain SQL into a node-sql-parser AST.
|
|
189
182
|
* Handles FOR XML multi-directive workaround automatically.
|
|
190
183
|
* Returns null if parsing fails.
|
|
184
|
+
* @deprecated Kept unchanged, node-sql-parser AST included, for callers that walk that tree; new code reads SQL with `SqlDocument.Parse(sql, dialect)`. To refuse unparseable caller SQL, use `StrictFragmentValidator`.
|
|
191
185
|
*/
|
|
192
186
|
static ParseSQL(sql, dialect) {
|
|
193
|
-
return
|
|
187
|
+
return NodeSqlParse(sql, dialect.ParserDialect);
|
|
194
188
|
}
|
|
195
189
|
/**
|
|
196
190
|
* Convert a node-sql-parser AST (or array of ASTs) back to a SQL string.
|
|
197
191
|
* This is a thin wrapper around node-sql-parser's sqlify.
|
|
192
|
+
* @deprecated Kept unchanged, node-sql-parser AST included, for callers that walk that tree; new code reads SQL with `SqlDocument.Parse(sql, dialect)`.
|
|
198
193
|
*/
|
|
199
194
|
static SqlifyAST(ast, dialect) {
|
|
200
195
|
const parser = new Parser();
|
|
201
196
|
const sql = parser.sqlify(Array.isArray(ast) ? ast[0] : ast, { database: dialect.ParserDialect });
|
|
202
|
-
return
|
|
197
|
+
return FixMaxTypeSerialization(sql);
|
|
203
198
|
}
|
|
204
199
|
// ─── AST primitives (instance) ──────────────────────
|
|
205
200
|
//
|
|
206
201
|
// These operate on the instance's parsed AST and hide node-sql-parser's
|
|
207
202
|
// shape behind typed, dialect-neutral accessors. The shape of `top`,
|
|
208
203
|
// `limit`, `into`, `set_op`, etc. is confined to this region and to
|
|
209
|
-
//
|
|
204
|
+
// legacy/nodeSqlRowCap — the only places that track those details.
|
|
210
205
|
//
|
|
211
206
|
// All inspect the FIRST statement only (matching SqlifyAST, which
|
|
212
207
|
// serializes only the first); MJ query SQL is single-statement.
|
|
213
208
|
/**
|
|
214
209
|
* High-level classification of the parsed statement:
|
|
215
210
|
* `'select'` | `'select-into'` | `'set-op'` | `'mutation'` | `'other'`.
|
|
211
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect).StatementKinds()`.
|
|
216
212
|
*/
|
|
217
213
|
get StatementKind() {
|
|
218
214
|
const root = SQLParser.unwrapRoot(this._ast);
|
|
@@ -253,6 +249,7 @@ export class SQLParser {
|
|
|
253
249
|
* `DECLARE`) and SELECTs are not writes. Matching is on the AST statement
|
|
254
250
|
* type, so the `REPLACE()` string function inside a SELECT is never
|
|
255
251
|
* mistaken for a `REPLACE` statement.
|
|
252
|
+
* @deprecated Must not be used to decide whether SQL is safe to run: it returns false whenever node-sql-parser cannot parse the SQL, so a write it cannot read passes. Use `SqlDocument.Parse(sql, dialect).IsReadOnly()` (fails closed) or `StrictFragmentValidator.ValidateReadOnlyStatement`.
|
|
256
253
|
*/
|
|
257
254
|
get HasWriteStatement() {
|
|
258
255
|
if (!this._ast)
|
|
@@ -268,25 +265,27 @@ export class SQLParser {
|
|
|
268
265
|
}
|
|
269
266
|
/**
|
|
270
267
|
* The outermost row cap on the parsed SELECT, dialect-neutral, or `null`
|
|
271
|
-
* when none is present.
|
|
268
|
+
* when none is present. Read from the AST field the dialect's grammar uses, so the
|
|
272
269
|
* caller never needs to know whether the cap was a `TOP` or `LIMIT`.
|
|
270
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect).RowCaps()` or `AnalyzePagingShape`.
|
|
273
271
|
*/
|
|
274
272
|
get OuterCap() {
|
|
275
273
|
const root = SQLParser.unwrapRoot(this._ast);
|
|
276
274
|
if (!root || root.type !== 'select')
|
|
277
275
|
return null;
|
|
278
|
-
return
|
|
276
|
+
return ReadRowCap(root, this._rowCapField);
|
|
279
277
|
}
|
|
280
278
|
/**
|
|
281
|
-
* Sets the outermost row cap
|
|
279
|
+
* Sets the outermost row cap, in the dialect's form
|
|
282
280
|
* (`TOP N` on SQL Server, `LIMIT N` elsewhere), preserving any existing
|
|
283
281
|
* OFFSET. No-op when the root isn't a SELECT.
|
|
282
|
+
* @deprecated Use the `SetRowCap` transform, which edits the SQL text as written.
|
|
284
283
|
*/
|
|
285
284
|
SetOuterCap(cap) {
|
|
286
285
|
const root = SQLParser.unwrapRoot(this._ast);
|
|
287
286
|
if (!root || root.type !== 'select')
|
|
288
287
|
return;
|
|
289
|
-
|
|
288
|
+
WriteRowCap(root, this._rowCapField, cap);
|
|
290
289
|
}
|
|
291
290
|
/**
|
|
292
291
|
* Removes the outermost row cap (TOP on SQL Server, LIMIT on PostgreSQL)
|
|
@@ -296,12 +295,13 @@ export class SQLParser {
|
|
|
296
295
|
* paged query's count reflects the full set rather than the capped subset.
|
|
297
296
|
* It clears both forms, so a PostgreSQL count drops an explicit `LIMIT` —
|
|
298
297
|
* consistent with how SQL Server's `TOP` is dropped.
|
|
298
|
+
* @deprecated Use the `SetRowCap` / `ReplaceSelectList` transforms, which edit the SQL text as written.
|
|
299
299
|
*/
|
|
300
300
|
ClearOuterCap() {
|
|
301
301
|
const root = SQLParser.unwrapRoot(this._ast);
|
|
302
302
|
if (!root || root.type !== 'select')
|
|
303
303
|
return;
|
|
304
|
-
|
|
304
|
+
ClearRowCap(root, this._rowCapField);
|
|
305
305
|
}
|
|
306
306
|
/**
|
|
307
307
|
* Removes the top-level ORDER BY from the parsed statement, following the
|
|
@@ -311,6 +311,7 @@ export class SQLParser {
|
|
|
311
311
|
*
|
|
312
312
|
* Used by the count-SQL builder: ORDER BY is irrelevant for a COUNT and is
|
|
313
313
|
* illegal inside a SQL Server CTE without TOP.
|
|
314
|
+
* @deprecated Use the `StripOrderBy` transform, which removes exactly the ORDER BY span.
|
|
314
315
|
*/
|
|
315
316
|
ClearOrderBy() {
|
|
316
317
|
let node = SQLParser.unwrapRoot(this._ast);
|
|
@@ -326,6 +327,7 @@ export class SQLParser {
|
|
|
326
327
|
* aliases, then the trailing `OPTION (...)` clause).
|
|
327
328
|
*
|
|
328
329
|
* Throws if the SQL was not parseable (check {@link IsValid} first).
|
|
330
|
+
* @deprecated Use `EditSet.Apply()` on the original text; this regenerates the SQL from the node-sql-parser tree.
|
|
329
331
|
*/
|
|
330
332
|
ToSQL() {
|
|
331
333
|
if (!this._ast)
|
|
@@ -359,6 +361,7 @@ export class SQLParser {
|
|
|
359
361
|
* Only the top level of the statement counts. The same words inside a subquery (a correlated
|
|
360
362
|
* `(SELECT … FOR JSON PATH)` column), a string literal, a quoted identifier or a comment do
|
|
361
363
|
* not stop a wrap.
|
|
364
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect)`: its top-level query exposes the `For` and `Option` tail clauses.
|
|
362
365
|
*/
|
|
363
366
|
static HasUnwrappableTrailingClause(sql, dialect) {
|
|
364
367
|
const top = SignificantTokens(LexSQL(sql, dialect)).filter(t => t.Depth === 0);
|
|
@@ -382,6 +385,7 @@ export class SQLParser {
|
|
|
382
385
|
* DELAY '…'`), which is exactly the stacked-injection class an AST scan
|
|
383
386
|
* misses (the whole string fails to parse, so the AST is null). A rendered
|
|
384
387
|
* read query must be a single statement, so any internal `;` is rejected.
|
|
388
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect).HasStackedStatements()`.
|
|
385
389
|
*/
|
|
386
390
|
static HasStackedStatements(sql, dialect) {
|
|
387
391
|
let sawSemicolon = false;
|
|
@@ -408,6 +412,7 @@ export class SQLParser {
|
|
|
408
412
|
* The dialect determines which literal and identifier forms are recognized: SQL Server
|
|
409
413
|
* `[…]`, PostgreSQL `E'…'` and dollar-quoted strings (`$$…$$`, `$tag$…$tag$`), MySQL
|
|
410
414
|
* `` `…` ``. Double-quoted identifiers are honored on every dialect.
|
|
415
|
+
* @deprecated Use `SqlTokens.Lex(sql, dialect)` and keep the tokens that are not comments.
|
|
411
416
|
*/
|
|
412
417
|
static StripComments(sql, dialect) {
|
|
413
418
|
return LexSQL(sql, dialect)
|
|
@@ -421,11 +426,12 @@ export class SQLParser {
|
|
|
421
426
|
* node-sql-parser's exprToSQL always produces backtick-quoted identifiers
|
|
422
427
|
* regardless of dialect. This method converts backticks to the dialect's
|
|
423
428
|
* native identifier quoting via `dialect.QuoteIdentifier()`.
|
|
429
|
+
* @deprecated Kept unchanged, node-sql-parser AST included, for callers that walk that tree; new code reads SQL with `SqlDocument.Parse(sql, dialect)`.
|
|
424
430
|
*/
|
|
425
431
|
static ExprToSQL(expr, dialect) {
|
|
426
432
|
const parser = new Parser();
|
|
427
433
|
let sql = parser.exprToSQL(expr);
|
|
428
|
-
sql =
|
|
434
|
+
sql = FixMaxTypeSerialization(sql);
|
|
429
435
|
// node-sql-parser emits `backtick` quoting; convert to dialect-native quoting
|
|
430
436
|
return sql.replace(/`([^`]+)`/g, (_match, name) => dialect.QuoteIdentifier(name));
|
|
431
437
|
}
|
|
@@ -434,6 +440,7 @@ export class SQLParser {
|
|
|
434
440
|
* Tokenize MJ SQL into an ordered list of tokens.
|
|
435
441
|
* Returns MJ tokens (template expressions, composition refs, block tags, comments)
|
|
436
442
|
* interleaved with SQL_TEXT tokens for the plain SQL segments.
|
|
443
|
+
* @deprecated Kept unchanged for callers that splice by its offsets; it reports tags inside SQL comments too. Use `QueryTemplate.Parse(sql, dialect)` (its `Nodes` and `Tokens`).
|
|
437
444
|
*/
|
|
438
445
|
static Tokenize(sql) {
|
|
439
446
|
return MJLexer.Tokenize(sql);
|
|
@@ -441,6 +448,7 @@ export class SQLParser {
|
|
|
441
448
|
/**
|
|
442
449
|
* Tokenize and return a summary with boolean flags.
|
|
443
450
|
* Useful for quick checks like "does this SQL have MJ extensions?"
|
|
451
|
+
* @deprecated Kept unchanged, paired with `Substitute`. Use `SqlTokens.Lex(sql, dialect).HasTemplate` and `QueryTemplate.Parse(sql, dialect)`.
|
|
444
452
|
*/
|
|
445
453
|
static Analyze(sql) {
|
|
446
454
|
return MJLexer.Parse(sql);
|
|
@@ -452,53 +460,39 @@ export class SQLParser {
|
|
|
452
460
|
* Context-aware: `sqlString` → string literal, `sqlNumber` → numeric literal,
|
|
453
461
|
* `sqlIdentifier` → bare identifier. Block tags and comments are stripped.
|
|
454
462
|
* Returns a position map for reversing the substitution.
|
|
463
|
+
* @deprecated Kept unchanged, paired with `Astify`. Read templates with `QueryTemplate.Parse(sql, dialect)`.
|
|
455
464
|
*/
|
|
456
465
|
static Substitute(sql) {
|
|
457
466
|
return MJPlaceholderSubstitution.Substitute(sql);
|
|
458
467
|
}
|
|
459
|
-
// ───
|
|
460
|
-
//
|
|
461
|
-
//
|
|
462
|
-
//
|
|
468
|
+
// ─── Extractors (deprecated) ─────────────────────────
|
|
469
|
+
// Reimplemented on the MJ Query lexer, the template tree and SqlDocument. Their result shapes
|
|
470
|
+
// are unchanged; their values are what a full structural read gives: CTE names are not tables,
|
|
471
|
+
// nothing is read from a comment or string, CTE text is the author's own, and statements
|
|
472
|
+
// node-sql-parser cannot read are extracted too.
|
|
463
473
|
/**
|
|
464
|
-
*
|
|
465
|
-
*
|
|
466
|
-
*
|
|
474
|
+
* Parses SQL and extracts its table and column references. A template is read branch by
|
|
475
|
+
* branch: the result is the union of every branch's references.
|
|
476
|
+
*
|
|
477
|
+
* - `Tables`: as {@link ExtractTableRefs}.
|
|
478
|
+
* - `Columns`: as {@link ExtractColumnRefs} (empty when the SQL could not be read completely).
|
|
479
|
+
* - `UsedASTParsing`: true when every reading of the SQL parsed completely.
|
|
467
480
|
*
|
|
468
|
-
* @param options Parse options, or just a SQL string
|
|
481
|
+
* @param options Parse options, or just a SQL string
|
|
482
|
+
* @param dialect The dialect, when `options` is a string; SQL Server when omitted
|
|
483
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect)` and its `TableReferences()` and
|
|
484
|
+
* `ColumnReferences()`, with `QueryTemplate` for templated SQL.
|
|
469
485
|
*/
|
|
470
486
|
static Parse(options, dialect) {
|
|
471
|
-
const
|
|
472
|
-
|
|
473
|
-
return { Tables: [], Columns: [], UsedASTParsing: false };
|
|
474
|
-
}
|
|
475
|
-
const cleanSQL = SQLParser.getCleanSQL(sql);
|
|
476
|
-
const tables = SQLParser.extractTablesViaAST(cleanSQL, parserDialect);
|
|
477
|
-
const usedAST = tables !== null;
|
|
478
|
-
const tableAliasMap = new Map();
|
|
479
|
-
const columnRefs = new Set();
|
|
480
|
-
if (usedAST) {
|
|
481
|
-
try {
|
|
482
|
-
const ast = SQLParser.astifyChecked(cleanSQL, parserDialect);
|
|
483
|
-
const statements = Array.isArray(ast) ? ast : [ast];
|
|
484
|
-
for (const stmt of statements) {
|
|
485
|
-
SQLParser.walkASTForExtraction(stmt, tableAliasMap, columnRefs);
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
catch { /* columns will be empty */ }
|
|
489
|
-
}
|
|
490
|
-
return {
|
|
491
|
-
Tables: tables || SQLParser.extractTablesViaRegex(cleanSQL),
|
|
492
|
-
Columns: SQLParser.buildColumnRefs(columnRefs),
|
|
493
|
-
UsedASTParsing: usedAST,
|
|
494
|
-
};
|
|
487
|
+
const sql = typeof options === 'string' ? options : options?.sql;
|
|
488
|
+
return LegacyParse(sql, typeof options === 'string' ? dialect : options?.dialect);
|
|
495
489
|
}
|
|
496
490
|
/**
|
|
497
|
-
*
|
|
498
|
-
* This is the original SQLParser.ParseWithTemplatePreprocessing() signature.
|
|
499
|
-
* Now equivalent to Parse() since all methods handle templates automatically.
|
|
491
|
+
* The same as {@link Parse}, which reads templates itself.
|
|
500
492
|
*
|
|
501
|
-
* @param options Parse options, or just a SQL string
|
|
493
|
+
* @param options Parse options, or just a SQL string
|
|
494
|
+
* @param dialect The dialect, when `options` is a string; SQL Server when omitted
|
|
495
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect)`, with `QueryTemplate` for templated SQL.
|
|
502
496
|
*/
|
|
503
497
|
static ParseWithTemplatePreprocessing(options, dialect) {
|
|
504
498
|
return SQLParser.Parse(options, dialect);
|
|
@@ -507,248 +501,114 @@ export class SQLParser {
|
|
|
507
501
|
/**
|
|
508
502
|
* Extract all table/view references from this instance's SQL.
|
|
509
503
|
* Convenience delegate to the static overload.
|
|
504
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect).TableReferences()`.
|
|
510
505
|
*/
|
|
511
506
|
ExtractTableRefs() {
|
|
512
507
|
return SQLParser.ExtractTableRefs(this._sql, this._dialect);
|
|
513
508
|
}
|
|
514
509
|
/**
|
|
515
|
-
*
|
|
516
|
-
*
|
|
510
|
+
* The tables and views the SQL reads, anywhere in the statement (subqueries and CTE bodies
|
|
511
|
+
* included), one entry per schema and table:
|
|
512
|
+
*
|
|
513
|
+
* - a CTE reference, a table-valued function and a derived table are not tables;
|
|
514
|
+
* - names inside comments and string literals are never read, nor are the `FROM` words of
|
|
515
|
+
* `EXTRACT(… FROM …)`, `TRIM(… FROM …)` and `IS DISTINCT FROM`;
|
|
516
|
+
* - an unqualified name gets the dialect's default schema (`dbo` on SQL Server, `public` on
|
|
517
|
+
* PostgreSQL), so `SchemaName` is always set;
|
|
518
|
+
* - a template is read branch by branch, and the tables of every branch are reported; a
|
|
519
|
+
* `{{query:"…"}}` composition is not a table.
|
|
520
|
+
*
|
|
521
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect).TableReferences()`, which returns `null`
|
|
522
|
+
* for an unwritten schema and marks CTE and function references by `Kind`.
|
|
517
523
|
*/
|
|
518
524
|
static ExtractTableRefs(sql, dialect) {
|
|
519
|
-
|
|
520
|
-
return [];
|
|
521
|
-
const cleanSQL = SQLParser.getCleanSQL(sql);
|
|
522
|
-
const parserDialect = dialect?.ParserDialect || 'TransactSQL';
|
|
523
|
-
const astResult = SQLParser.extractTablesViaAST(cleanSQL, parserDialect);
|
|
524
|
-
if (astResult)
|
|
525
|
-
return astResult;
|
|
526
|
-
return SQLParser.extractTablesViaRegex(cleanSQL);
|
|
525
|
+
return LegacyTableReferences(sql, dialect);
|
|
527
526
|
}
|
|
528
527
|
/**
|
|
529
528
|
* Extract all column references from this instance's SQL.
|
|
530
529
|
* Convenience delegate to the static overload.
|
|
530
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect).ColumnReferences()`.
|
|
531
531
|
*/
|
|
532
532
|
ExtractColumnRefs() {
|
|
533
533
|
return SQLParser.ExtractColumnRefs(this._sql, this._dialect);
|
|
534
534
|
}
|
|
535
535
|
/**
|
|
536
|
-
*
|
|
537
|
-
*
|
|
536
|
+
* Every identifier path that can be a column, in every clause (select list, joins, WHERE,
|
|
537
|
+
* GROUP BY, HAVING, ORDER BY, window and `WITHIN GROUP` clauses, subqueries), as
|
|
538
|
+
* `{ ColumnName, TableQualifier }`, one entry per written `qualifier.column`. A template is
|
|
539
|
+
* read branch by branch. Returns `[]` when the SQL cannot be read completely; use
|
|
540
|
+
* {@link ExtractColumnRefsChecked} to tell that apart from SQL with no column references.
|
|
541
|
+
*
|
|
542
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect).ColumnReferences()`, which also binds each
|
|
543
|
+
* reference to its source.
|
|
538
544
|
*/
|
|
539
545
|
static ExtractColumnRefs(sql, dialect) {
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
const statements = Array.isArray(ast) ? ast : [ast];
|
|
549
|
-
for (const statement of statements) {
|
|
550
|
-
SQLParser.walkASTForExtraction(statement, tableAliasMap, columnRefs);
|
|
551
|
-
}
|
|
552
|
-
return SQLParser.buildColumnRefs(columnRefs);
|
|
553
|
-
}
|
|
554
|
-
catch {
|
|
555
|
-
return [];
|
|
556
|
-
}
|
|
546
|
+
return LegacyColumnReferencesChecked(sql, dialect).Columns;
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* {@link ExtractColumnRefs}, with whether the SQL could be read completely: `Complete: false`
|
|
550
|
+
* (and no columns) means the parse failed, not that the SQL names no column.
|
|
551
|
+
*/
|
|
552
|
+
static ExtractColumnRefsChecked(sql, dialect) {
|
|
553
|
+
return LegacyColumnReferencesChecked(sql, dialect);
|
|
557
554
|
}
|
|
558
555
|
// ─── SELECT Column Extraction ─────────────────────────
|
|
559
556
|
/**
|
|
560
557
|
* Extract SELECT clause columns from this instance's SQL.
|
|
561
558
|
* Convenience delegate to the static overload.
|
|
559
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect).OutputItems()`.
|
|
562
560
|
*/
|
|
563
561
|
ExtractSelectColumns() {
|
|
564
562
|
return SQLParser.ExtractSelectColumns(this._sql, this._dialect);
|
|
565
563
|
}
|
|
566
564
|
/**
|
|
567
|
-
* Extracts the SELECT
|
|
568
|
-
*
|
|
569
|
-
* Handles:
|
|
565
|
+
* Extracts the first statement's SELECT columns with their output names, source columns, and
|
|
566
|
+
* table qualifiers (for a set operation, the first branch's):
|
|
570
567
|
* - Simple columns: `u.Name` → { OutputName: "Name", SourceColumn: "Name", TableQualifier: "u" }
|
|
571
|
-
* - AS
|
|
572
|
-
* - Expressions: `COUNT(*)` → { OutputName: "COUNT(
|
|
573
|
-
* -
|
|
568
|
+
* - Aliases (`AS a`, `a = expr` on SQL Server): `e.Name AS EntityName` → { OutputName: "EntityName", SourceColumn: "Name", TableQualifier: "e" }
|
|
569
|
+
* - Expressions: `COUNT(*)` → { OutputName: "COUNT(...)", SourceColumn: "COUNT(...)", IsExpression: true }; other unnamed expressions are `EXPR`
|
|
570
|
+
* - Stars: `*` and `t.*` → OutputName `*`, with `t` as the qualifier
|
|
571
|
+
*
|
|
572
|
+
* A template is read through its base render (every first branch). Returns `[]` when the SQL
|
|
573
|
+
* cannot be read completely; use {@link ExtractSelectColumnsChecked} to tell that apart from a
|
|
574
|
+
* statement with no select list.
|
|
575
|
+
*
|
|
576
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect).OutputItems()`.
|
|
574
577
|
*/
|
|
575
578
|
static ExtractSelectColumns(sql, dialect) {
|
|
576
|
-
|
|
577
|
-
return [];
|
|
578
|
-
const cleanSQL = SQLParser.getCleanSQL(sql);
|
|
579
|
-
try {
|
|
580
|
-
const ast = SQLParser.astifyChecked(cleanSQL, dialect.ParserDialect);
|
|
581
|
-
const statements = Array.isArray(ast) ? ast : [ast];
|
|
582
|
-
const columns = [];
|
|
583
|
-
for (const statement of statements) {
|
|
584
|
-
const selectColumns = SQLParser.extractSelectColumnsFromAST(statement);
|
|
585
|
-
columns.push(...selectColumns);
|
|
586
|
-
}
|
|
587
|
-
return columns;
|
|
588
|
-
}
|
|
589
|
-
catch {
|
|
590
|
-
return [];
|
|
591
|
-
}
|
|
579
|
+
return LegacySelectColumnsChecked(sql, dialect).Columns;
|
|
592
580
|
}
|
|
593
581
|
/**
|
|
594
|
-
*
|
|
582
|
+
* {@link ExtractSelectColumns}, with whether the SQL could be read completely: `Complete:
|
|
583
|
+
* false` (and no columns) means the parse failed, not that the statement has no select list.
|
|
595
584
|
*/
|
|
596
|
-
static
|
|
597
|
-
|
|
598
|
-
if (!node || typeof node !== 'object')
|
|
599
|
-
return columns;
|
|
600
|
-
const stmt = node;
|
|
601
|
-
// node-sql-parser SELECT statements have a `columns` array
|
|
602
|
-
const cols = stmt['columns'];
|
|
603
|
-
if (!Array.isArray(cols))
|
|
604
|
-
return columns;
|
|
605
|
-
for (const col of cols) {
|
|
606
|
-
if (col === '*') {
|
|
607
|
-
columns.push({
|
|
608
|
-
OutputName: '*',
|
|
609
|
-
SourceColumn: '*',
|
|
610
|
-
TableQualifier: null,
|
|
611
|
-
IsExpression: false,
|
|
612
|
-
});
|
|
613
|
-
continue;
|
|
614
|
-
}
|
|
615
|
-
if (!col || typeof col !== 'object')
|
|
616
|
-
continue;
|
|
617
|
-
const colNode = col;
|
|
618
|
-
// The output alias (AS name), or null
|
|
619
|
-
const asAlias = colNode['as'];
|
|
620
|
-
// The expression node
|
|
621
|
-
const expr = colNode['expr'];
|
|
622
|
-
if (!expr)
|
|
623
|
-
continue;
|
|
624
|
-
const exprType = expr['type'];
|
|
625
|
-
if (exprType === 'column_ref') {
|
|
626
|
-
const columnName = SQLParser.unwrapIdentifier(expr['column']) ?? 'UNKNOWN';
|
|
627
|
-
const table = SQLParser.unwrapIdentifier(expr['table']);
|
|
628
|
-
columns.push({
|
|
629
|
-
OutputName: asAlias ?? columnName,
|
|
630
|
-
SourceColumn: columnName,
|
|
631
|
-
TableQualifier: table,
|
|
632
|
-
IsExpression: false,
|
|
633
|
-
});
|
|
634
|
-
}
|
|
635
|
-
else {
|
|
636
|
-
// Expression (aggregate, function, etc.)
|
|
637
|
-
const outputName = asAlias ?? SQLParser.exprToString(expr);
|
|
638
|
-
columns.push({
|
|
639
|
-
OutputName: outputName,
|
|
640
|
-
SourceColumn: outputName,
|
|
641
|
-
TableQualifier: null,
|
|
642
|
-
IsExpression: true,
|
|
643
|
-
});
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
return columns;
|
|
647
|
-
}
|
|
648
|
-
/**
|
|
649
|
-
* Unwraps an AST identifier node to a plain string.
|
|
650
|
-
* node-sql-parser represents PostgreSQL double-quoted identifiers as
|
|
651
|
-
* `{ expr: { type: 'double_quote_string', value: 'Name' } }` instead
|
|
652
|
-
* of a plain string `'Name'`. This helper normalizes both representations.
|
|
653
|
-
*/
|
|
654
|
-
static unwrapIdentifier(node) {
|
|
655
|
-
if (node === null || node === undefined)
|
|
656
|
-
return null;
|
|
657
|
-
if (typeof node === 'string')
|
|
658
|
-
return node;
|
|
659
|
-
if (typeof node === 'object') {
|
|
660
|
-
const obj = node;
|
|
661
|
-
// PG AST identifier nodes: { type: 'double_quote_string'|'default', value: 'Name' }
|
|
662
|
-
// 'double_quote_string' = quoted identifier ("Name"), 'default' = unquoted (membershiptype)
|
|
663
|
-
if (obj['type'] === 'double_quote_string' || obj['type'] === 'single_quote_string' || obj['type'] === 'default') {
|
|
664
|
-
return obj['value'] ?? null;
|
|
665
|
-
}
|
|
666
|
-
// Wrapped in expr: { expr: { type: 'double_quote_string', value: 'Name' } }
|
|
667
|
-
if (obj['expr'] && typeof obj['expr'] === 'object') {
|
|
668
|
-
return SQLParser.unwrapIdentifier(obj['expr']);
|
|
669
|
-
}
|
|
670
|
-
}
|
|
671
|
-
return null;
|
|
672
|
-
}
|
|
673
|
-
/**
|
|
674
|
-
* Best-effort string representation of an AST expression node (for expression columns).
|
|
675
|
-
*/
|
|
676
|
-
static exprToString(expr) {
|
|
677
|
-
const type = expr['type'];
|
|
678
|
-
if (type === 'aggr_func') {
|
|
679
|
-
const name = expr['name'] ?? 'EXPR';
|
|
680
|
-
return `${name}(...)`;
|
|
681
|
-
}
|
|
682
|
-
if (type === 'function') {
|
|
683
|
-
const name = expr['name']?.['name'] ?? 'FUNC';
|
|
684
|
-
return `${name}(...)`;
|
|
685
|
-
}
|
|
686
|
-
return 'EXPR';
|
|
585
|
+
static ExtractSelectColumnsChecked(sql, dialect) {
|
|
586
|
+
return LegacySelectColumnsChecked(sql, dialect);
|
|
687
587
|
}
|
|
688
588
|
// ─── CTE Extraction ────────────────────────────────
|
|
689
589
|
/**
|
|
690
590
|
* Extract CTE definitions from this instance's SQL.
|
|
691
591
|
* Convenience delegate to the static overload.
|
|
592
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect).CTEs()` or `SplitLeadingCTEs`.
|
|
692
593
|
*/
|
|
693
594
|
ExtractCTEs() {
|
|
694
595
|
return SQLParser.ExtractCTEs(this._sql, this._dialect);
|
|
695
596
|
}
|
|
696
597
|
/**
|
|
697
|
-
*
|
|
598
|
+
* Splits a statement that starts with a WITH clause (after any leading comments) into its CTE
|
|
599
|
+
* definitions and the main statement, as written.
|
|
698
600
|
*
|
|
699
601
|
* Given: `WITH A AS (SELECT 1), B AS (SELECT 2) SELECT A.x, B.y FROM A, B`
|
|
700
|
-
* Returns: CTEDefinitions: ["A AS (
|
|
602
|
+
* Returns: CTEDefinitions: ["A AS (SELECT 1)", "B AS (SELECT 2)"], MainStatement: "SELECT A.x, B.y FROM A, B"
|
|
603
|
+
*
|
|
604
|
+
* Each definition is the exact text of `name [(columns)] AS (body)`, quoting included. The
|
|
605
|
+
* main statement is the rest of the text, trimmed. `UsedASTParsing` is true when the
|
|
606
|
+
* statement parsed completely. Returns `null` when the SQL does not start with WITH.
|
|
701
607
|
*
|
|
702
|
-
*
|
|
703
|
-
* falls back to paren-depth scanning if AST fails (e.g., Nunjucks-templated SQL).
|
|
608
|
+
* @deprecated Use `SqlDocument.Parse(sql, dialect).CTEs()` or `SplitLeadingCTEs`.
|
|
704
609
|
*/
|
|
705
610
|
static ExtractCTEs(sql, dialect) {
|
|
706
|
-
|
|
707
|
-
// queries with a descriptive header block are recognized as CTEs.
|
|
708
|
-
// The AST parser handles comments natively, but when it fails
|
|
709
|
-
// (e.g. TRY_CAST, Nunjucks templates) the regex fallback needs
|
|
710
|
-
// the comments gone to see the WITH keyword.
|
|
711
|
-
const stripped = SQLParser.skipLeadingCommentsAndWhitespace(sql);
|
|
712
|
-
if (!/^WITH\s/i.test(stripped))
|
|
713
|
-
return null;
|
|
714
|
-
const astResult = SQLParser.extractCTEsViaAST(stripped, dialect.ParserDialect);
|
|
715
|
-
if (astResult)
|
|
716
|
-
return astResult;
|
|
717
|
-
return SQLParser.extractCTEsViaRegex(stripped);
|
|
718
|
-
}
|
|
719
|
-
/**
|
|
720
|
-
* Strips leading whitespace AND SQL comments from a string.
|
|
721
|
-
* Handles block comments and line comments (-- ...).
|
|
722
|
-
* Returns the remainder starting at the first non-whitespace, non-comment character.
|
|
723
|
-
*/
|
|
724
|
-
static skipLeadingCommentsAndWhitespace(sql) {
|
|
725
|
-
let i = 0;
|
|
726
|
-
const len = sql.length;
|
|
727
|
-
while (i < len) {
|
|
728
|
-
const ch = sql[i];
|
|
729
|
-
if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
|
|
730
|
-
i++;
|
|
731
|
-
continue;
|
|
732
|
-
}
|
|
733
|
-
if (ch === '/' && i + 1 < len && sql[i + 1] === '*') {
|
|
734
|
-
i += 2;
|
|
735
|
-
while (i < len - 1 && !(sql[i] === '*' && sql[i + 1] === '/'))
|
|
736
|
-
i++;
|
|
737
|
-
if (i < len - 1)
|
|
738
|
-
i += 2;
|
|
739
|
-
else
|
|
740
|
-
i = len;
|
|
741
|
-
continue;
|
|
742
|
-
}
|
|
743
|
-
if (ch === '-' && i + 1 < len && sql[i + 1] === '-') {
|
|
744
|
-
i += 2;
|
|
745
|
-
while (i < len && sql[i] !== '\n')
|
|
746
|
-
i++;
|
|
747
|
-
continue;
|
|
748
|
-
}
|
|
749
|
-
break;
|
|
750
|
-
}
|
|
751
|
-
return sql.substring(i);
|
|
611
|
+
return LegacyCTEExtraction(sql, dialect);
|
|
752
612
|
}
|
|
753
613
|
// ─── MJ Template Extraction ────────────────────────
|
|
754
614
|
/**
|
|
@@ -757,12 +617,13 @@ export class SQLParser {
|
|
|
757
617
|
* `{% elif %}`, `{% for %}` and `{% set %}` tags.
|
|
758
618
|
*
|
|
759
619
|
* Example: `RenameTemplateVariable("WHERE x = {{ region | sqlString }}", "region", "userRegion")`
|
|
760
|
-
* → `"WHERE x = {{
|
|
620
|
+
* → `"WHERE x = {{userRegion | sqlString}}"`
|
|
761
621
|
*
|
|
762
|
-
*
|
|
622
|
+
* @deprecated Rename through the `QueryTemplate` tree (`Parameters()` gives every use's span)
|
|
623
|
+
* and an `EditSet`.
|
|
763
624
|
*/
|
|
764
625
|
static RenameTemplateVariable(sql, oldName, newName) {
|
|
765
|
-
return
|
|
626
|
+
return ReplaceLegacyTemplateVariable(sql, oldName, filters => RebuildLegacyTemplateExpr(newName, filters), newName);
|
|
766
627
|
}
|
|
767
628
|
/**
|
|
768
629
|
* Substitutes a template variable with a literal value in all `{{ variable | filters }}` expressions.
|
|
@@ -776,332 +637,58 @@ export class SQLParser {
|
|
|
776
637
|
* `{% for %}` and `{% set %}` tags are replaced with it too, so conditions see the value.
|
|
777
638
|
* It must be a template-language literal (`"West"`, `42`), not a SQL one.
|
|
778
639
|
*
|
|
779
|
-
*
|
|
640
|
+
* @deprecated Substitute through the `QueryTemplate` tree (`Parameters()` gives every use's
|
|
641
|
+
* span) and an `EditSet`.
|
|
780
642
|
*/
|
|
781
643
|
static SubstituteTemplateVariable(sql, variableName, literalValue, tagLiteral) {
|
|
782
|
-
return
|
|
783
|
-
}
|
|
784
|
-
/**
|
|
785
|
-
* Replaces a variable's `{{ }}` expressions with `exprText(token)` and, when `tagText` is
|
|
786
|
-
* given, its reads inside block tags with `tagText`. Edits apply from the end of the SQL so
|
|
787
|
-
* earlier offsets stay valid.
|
|
788
|
-
*/
|
|
789
|
-
static replaceTemplateVariable(sql, variableName, exprText, tagText) {
|
|
790
|
-
const nameLower = variableName.toLowerCase();
|
|
791
|
-
const edits = [];
|
|
792
|
-
for (const token of MJLexer.Tokenize(sql)) {
|
|
793
|
-
if (token.type === 'MJ_TEMPLATE_EXPR' && token.parsed.variable.toLowerCase() === nameLower) {
|
|
794
|
-
edits.push({ token, text: exprText(token) });
|
|
795
|
-
}
|
|
796
|
-
else if (tagText !== undefined && VARIABLE_READING_TAGS.has(token.type)) {
|
|
797
|
-
edits.push({ token, text: ReplaceVariableInTag(token.raw, variableName, tagText) });
|
|
798
|
-
}
|
|
799
|
-
}
|
|
800
|
-
let result = sql;
|
|
801
|
-
for (const { token, text } of edits.sort((a, b) => b.token.start - a.token.start)) {
|
|
802
|
-
result = result.substring(0, token.start) + text + result.substring(token.end);
|
|
803
|
-
}
|
|
804
|
-
return result;
|
|
644
|
+
return ReplaceLegacyTemplateVariable(sql, variableName, () => literalValue, tagLiteral);
|
|
805
645
|
}
|
|
806
646
|
/**
|
|
807
|
-
*
|
|
808
|
-
*
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
return `{{${variable}}}`;
|
|
813
|
-
const filterChain = filters.map(f => {
|
|
814
|
-
if (f.args.length === 0)
|
|
815
|
-
return f.name;
|
|
816
|
-
const args = f.args.map(a => typeof a === 'string' ? `'${a}'` : String(a)).join(', ');
|
|
817
|
-
return `${f.name}(${args})`;
|
|
818
|
-
}).join(' | ');
|
|
819
|
-
return `{{${variable} | ${filterChain}}}`;
|
|
820
|
-
}
|
|
821
|
-
/**
|
|
822
|
-
* Extract all {{ variable | filter }} expressions from SQL.
|
|
823
|
-
* Returns structured info for each expression including variable name and filter chain.
|
|
647
|
+
* Every `{{ variable | filter }}` expression, with its variable name and filter chain. A tag
|
|
648
|
+
* inside a SQL comment is inert and is not reported.
|
|
649
|
+
*
|
|
650
|
+
* @deprecated Use `QueryTemplate.Parse(sql, dialect)`: its `Nodes` hold every expression, and
|
|
651
|
+
* `Parameters()` the names they read.
|
|
824
652
|
*/
|
|
825
653
|
static ExtractTemplateExpressions(sql) {
|
|
826
|
-
|
|
827
|
-
const exprs = [];
|
|
828
|
-
for (const token of tokens) {
|
|
829
|
-
if (token.type === 'MJ_TEMPLATE_EXPR') {
|
|
830
|
-
const parsed = token.parsed;
|
|
831
|
-
exprs.push({
|
|
832
|
-
type: 'mj_template_expr',
|
|
833
|
-
variable: parsed.variable,
|
|
834
|
-
filters: parsed.filters,
|
|
835
|
-
raw: token.raw,
|
|
836
|
-
});
|
|
837
|
-
}
|
|
838
|
-
}
|
|
839
|
-
return exprs;
|
|
654
|
+
return LegacyTemplateExpressions(sql);
|
|
840
655
|
}
|
|
841
656
|
/**
|
|
842
|
-
*
|
|
843
|
-
*
|
|
657
|
+
* Every `{{query:"…"}}` composition reference, with its category path, query name and
|
|
658
|
+
* parameters. A reference inside a SQL comment is inert and is not reported.
|
|
659
|
+
*
|
|
660
|
+
* @deprecated Use `QueryTemplate.Parse(sql, dialect).CompositionReferences()`.
|
|
844
661
|
*/
|
|
845
662
|
static ExtractCompositionRefs(sql) {
|
|
846
|
-
|
|
847
|
-
const refs = [];
|
|
848
|
-
for (const token of tokens) {
|
|
849
|
-
if (token.type === 'MJ_COMPOSITION_REF') {
|
|
850
|
-
const parsed = token.parsed;
|
|
851
|
-
refs.push({
|
|
852
|
-
type: 'mj_composition_ref',
|
|
853
|
-
categoryPath: parsed.categoryPath,
|
|
854
|
-
queryName: parsed.queryName,
|
|
855
|
-
parameters: parsed.parameters,
|
|
856
|
-
raw: token.raw,
|
|
857
|
-
});
|
|
858
|
-
}
|
|
859
|
-
}
|
|
860
|
-
return refs;
|
|
663
|
+
return LegacyCompositionRefs(sql);
|
|
861
664
|
}
|
|
862
665
|
/**
|
|
863
|
-
*
|
|
666
|
+
* The `{% if %}` blocks, each with its if/elif/else branches: the condition text and the
|
|
667
|
+
* branch body's exact source text. A tag inside a SQL comment is inert.
|
|
668
|
+
*
|
|
669
|
+
* @deprecated Use `QueryTemplate.Parse(sql, dialect)`: its `If` nodes hold every branch.
|
|
864
670
|
*/
|
|
865
671
|
static ExtractConditionalBlocks(sql) {
|
|
866
|
-
|
|
867
|
-
const blocks = [];
|
|
868
|
-
const stack = [];
|
|
869
|
-
for (const token of tokens) {
|
|
870
|
-
switch (token.type) {
|
|
871
|
-
case 'MJ_IF_OPEN': {
|
|
872
|
-
const parsed = token.parsed;
|
|
873
|
-
stack.push({
|
|
874
|
-
branches: [{ condition: parsed.expression, body: { raw: '', nodes: [] } }],
|
|
875
|
-
raw: token.raw,
|
|
876
|
-
});
|
|
877
|
-
break;
|
|
878
|
-
}
|
|
879
|
-
case 'MJ_ELIF': {
|
|
880
|
-
const parsed = token.parsed;
|
|
881
|
-
const current = stack[stack.length - 1];
|
|
882
|
-
if (current) {
|
|
883
|
-
current.raw += token.raw;
|
|
884
|
-
current.branches.push({ condition: parsed.expression, body: { raw: '', nodes: [] } });
|
|
885
|
-
}
|
|
886
|
-
break;
|
|
887
|
-
}
|
|
888
|
-
case 'MJ_ELSE': {
|
|
889
|
-
const current = stack[stack.length - 1];
|
|
890
|
-
if (current) {
|
|
891
|
-
current.raw += token.raw;
|
|
892
|
-
current.branches.push({ condition: null, body: { raw: '', nodes: [] } });
|
|
893
|
-
}
|
|
894
|
-
break;
|
|
895
|
-
}
|
|
896
|
-
case 'MJ_ENDIF': {
|
|
897
|
-
const completed = stack.pop();
|
|
898
|
-
if (completed) {
|
|
899
|
-
completed.raw += token.raw;
|
|
900
|
-
blocks.push({ type: 'mj_conditional', branches: completed.branches, raw: completed.raw });
|
|
901
|
-
}
|
|
902
|
-
break;
|
|
903
|
-
}
|
|
904
|
-
default: {
|
|
905
|
-
const current = stack[stack.length - 1];
|
|
906
|
-
if (current && current.branches.length > 0) {
|
|
907
|
-
const lastBranch = current.branches[current.branches.length - 1];
|
|
908
|
-
lastBranch.body.raw += token.raw;
|
|
909
|
-
SQLParser.addNodeToFragment(token, lastBranch);
|
|
910
|
-
current.raw += token.raw;
|
|
911
|
-
}
|
|
912
|
-
}
|
|
913
|
-
}
|
|
914
|
-
}
|
|
915
|
-
return blocks;
|
|
672
|
+
return LegacyConditionalBlocks(sql);
|
|
916
673
|
}
|
|
917
674
|
/**
|
|
918
|
-
*
|
|
675
|
+
* The parameters a template reads, with the type its SQL filters imply, whether it is
|
|
676
|
+
* required, its default and its filters:
|
|
919
677
|
*
|
|
920
|
-
*
|
|
921
|
-
*
|
|
922
|
-
*
|
|
923
|
-
*
|
|
924
|
-
*
|
|
925
|
-
* `
|
|
678
|
+
* - required when at least one use sits outside every `{% if %}` block and has no
|
|
679
|
+
* `default(…)`; a name used only inside conditional blocks, or only in `{% if %}`
|
|
680
|
+
* conditions, is optional;
|
|
681
|
+
* - the iterable of a `{% for %}` is an `array` parameter; the loop variable, `loop.*`,
|
|
682
|
+
* `{% set %}` names and `Context.*` tokens are not parameters;
|
|
683
|
+
* - the type comes from the last SQL filter (`sqlString` → string, `sqlNumber` → number, …);
|
|
684
|
+
* a name read only by conditions is a `string`;
|
|
685
|
+
* - the default comes from a `default(…)` filter, or else from a `{% else %}` branch that
|
|
686
|
+
* compares with a single literal.
|
|
926
687
|
*
|
|
927
|
-
*
|
|
928
|
-
* `{% for kw in OrgKeywords %}` as a required parameter and failed to
|
|
929
|
-
* register `OrgKeywords` at all. See `__tests__/extract-parameter-info-loops.test.ts`
|
|
930
|
-
* and `SKIP-QUERY-RENDERING-BUGS.md` (Bug B) at the repo root.
|
|
931
|
-
*
|
|
932
|
-
* Infers type from filters, isRequired from conditional block context.
|
|
688
|
+
* @deprecated Use `QueryTemplate.Parse(sql, dialect).Parameters()`.
|
|
933
689
|
*/
|
|
934
690
|
static ExtractParameterInfo(sql) {
|
|
935
|
-
|
|
936
|
-
const paramMap = new Map();
|
|
937
|
-
// Lexical scope stack: each entry is the set of loop-local variable
|
|
938
|
-
// names introduced by an enclosing {% for %} block.
|
|
939
|
-
const loopScopes = [];
|
|
940
|
-
// Set of every loop-local identifier ever introduced during the walk
|
|
941
|
-
// (across all scopes). Used to filter out names that
|
|
942
|
-
// `findConditionalVariables` may have picked up from {% if %} guards
|
|
943
|
-
// surrounding a {{ loopLocal }} expression.
|
|
944
|
-
const everSeenLoopLocals = new Set();
|
|
945
|
-
const isLoopLocal = (variable) => {
|
|
946
|
-
// Match the root identifier (e.g. `kw` in `kw.foo`, `kw` in `kw|filter`).
|
|
947
|
-
const root = variable.split(/[.\s|]/, 1)[0];
|
|
948
|
-
for (const scope of loopScopes) {
|
|
949
|
-
if (scope.has(root))
|
|
950
|
-
return true;
|
|
951
|
-
}
|
|
952
|
-
return false;
|
|
953
|
-
};
|
|
954
|
-
// Track which iterables appear in {% for X in Y %} so we can register
|
|
955
|
-
// them as array parameters even if Y is never used in a {{ }} expression.
|
|
956
|
-
// Maps iterable name → whether it appears outside a containing {% if %}
|
|
957
|
-
// block (used only to differentiate required vs optional later).
|
|
958
|
-
const loopIterables = new Map();
|
|
959
|
-
let conditionalDepth = 0;
|
|
960
|
-
for (const token of tokens) {
|
|
961
|
-
switch (token.type) {
|
|
962
|
-
case 'MJ_FOR_OPEN': {
|
|
963
|
-
const parsed = token.parsed;
|
|
964
|
-
loopScopes.push(new Set(parsed.loopVariable ? [parsed.loopVariable] : []));
|
|
965
|
-
if (parsed.loopVariable) {
|
|
966
|
-
everSeenLoopLocals.add(parsed.loopVariable);
|
|
967
|
-
}
|
|
968
|
-
if (parsed.loopIterable) {
|
|
969
|
-
// Iterable identifier — strip filters/whitespace so
|
|
970
|
-
// `tags | sort` becomes `tags`.
|
|
971
|
-
const iterableName = parsed.loopIterable.split(/[.\s|]/, 1)[0];
|
|
972
|
-
if (iterableName && !SQLParser.JINJA_KEYWORDS.has(iterableName.toLowerCase())) {
|
|
973
|
-
const existing = loopIterables.get(iterableName);
|
|
974
|
-
// Required only when the for tag is at the top level
|
|
975
|
-
// (not wrapped in any {% if %}). If wrapped, the iterable
|
|
976
|
-
// becomes optional — same convention as condition-only vars.
|
|
977
|
-
const isRequired = existing
|
|
978
|
-
? existing.isRequired || conditionalDepth === 0
|
|
979
|
-
: conditionalDepth === 0;
|
|
980
|
-
loopIterables.set(iterableName, { isRequired });
|
|
981
|
-
}
|
|
982
|
-
}
|
|
983
|
-
break;
|
|
984
|
-
}
|
|
985
|
-
case 'MJ_ENDFOR':
|
|
986
|
-
loopScopes.pop();
|
|
987
|
-
break;
|
|
988
|
-
case 'MJ_IF_OPEN':
|
|
989
|
-
conditionalDepth++;
|
|
990
|
-
break;
|
|
991
|
-
case 'MJ_ENDIF':
|
|
992
|
-
conditionalDepth = Math.max(0, conditionalDepth - 1);
|
|
993
|
-
break;
|
|
994
|
-
case 'MJ_TEMPLATE_EXPR': {
|
|
995
|
-
const parsed = token.parsed;
|
|
996
|
-
const varName = parsed.variable;
|
|
997
|
-
// Skip if the variable's root is a loop local, or if the
|
|
998
|
-
// variable is a Nunjucks built-in (loop, loop.last, etc.).
|
|
999
|
-
if (isLoopLocal(varName))
|
|
1000
|
-
break;
|
|
1001
|
-
const root = varName.split(/[.\s]/, 1)[0];
|
|
1002
|
-
if (root.toLowerCase() === 'loop')
|
|
1003
|
-
break;
|
|
1004
|
-
// A `default(…)` filter renders the expression without the parameter, so a use
|
|
1005
|
-
// with one does not make the parameter required; any use without one does.
|
|
1006
|
-
const defaultValue = SQLParser.extractDefaultValue(parsed.filters);
|
|
1007
|
-
const hasDefault = parsed.filters.some(f => f.name === 'default');
|
|
1008
|
-
const existing = paramMap.get(varName);
|
|
1009
|
-
if (!existing) {
|
|
1010
|
-
paramMap.set(varName, {
|
|
1011
|
-
name: varName,
|
|
1012
|
-
type: SQLParser.inferTypeFromFilters(parsed.filters),
|
|
1013
|
-
isRequired: !hasDefault,
|
|
1014
|
-
defaultValue,
|
|
1015
|
-
filters: parsed.filters,
|
|
1016
|
-
usageLocations: [],
|
|
1017
|
-
});
|
|
1018
|
-
}
|
|
1019
|
-
else {
|
|
1020
|
-
if (!hasDefault)
|
|
1021
|
-
existing.isRequired = true;
|
|
1022
|
-
if (existing.defaultValue === null)
|
|
1023
|
-
existing.defaultValue = defaultValue;
|
|
1024
|
-
}
|
|
1025
|
-
paramMap.get(varName).usageLocations.push(token.raw);
|
|
1026
|
-
break;
|
|
1027
|
-
}
|
|
1028
|
-
}
|
|
1029
|
-
}
|
|
1030
|
-
// Predicates used to filter out names that look like parameters but
|
|
1031
|
-
// are actually loop locals or Nunjucks built-ins.
|
|
1032
|
-
const isLoopBuiltin = (varName) => {
|
|
1033
|
-
const root = varName.split(/[.\s]/, 1)[0].toLowerCase();
|
|
1034
|
-
// `loop` is the Nunjucks-provided namespace inside {% for %} blocks
|
|
1035
|
-
// (`loop.last`, `loop.first`, `loop.index`, etc.). Members of the
|
|
1036
|
-
// namespace get extracted as bare identifiers (`last`, `first`,
|
|
1037
|
-
// `index`) by addConditionVariables's regex split.
|
|
1038
|
-
return root === 'loop'
|
|
1039
|
-
|| root === 'last' || root === 'first'
|
|
1040
|
-
|| root === 'index' || root === 'index0'
|
|
1041
|
-
|| root === 'revindex' || root === 'revindex0'
|
|
1042
|
-
|| root === 'length' || root === 'cycle';
|
|
1043
|
-
};
|
|
1044
|
-
const conditionalVars = SQLParser.findConditionalVariables(tokens);
|
|
1045
|
-
for (const [varName, param] of paramMap) {
|
|
1046
|
-
if (conditionalVars.onlyInConditional.has(varName)) {
|
|
1047
|
-
param.isRequired = false;
|
|
1048
|
-
}
|
|
1049
|
-
}
|
|
1050
|
-
// Variables that appear only in {% if %}/{% elif %} condition expressions
|
|
1051
|
-
// (never in a {{ }} template expression) still need to be surfaced as
|
|
1052
|
-
// optional parameters so callers can supply them at runtime.
|
|
1053
|
-
// EXCEPT: loop locals (introduced by {% for %}), Nunjucks loop built-ins
|
|
1054
|
-
// (loop, loop.last, etc.), and identifiers we've already classified as
|
|
1055
|
-
// loop iterables.
|
|
1056
|
-
for (const varName of conditionalVars.onlyInConditional) {
|
|
1057
|
-
if (paramMap.has(varName))
|
|
1058
|
-
continue;
|
|
1059
|
-
const root = varName.split(/[.\s]/, 1)[0];
|
|
1060
|
-
if (everSeenLoopLocals.has(root))
|
|
1061
|
-
continue;
|
|
1062
|
-
if (isLoopBuiltin(varName))
|
|
1063
|
-
continue;
|
|
1064
|
-
if (loopIterables.has(varName))
|
|
1065
|
-
continue;
|
|
1066
|
-
paramMap.set(varName, {
|
|
1067
|
-
name: varName,
|
|
1068
|
-
type: 'string',
|
|
1069
|
-
isRequired: false,
|
|
1070
|
-
defaultValue: null,
|
|
1071
|
-
filters: [],
|
|
1072
|
-
usageLocations: [],
|
|
1073
|
-
});
|
|
1074
|
-
}
|
|
1075
|
-
// Register loop iterables that aren't already in the param map.
|
|
1076
|
-
// If the iterable is also referenced as a {{ }} expression elsewhere
|
|
1077
|
-
// (already in paramMap), keep its existing entry but ensure it's marked
|
|
1078
|
-
// as array type — the {% for %} usage is a stronger type signal.
|
|
1079
|
-
for (const [iterableName, { isRequired }] of loopIterables) {
|
|
1080
|
-
const existing = paramMap.get(iterableName);
|
|
1081
|
-
if (existing) {
|
|
1082
|
-
existing.type = 'array';
|
|
1083
|
-
// If the iterable also appears inside an {% if %} guard, keep
|
|
1084
|
-
// it optional; if it's at top level somewhere, mark required.
|
|
1085
|
-
if (!conditionalVars.onlyInConditional.has(iterableName)) {
|
|
1086
|
-
existing.isRequired = existing.isRequired && isRequired;
|
|
1087
|
-
}
|
|
1088
|
-
}
|
|
1089
|
-
else {
|
|
1090
|
-
paramMap.set(iterableName, {
|
|
1091
|
-
name: iterableName,
|
|
1092
|
-
type: 'array',
|
|
1093
|
-
isRequired,
|
|
1094
|
-
defaultValue: null,
|
|
1095
|
-
filters: [],
|
|
1096
|
-
usageLocations: [],
|
|
1097
|
-
});
|
|
1098
|
-
}
|
|
1099
|
-
}
|
|
1100
|
-
// Enrich parameters with default values extracted from {% else %} blocks.
|
|
1101
|
-
// Pattern: {% if Var %} ... {{ Var | sqlFilter }} ... {% else %} ... = 'literal' ... {% endif %}
|
|
1102
|
-
// The literal in the else branch is the semantic default for the parameter.
|
|
1103
|
-
SQLParser.enrichDefaultsFromElseBranches(sql, paramMap);
|
|
1104
|
-
return Array.from(paramMap.values());
|
|
691
|
+
return LegacyParameterInfo(sql);
|
|
1105
692
|
}
|
|
1106
693
|
// ─── AST Walker ──────────────────────────────────────
|
|
1107
694
|
/**
|
|
@@ -1117,6 +704,7 @@ export class SQLParser {
|
|
|
1117
704
|
*
|
|
1118
705
|
* @param result The MJAstifyResult from Astify()
|
|
1119
706
|
* @returns Walk result with annotations, or empty result if AST parsing failed
|
|
707
|
+
* @deprecated Kept unchanged, node-sql-parser AST included, for callers that walk that tree; new code reads SQL with `SqlDocument.Parse(sql, dialect)`. Template positions come from `QueryTemplate.Parse(sql, dialect)`.
|
|
1120
708
|
*/
|
|
1121
709
|
static WalkAST(result) {
|
|
1122
710
|
const emptyResult = {
|
|
@@ -1343,162 +931,6 @@ export class SQLParser {
|
|
|
1343
931
|
return { annotations: deduped, byClause, byPlaceholder, templateExprs, compositionRefs };
|
|
1344
932
|
}
|
|
1345
933
|
// ═══════════════════════════════════════════════════
|
|
1346
|
-
// Private: SQL Parsing
|
|
1347
|
-
// ═══════════════════════════════════════════════════
|
|
1348
|
-
/**
|
|
1349
|
-
* Parse SQL safely, returning null on failure.
|
|
1350
|
-
*
|
|
1351
|
-
* Includes a workaround for node-sql-parser's inability to handle multi-directive
|
|
1352
|
-
* FOR XML clauses (e.g., `FOR XML PATH('M'), ROOT('R')`). The parser handles
|
|
1353
|
-
* `FOR XML PATH('M')` fine but chokes on the comma-separated directives.
|
|
1354
|
-
* We strip the extra directives before parsing and restore them on the AST's `for` property.
|
|
1355
|
-
*/
|
|
1356
|
-
/** Resolves overloaded Parse() args: (string, dialect?) or (options) */
|
|
1357
|
-
static resolveParseArgs(options, dialect) {
|
|
1358
|
-
if (typeof options === 'string') {
|
|
1359
|
-
return { sql: options, parserDialect: dialect?.ParserDialect || 'TransactSQL' };
|
|
1360
|
-
}
|
|
1361
|
-
return { sql: options.sql, parserDialect: options.dialect?.ParserDialect || 'TransactSQL' };
|
|
1362
|
-
}
|
|
1363
|
-
static parseSQL(sql, dialect) {
|
|
1364
|
-
try {
|
|
1365
|
-
return SQLParser.astifyChecked(sql, dialect);
|
|
1366
|
-
}
|
|
1367
|
-
catch {
|
|
1368
|
-
// If direct parse fails, try with FOR XML workaround
|
|
1369
|
-
const forXmlResult = SQLParser.stripForXmlDirectives(sql);
|
|
1370
|
-
if (forXmlResult) {
|
|
1371
|
-
try {
|
|
1372
|
-
const ast = SQLParser.astifyChecked(forXmlResult.cleanedSQL, dialect);
|
|
1373
|
-
// Restore the original FOR XML clause on the AST
|
|
1374
|
-
SQLParser.restoreForXmlOnAST(ast, forXmlResult.originalForXml);
|
|
1375
|
-
return ast;
|
|
1376
|
-
}
|
|
1377
|
-
catch {
|
|
1378
|
-
return null;
|
|
1379
|
-
}
|
|
1380
|
-
}
|
|
1381
|
-
return null;
|
|
1382
|
-
}
|
|
1383
|
-
}
|
|
1384
|
-
/**
|
|
1385
|
-
* Parses with node-sql-parser and throws when the result is not a real reading of the SQL.
|
|
1386
|
-
*
|
|
1387
|
-
* The T-SQL grammar accepts some statements it cannot parse — notably a CTE with a
|
|
1388
|
-
* bracket-quoted name, `WITH [x] AS (…) SELECT …` — as a run of bare `name = value`
|
|
1389
|
-
* assignments (`WITH = [x]`, `AS = (…)`, `SELECT = …`). No real statement has that shape, so
|
|
1390
|
-
* such a result is treated as a parse failure and callers take their fallback paths instead
|
|
1391
|
-
* of reading a meaningless tree.
|
|
1392
|
-
*/
|
|
1393
|
-
static astifyChecked(sql, dialect) {
|
|
1394
|
-
try {
|
|
1395
|
-
const ast = new Parser().astify(sql, { database: dialect });
|
|
1396
|
-
if (SQLParser.isMisreadAsAssignments(ast)) {
|
|
1397
|
-
throw new Error('SQLParser: the statement was read as variable assignments, not as SQL');
|
|
1398
|
-
}
|
|
1399
|
-
return ast;
|
|
1400
|
-
}
|
|
1401
|
-
catch (err) {
|
|
1402
|
-
const niladic = SQLParser.parenthesizeNiladicUserFunctions(sql, dialect);
|
|
1403
|
-
if (niladic.rewrittenNames.size === 0)
|
|
1404
|
-
throw err;
|
|
1405
|
-
const ast = new Parser().astify(niladic.rewritten, { database: dialect });
|
|
1406
|
-
if (SQLParser.isMisreadAsAssignments(ast)) {
|
|
1407
|
-
throw new Error('SQLParser: the statement was read as variable assignments, not as SQL');
|
|
1408
|
-
}
|
|
1409
|
-
SQLParser.stripNiladicUserFunctionArgs(ast, niladic.rewrittenNames);
|
|
1410
|
-
return ast;
|
|
1411
|
-
}
|
|
1412
|
-
}
|
|
1413
|
-
/**
|
|
1414
|
-
* Rewrites bare `CURRENT_USER`, `SESSION_USER`, and `SYSTEM_USER` keywords (outside strings,
|
|
1415
|
-
* comments, and quoted identifiers) to `CURRENT_USER()` / `SESSION_USER()` / `SYSTEM_USER()`
|
|
1416
|
-
* so node-sql-parser's T-SQL and PostgreSQL grammars accept them. Qualified column references
|
|
1417
|
-
* (`t.current_user`), aliases (`AS current_user`), and calls that already carry `()` are left
|
|
1418
|
-
* untouched.
|
|
1419
|
-
*/
|
|
1420
|
-
static parenthesizeNiladicUserFunctions(sql, parserDialect) {
|
|
1421
|
-
const rewrittenNames = new Set();
|
|
1422
|
-
const lexDialect = /postgres/i.test(parserDialect) ? POSTGRES_LEXING : SQL_SERVER_LEXING;
|
|
1423
|
-
const tokens = SignificantTokens(LexSQL(sql, lexDialect));
|
|
1424
|
-
let out = '';
|
|
1425
|
-
let cursor = 0;
|
|
1426
|
-
for (let i = 0; i < tokens.length; i++) {
|
|
1427
|
-
const t = tokens[i];
|
|
1428
|
-
const upper = t.Kind === 'word' ? t.Text.toUpperCase() : '';
|
|
1429
|
-
if (upper &&
|
|
1430
|
-
NILADIC_USER_FUNCTIONS.has(upper) &&
|
|
1431
|
-
tokens[i - 1]?.Kind !== 'dot' &&
|
|
1432
|
-
tokens[i + 1]?.Kind !== 'dot' &&
|
|
1433
|
-
tokens[i + 1]?.Kind !== 'open' &&
|
|
1434
|
-
!IsKeyword(tokens[i - 1], 'AS')) {
|
|
1435
|
-
out += sql.substring(cursor, t.End) + '()';
|
|
1436
|
-
cursor = t.End;
|
|
1437
|
-
rewrittenNames.add(upper);
|
|
1438
|
-
}
|
|
1439
|
-
}
|
|
1440
|
-
if (rewrittenNames.size === 0)
|
|
1441
|
-
return { rewritten: sql, rewrittenNames };
|
|
1442
|
-
return { rewritten: out + sql.substring(cursor), rewrittenNames };
|
|
1443
|
-
}
|
|
1444
|
-
/**
|
|
1445
|
-
* Removes empty `args` from `CURRENT_USER` / `SESSION_USER` / `SYSTEM_USER` function AST nodes
|
|
1446
|
-
* produced by {@link parenthesizeNiladicUserFunctions}, matching the AST shape node-sql-parser
|
|
1447
|
-
* produces for `CURRENT_TIMESTAMP` so `SqlifyAST` emits the standard niladic form without `()`.
|
|
1448
|
-
*/
|
|
1449
|
-
static stripNiladicUserFunctionArgs(node, rewrittenNames) {
|
|
1450
|
-
if (!node || typeof node !== 'object')
|
|
1451
|
-
return;
|
|
1452
|
-
if (Array.isArray(node)) {
|
|
1453
|
-
for (const item of node)
|
|
1454
|
-
SQLParser.stripNiladicUserFunctionArgs(item, rewrittenNames);
|
|
1455
|
-
return;
|
|
1456
|
-
}
|
|
1457
|
-
const obj = node;
|
|
1458
|
-
if (obj.type === 'function') {
|
|
1459
|
-
const fnName = SQLParser.extractFunctionNodeName(obj);
|
|
1460
|
-
const args = obj.args;
|
|
1461
|
-
if (fnName &&
|
|
1462
|
-
rewrittenNames.has(fnName.toUpperCase()) &&
|
|
1463
|
-
args &&
|
|
1464
|
-
Array.isArray(args.value) &&
|
|
1465
|
-
args.value.length === 0) {
|
|
1466
|
-
delete obj.args;
|
|
1467
|
-
}
|
|
1468
|
-
}
|
|
1469
|
-
for (const value of Object.values(obj)) {
|
|
1470
|
-
SQLParser.stripNiladicUserFunctionArgs(value, rewrittenNames);
|
|
1471
|
-
}
|
|
1472
|
-
}
|
|
1473
|
-
/** Extracts the simple function name from a node-sql-parser `function` AST node. */
|
|
1474
|
-
static extractFunctionNodeName(fnNode) {
|
|
1475
|
-
const rawName = fnNode.name;
|
|
1476
|
-
if (typeof rawName === 'string')
|
|
1477
|
-
return rawName;
|
|
1478
|
-
if (rawName && typeof rawName === 'object') {
|
|
1479
|
-
const inner = rawName.name;
|
|
1480
|
-
if (typeof inner === 'string')
|
|
1481
|
-
return inner;
|
|
1482
|
-
if (Array.isArray(inner) && inner.length === 1) {
|
|
1483
|
-
const first = inner[0];
|
|
1484
|
-
if (typeof first === 'string')
|
|
1485
|
-
return first;
|
|
1486
|
-
if (first && typeof first === 'object' && typeof first.value === 'string') {
|
|
1487
|
-
return first.value;
|
|
1488
|
-
}
|
|
1489
|
-
}
|
|
1490
|
-
}
|
|
1491
|
-
return null;
|
|
1492
|
-
}
|
|
1493
|
-
/** Whether any top-level node is a bare assignment wrapper rather than a statement. */
|
|
1494
|
-
static isMisreadAsAssignments(ast) {
|
|
1495
|
-
const statements = Array.isArray(ast) ? ast : [ast];
|
|
1496
|
-
return statements.some(statement => {
|
|
1497
|
-
const node = statement;
|
|
1498
|
-
return !node || (typeof node.type !== 'string' && node.stmt?.type === 'assign');
|
|
1499
|
-
});
|
|
1500
|
-
}
|
|
1501
|
-
// ═══════════════════════════════════════════════════
|
|
1502
934
|
// Private: Parse Preprocessing (fallback + restoration)
|
|
1503
935
|
// ═══════════════════════════════════════════════════
|
|
1504
936
|
/**
|
|
@@ -1530,7 +962,7 @@ export class SQLParser {
|
|
|
1530
962
|
// No transform applied → re-parsing the same SQL would just fail again.
|
|
1531
963
|
if (work === sql)
|
|
1532
964
|
return noResult;
|
|
1533
|
-
const ast =
|
|
965
|
+
const ast = NodeSqlParse(work, dialect.ParserDialect);
|
|
1534
966
|
if (!ast)
|
|
1535
967
|
return noResult;
|
|
1536
968
|
return { ast, aliasMap, trailingOption };
|
|
@@ -1724,536 +1156,5 @@ export class SQLParser {
|
|
|
1724
1156
|
}
|
|
1725
1157
|
return n;
|
|
1726
1158
|
}
|
|
1727
|
-
/**
|
|
1728
|
-
* Detects FOR XML clauses that node-sql-parser can't handle and simplifies them.
|
|
1729
|
-
*
|
|
1730
|
-
* node-sql-parser handles: FOR XML PATH, FOR XML PATH('arg'), FOR XML RAW, FOR XML AUTO
|
|
1731
|
-
* node-sql-parser fails on: FOR XML RAW('arg'), and any comma-separated directives
|
|
1732
|
-
*
|
|
1733
|
-
* Simplifies to a form the parser accepts, preserving the original for restoration.
|
|
1734
|
-
* Returns null if no problematic FOR XML pattern is found.
|
|
1735
|
-
*/
|
|
1736
|
-
static stripForXmlDirectives(sql) {
|
|
1737
|
-
// Read from tokens, not a regex: a trailing-clause regex backtracks polynomially on long
|
|
1738
|
-
// whitespace runs, and tokens also keep a FOR XML inside a subquery or string out of it.
|
|
1739
|
-
const tokens = SignificantTokens(LexSQL(sql, SQL_SERVER_LEXING));
|
|
1740
|
-
const forAt = tokens.findIndex((t, i) => t.Depth === 0 && IsKeyword(t, 'FOR') && IsKeyword(tokens[i + 1], 'XML') &&
|
|
1741
|
-
FOR_XML_DIRECTIVES.some(d => IsKeyword(tokens[i + 2], d)));
|
|
1742
|
-
if (forAt === -1)
|
|
1743
|
-
return null;
|
|
1744
|
-
const directive = tokens[forAt + 2].Text.toUpperCase(); // PATH, RAW, etc.
|
|
1745
|
-
let next = forAt + 3;
|
|
1746
|
-
let quotedArg = null;
|
|
1747
|
-
if (tokens[next]?.Kind === 'open' && tokens[next + 1]?.Kind === 'string' && tokens[next + 2]?.Kind === 'close') {
|
|
1748
|
-
quotedArg = sql.substring(tokens[next].Start, tokens[next + 2].End);
|
|
1749
|
-
next += 3;
|
|
1750
|
-
}
|
|
1751
|
-
const rest = tokens.slice(next);
|
|
1752
|
-
// The clause must run to the end of the statement: nothing may follow it except
|
|
1753
|
-
// comma-separated directives, and no statement may follow a semicolon.
|
|
1754
|
-
if (rest.some(t => t.Kind === 'semicolon'))
|
|
1755
|
-
return null;
|
|
1756
|
-
const hasExtraDirectives = rest.length > 0 && rest[0].Kind === 'comma';
|
|
1757
|
-
if (rest.length > 0 && !hasExtraDirectives)
|
|
1758
|
-
return null;
|
|
1759
|
-
// Only needs workaround if there are extra comma-separated directives
|
|
1760
|
-
// OR if it's RAW/EXPLICIT with a quoted arg (parser can't handle those)
|
|
1761
|
-
const needsWorkaround = hasExtraDirectives ||
|
|
1762
|
-
(quotedArg !== null && (directive === 'RAW' || directive === 'EXPLICIT'));
|
|
1763
|
-
if (!needsWorkaround)
|
|
1764
|
-
return null;
|
|
1765
|
-
// Simplify to a form the parser accepts:
|
|
1766
|
-
// PATH('arg') → PATH('arg') (parser handles this)
|
|
1767
|
-
// RAW('arg') → RAW (parser can't handle quoted arg on RAW)
|
|
1768
|
-
// Any + comma extras → strip extras
|
|
1769
|
-
const simplifiedDirective = directive === 'PATH' && quotedArg !== null
|
|
1770
|
-
? `FOR XML PATH${quotedArg}`
|
|
1771
|
-
: `FOR XML ${directive}`;
|
|
1772
|
-
const clauseStart = tokens[forAt].Start;
|
|
1773
|
-
return { cleanedSQL: sql.substring(0, clauseStart) + simplifiedDirective, originalForXml: sql.substring(clauseStart) };
|
|
1774
|
-
}
|
|
1775
|
-
/**
|
|
1776
|
-
* Restores the original FOR XML clause text on the AST's `for` property.
|
|
1777
|
-
* This ensures that when the AST is inspected (e.g., for isOrderByLegalInCTE checks),
|
|
1778
|
-
* the FOR XML presence is correctly detected.
|
|
1779
|
-
*/
|
|
1780
|
-
static restoreForXmlOnAST(ast, originalForXml) {
|
|
1781
|
-
const stmt = (Array.isArray(ast) ? ast[0] : ast);
|
|
1782
|
-
if (!stmt)
|
|
1783
|
-
return;
|
|
1784
|
-
// Walk the _next chain (UNION) to find the statement with the FOR clause
|
|
1785
|
-
let current = stmt;
|
|
1786
|
-
while (current) {
|
|
1787
|
-
if (current.for && typeof current.for === 'object') {
|
|
1788
|
-
// Attach the original text so downstream code can reconstruct it
|
|
1789
|
-
current.for.__originalForXml = originalForXml;
|
|
1790
|
-
return;
|
|
1791
|
-
}
|
|
1792
|
-
current = current._next;
|
|
1793
|
-
}
|
|
1794
|
-
}
|
|
1795
|
-
/** Get clean SQL (MJ tokens replaced with placeholders) for AST parsing */
|
|
1796
|
-
static getCleanSQL(sql) {
|
|
1797
|
-
const analysis = MJLexer.Parse(sql);
|
|
1798
|
-
if (!analysis.hasMJExtensions)
|
|
1799
|
-
return sql;
|
|
1800
|
-
return MJPlaceholderSubstitution.Substitute(sql).cleanSQL;
|
|
1801
|
-
}
|
|
1802
|
-
// ═══════════════════════════════════════════════════
|
|
1803
|
-
// Private: Table Extraction
|
|
1804
|
-
// ═══════════════════════════════════════════════════
|
|
1805
|
-
static extractTablesViaAST(sql, dialect) {
|
|
1806
|
-
try {
|
|
1807
|
-
const ast = SQLParser.astifyChecked(sql, dialect);
|
|
1808
|
-
const tableAliasMap = new Map();
|
|
1809
|
-
const columnRefs = new Set();
|
|
1810
|
-
const statements = Array.isArray(ast) ? ast : [ast];
|
|
1811
|
-
for (const statement of statements) {
|
|
1812
|
-
SQLParser.walkASTForExtraction(statement, tableAliasMap, columnRefs);
|
|
1813
|
-
}
|
|
1814
|
-
return SQLParser.deduplicateTables(tableAliasMap);
|
|
1815
|
-
}
|
|
1816
|
-
catch {
|
|
1817
|
-
return null;
|
|
1818
|
-
}
|
|
1819
|
-
}
|
|
1820
|
-
static extractTablesViaRegex(sql) {
|
|
1821
|
-
const tableAliasMap = new Map();
|
|
1822
|
-
const tablePattern = /(?:FROM|JOIN|INTO)\s+(?:\[?(\w+)\]?\.)?\[?(\w+)\]?(?:\s+(?:AS\s+)?(\w+))?/gi;
|
|
1823
|
-
const matches = [...sql.matchAll(tablePattern)];
|
|
1824
|
-
for (const match of matches) {
|
|
1825
|
-
const schemaName = match[1] || 'dbo';
|
|
1826
|
-
const tableName = match[2];
|
|
1827
|
-
const alias = match[3] || tableName;
|
|
1828
|
-
if (!tableAliasMap.has(alias)) {
|
|
1829
|
-
tableAliasMap.set(alias, { schemaName, tableName });
|
|
1830
|
-
}
|
|
1831
|
-
}
|
|
1832
|
-
return SQLParser.deduplicateTables(tableAliasMap);
|
|
1833
|
-
}
|
|
1834
|
-
static deduplicateTables(tableAliasMap) {
|
|
1835
|
-
const seen = new Set();
|
|
1836
|
-
const tables = [];
|
|
1837
|
-
for (const [alias, info] of tableAliasMap) {
|
|
1838
|
-
const key = `${info.schemaName.toLowerCase()}.${info.tableName.toLowerCase()}`;
|
|
1839
|
-
if (!seen.has(key)) {
|
|
1840
|
-
seen.add(key);
|
|
1841
|
-
tables.push({ TableName: info.tableName, SchemaName: info.schemaName, Alias: alias });
|
|
1842
|
-
}
|
|
1843
|
-
}
|
|
1844
|
-
return tables;
|
|
1845
|
-
}
|
|
1846
|
-
static buildColumnRefs(columnRefs) {
|
|
1847
|
-
const columns = [];
|
|
1848
|
-
for (const ref of columnRefs) {
|
|
1849
|
-
const dotIndex = ref.lastIndexOf('.');
|
|
1850
|
-
if (dotIndex >= 0) {
|
|
1851
|
-
columns.push({ ColumnName: ref.substring(dotIndex + 1), TableQualifier: ref.substring(0, dotIndex) });
|
|
1852
|
-
}
|
|
1853
|
-
else {
|
|
1854
|
-
columns.push({ ColumnName: ref, TableQualifier: null });
|
|
1855
|
-
}
|
|
1856
|
-
}
|
|
1857
|
-
return columns;
|
|
1858
|
-
}
|
|
1859
|
-
// ═══════════════════════════════════════════════════
|
|
1860
|
-
// Private: CTE Extraction
|
|
1861
|
-
// ═══════════════════════════════════════════════════
|
|
1862
|
-
static extractCTEsViaAST(sql, dialect) {
|
|
1863
|
-
try {
|
|
1864
|
-
const parser = new Parser();
|
|
1865
|
-
const ast = SQLParser.astifyChecked(sql, dialect);
|
|
1866
|
-
const singleAst = (Array.isArray(ast) ? ast[0] : ast);
|
|
1867
|
-
if (!singleAst.with || !Array.isArray(singleAst.with) || singleAst.with.length === 0) {
|
|
1868
|
-
return null;
|
|
1869
|
-
}
|
|
1870
|
-
const cteDefinitions = [];
|
|
1871
|
-
for (const cte of singleAst.with) {
|
|
1872
|
-
const cteRecord = cte;
|
|
1873
|
-
const cteName = cteRecord.name.value;
|
|
1874
|
-
const bodySQL = SQLParser.fixMaxTypeSerialization(parser.sqlify(cteRecord.stmt.ast, { database: dialect }));
|
|
1875
|
-
cteDefinitions.push(`${cteName} AS (\n${bodySQL}\n)`);
|
|
1876
|
-
}
|
|
1877
|
-
const mainAst = { ...singleAst, with: null };
|
|
1878
|
-
const mainStatement = SQLParser.fixMaxTypeSerialization(parser.sqlify(mainAst, { database: dialect }));
|
|
1879
|
-
return { CTEDefinitions: cteDefinitions, MainStatement: mainStatement, UsedASTParsing: true };
|
|
1880
|
-
}
|
|
1881
|
-
catch {
|
|
1882
|
-
return null;
|
|
1883
|
-
}
|
|
1884
|
-
}
|
|
1885
|
-
static extractCTEsViaRegex(sql) {
|
|
1886
|
-
const withStripped = sql.trimStart().replace(/^WITH\s+/i, '');
|
|
1887
|
-
const cteDefinitions = [];
|
|
1888
|
-
let pos = 0;
|
|
1889
|
-
const len = withStripped.length;
|
|
1890
|
-
while (pos < len) {
|
|
1891
|
-
pos = SQLParser.skipWhitespace(withStripped, pos);
|
|
1892
|
-
if (pos >= len)
|
|
1893
|
-
break;
|
|
1894
|
-
const remaining = withStripped.substring(pos);
|
|
1895
|
-
const cteHeaderMatch = remaining.match(/^(\[[^\]]+\]|"[^"]+"|[A-Za-z_]\w*)\s+AS\s*\(/i);
|
|
1896
|
-
if (!cteHeaderMatch)
|
|
1897
|
-
break;
|
|
1898
|
-
const cteName = cteHeaderMatch[1];
|
|
1899
|
-
pos += cteHeaderMatch[0].length;
|
|
1900
|
-
const bodyStart = pos;
|
|
1901
|
-
pos = SQLParser.findMatchingCloseParen(withStripped, pos);
|
|
1902
|
-
const cteBody = withStripped.substring(bodyStart, pos);
|
|
1903
|
-
cteDefinitions.push(`${cteName} AS (\n${cteBody}\n)`);
|
|
1904
|
-
pos++;
|
|
1905
|
-
pos = SQLParser.skipWhitespace(withStripped, pos);
|
|
1906
|
-
if (pos < len && withStripped[pos] === ',')
|
|
1907
|
-
pos++;
|
|
1908
|
-
}
|
|
1909
|
-
const mainStatement = withStripped.substring(pos).trim();
|
|
1910
|
-
return { CTEDefinitions: cteDefinitions, MainStatement: mainStatement, UsedASTParsing: false };
|
|
1911
|
-
}
|
|
1912
|
-
static skipWhitespace(sql, pos) {
|
|
1913
|
-
while (pos < sql.length && /\s/.test(sql[pos]))
|
|
1914
|
-
pos++;
|
|
1915
|
-
return pos;
|
|
1916
|
-
}
|
|
1917
|
-
static findMatchingCloseParen(sql, pos) {
|
|
1918
|
-
let depth = 1;
|
|
1919
|
-
const len = sql.length;
|
|
1920
|
-
while (pos < len && depth > 0) {
|
|
1921
|
-
const ch = sql[pos];
|
|
1922
|
-
if (ch === "'") {
|
|
1923
|
-
pos++;
|
|
1924
|
-
while (pos < len) {
|
|
1925
|
-
if (sql[pos] === "'") {
|
|
1926
|
-
if (pos + 1 < len && sql[pos + 1] === "'") {
|
|
1927
|
-
pos += 2;
|
|
1928
|
-
continue;
|
|
1929
|
-
}
|
|
1930
|
-
break;
|
|
1931
|
-
}
|
|
1932
|
-
pos++;
|
|
1933
|
-
}
|
|
1934
|
-
}
|
|
1935
|
-
else if (ch === '-' && pos + 1 < len && sql[pos + 1] === '-') {
|
|
1936
|
-
pos += 2;
|
|
1937
|
-
while (pos < len && sql[pos] !== '\n')
|
|
1938
|
-
pos++;
|
|
1939
|
-
}
|
|
1940
|
-
else if (ch === '/' && pos + 1 < len && sql[pos + 1] === '*') {
|
|
1941
|
-
pos += 2;
|
|
1942
|
-
while (pos < len && !(sql[pos] === '*' && pos + 1 < len && sql[pos + 1] === '/'))
|
|
1943
|
-
pos++;
|
|
1944
|
-
if (pos < len)
|
|
1945
|
-
pos++;
|
|
1946
|
-
}
|
|
1947
|
-
else if (ch === '(') {
|
|
1948
|
-
depth++;
|
|
1949
|
-
}
|
|
1950
|
-
else if (ch === ')') {
|
|
1951
|
-
depth--;
|
|
1952
|
-
if (depth === 0)
|
|
1953
|
-
return pos;
|
|
1954
|
-
}
|
|
1955
|
-
pos++;
|
|
1956
|
-
}
|
|
1957
|
-
return pos;
|
|
1958
|
-
}
|
|
1959
|
-
// ═══════════════════════════════════════════════════
|
|
1960
|
-
// Private: AST Walking (table/column extraction)
|
|
1961
|
-
// ═══════════════════════════════════════════════════
|
|
1962
|
-
static walkASTForExtraction(node, tableAliasMap, columnRefs) {
|
|
1963
|
-
if (!node || typeof node !== 'object')
|
|
1964
|
-
return;
|
|
1965
|
-
if (node.with) {
|
|
1966
|
-
const ctes = Array.isArray(node.with) ? node.with : [node.with];
|
|
1967
|
-
for (const cte of ctes) {
|
|
1968
|
-
const cteRecord = cte;
|
|
1969
|
-
if (cteRecord.stmt) {
|
|
1970
|
-
const stmtRecord = cteRecord.stmt;
|
|
1971
|
-
const cteAst = (stmtRecord.ast || stmtRecord);
|
|
1972
|
-
SQLParser.walkASTForExtraction(cteAst, tableAliasMap, columnRefs);
|
|
1973
|
-
}
|
|
1974
|
-
}
|
|
1975
|
-
}
|
|
1976
|
-
if (node.from) {
|
|
1977
|
-
const fromItems = Array.isArray(node.from) ? node.from : [node.from];
|
|
1978
|
-
for (const fromItem of fromItems) {
|
|
1979
|
-
SQLParser.walkFromItem(fromItem, tableAliasMap, columnRefs);
|
|
1980
|
-
}
|
|
1981
|
-
}
|
|
1982
|
-
if (node.columns) {
|
|
1983
|
-
const cols = Array.isArray(node.columns) ? node.columns : [node.columns];
|
|
1984
|
-
for (const col of cols) {
|
|
1985
|
-
if (col === '*')
|
|
1986
|
-
continue;
|
|
1987
|
-
const colRecord = col;
|
|
1988
|
-
if (colRecord.expr) {
|
|
1989
|
-
SQLParser.walkExpression(colRecord.expr, columnRefs, tableAliasMap);
|
|
1990
|
-
}
|
|
1991
|
-
}
|
|
1992
|
-
}
|
|
1993
|
-
if (node.where) {
|
|
1994
|
-
SQLParser.walkExpression(node.where, columnRefs, tableAliasMap);
|
|
1995
|
-
}
|
|
1996
|
-
if (node.groupby) {
|
|
1997
|
-
const groupbyRecord = node.groupby;
|
|
1998
|
-
const groupItems = groupbyRecord.columns || node.groupby;
|
|
1999
|
-
const items = Array.isArray(groupItems) ? groupItems : [groupItems];
|
|
2000
|
-
for (const group of items) {
|
|
2001
|
-
SQLParser.walkExpression(group, columnRefs, tableAliasMap);
|
|
2002
|
-
}
|
|
2003
|
-
}
|
|
2004
|
-
if (node.orderby) {
|
|
2005
|
-
const orders = Array.isArray(node.orderby) ? node.orderby : [node.orderby];
|
|
2006
|
-
for (const order of orders) {
|
|
2007
|
-
const orderRecord = order;
|
|
2008
|
-
SQLParser.walkExpression((orderRecord.expr || orderRecord), columnRefs, tableAliasMap);
|
|
2009
|
-
}
|
|
2010
|
-
}
|
|
2011
|
-
if (node._next) {
|
|
2012
|
-
SQLParser.walkASTForExtraction(node._next, tableAliasMap, columnRefs);
|
|
2013
|
-
}
|
|
2014
|
-
}
|
|
2015
|
-
static walkFromItem(fromItem, tableAliasMap, columnRefs) {
|
|
2016
|
-
if (!fromItem)
|
|
2017
|
-
return;
|
|
2018
|
-
const tableName = SQLParser.unwrapIdentifier(fromItem.table);
|
|
2019
|
-
if (tableName) {
|
|
2020
|
-
const alias = SQLParser.unwrapIdentifier(fromItem.as) ?? tableName;
|
|
2021
|
-
tableAliasMap.set(alias, {
|
|
2022
|
-
schemaName: SQLParser.unwrapIdentifier(fromItem.db) || 'dbo',
|
|
2023
|
-
tableName,
|
|
2024
|
-
});
|
|
2025
|
-
}
|
|
2026
|
-
if (fromItem.expr) {
|
|
2027
|
-
const exprRecord = fromItem.expr;
|
|
2028
|
-
const subqueryAst = (exprRecord.ast || exprRecord);
|
|
2029
|
-
SQLParser.walkASTForExtraction(subqueryAst, tableAliasMap, columnRefs);
|
|
2030
|
-
}
|
|
2031
|
-
if (fromItem.on) {
|
|
2032
|
-
SQLParser.walkExpression(fromItem.on, columnRefs, tableAliasMap);
|
|
2033
|
-
}
|
|
2034
|
-
if (fromItem.using) {
|
|
2035
|
-
const usings = Array.isArray(fromItem.using) ? fromItem.using : [fromItem.using];
|
|
2036
|
-
for (const col of usings) {
|
|
2037
|
-
const name = col && typeof col === 'object' && 'column' in col
|
|
2038
|
-
? SQLParser.unwrapIdentifier(col.column)
|
|
2039
|
-
: SQLParser.unwrapIdentifier(col);
|
|
2040
|
-
if (name)
|
|
2041
|
-
columnRefs.add(name);
|
|
2042
|
-
}
|
|
2043
|
-
}
|
|
2044
|
-
}
|
|
2045
|
-
static walkExpression(expr, columnRefs, tableAliasMap) {
|
|
2046
|
-
if (!expr || typeof expr !== 'object')
|
|
2047
|
-
return;
|
|
2048
|
-
if (expr.type === 'column_ref') {
|
|
2049
|
-
// The PostgreSQL grammar returns identifier nodes here, not strings.
|
|
2050
|
-
const column = SQLParser.unwrapIdentifier(expr.column);
|
|
2051
|
-
const table = SQLParser.unwrapIdentifier(expr.table);
|
|
2052
|
-
if (column)
|
|
2053
|
-
columnRefs.add(table ? `${table}.${column}` : column);
|
|
2054
|
-
}
|
|
2055
|
-
if (expr.ast && tableAliasMap) {
|
|
2056
|
-
SQLParser.walkASTForExtraction(expr.ast, tableAliasMap, columnRefs);
|
|
2057
|
-
}
|
|
2058
|
-
if (expr.left)
|
|
2059
|
-
SQLParser.walkExpression(expr.left, columnRefs, tableAliasMap);
|
|
2060
|
-
if (expr.right)
|
|
2061
|
-
SQLParser.walkExpression(expr.right, columnRefs, tableAliasMap);
|
|
2062
|
-
if (expr.args) {
|
|
2063
|
-
const argsRecord = expr.args;
|
|
2064
|
-
const args = argsRecord.value || expr.args;
|
|
2065
|
-
const argList = Array.isArray(args) ? args : [args];
|
|
2066
|
-
for (const arg of argList) {
|
|
2067
|
-
SQLParser.walkExpression(arg, columnRefs, tableAliasMap);
|
|
2068
|
-
}
|
|
2069
|
-
}
|
|
2070
|
-
if (expr.expr)
|
|
2071
|
-
SQLParser.walkExpression(expr.expr, columnRefs, tableAliasMap);
|
|
2072
|
-
// IN (SELECT …) is an expr_list on `value`, not `args`. Without this walk,
|
|
2073
|
-
// ExtractTableRefs misses the subquery FROM (EXISTS uses `args` and was found).
|
|
2074
|
-
if (expr.value != null) {
|
|
2075
|
-
const values = Array.isArray(expr.value) ? expr.value : [expr.value];
|
|
2076
|
-
for (const v of values) {
|
|
2077
|
-
if (v && typeof v === 'object') {
|
|
2078
|
-
SQLParser.walkExpression(v, columnRefs, tableAliasMap);
|
|
2079
|
-
}
|
|
2080
|
-
}
|
|
2081
|
-
}
|
|
2082
|
-
}
|
|
2083
|
-
// ═══════════════════════════════════════════════════
|
|
2084
|
-
// Private: Parameter Analysis
|
|
2085
|
-
// ═══════════════════════════════════════════════════
|
|
2086
|
-
static inferTypeFromFilters(filters) {
|
|
2087
|
-
const filterTypeMap = {
|
|
2088
|
-
'sqlString': 'string',
|
|
2089
|
-
'sqlNumber': 'number',
|
|
2090
|
-
'sqlDate': 'date',
|
|
2091
|
-
'sqlBoolean': 'boolean',
|
|
2092
|
-
'sqlIn': 'array',
|
|
2093
|
-
'sqlIdentifier': 'string',
|
|
2094
|
-
'sqlNoKeywordsExpression': 'string',
|
|
2095
|
-
};
|
|
2096
|
-
for (let i = filters.length - 1; i >= 0; i--) {
|
|
2097
|
-
const mapped = filterTypeMap[filters[i].name];
|
|
2098
|
-
if (mapped)
|
|
2099
|
-
return mapped;
|
|
2100
|
-
}
|
|
2101
|
-
return 'unknown';
|
|
2102
|
-
}
|
|
2103
|
-
static extractDefaultValue(filters) {
|
|
2104
|
-
for (const filter of filters) {
|
|
2105
|
-
if (filter.name === 'default' && filter.args.length > 0) {
|
|
2106
|
-
return filter.args[0];
|
|
2107
|
-
}
|
|
2108
|
-
}
|
|
2109
|
-
return null;
|
|
2110
|
-
}
|
|
2111
|
-
/**
|
|
2112
|
-
* Extracts the primary variable name from an {% if %} condition expression.
|
|
2113
|
-
* Handles patterns like:
|
|
2114
|
-
* "Status" → "Status"
|
|
2115
|
-
* "Status and Status.length > 0" → "Status"
|
|
2116
|
-
* "StartDate and StartDate.length" → "StartDate"
|
|
2117
|
-
*/
|
|
2118
|
-
static extractConditionVariable(condition) {
|
|
2119
|
-
const match = condition.match(/^\s*([A-Za-z_]\w*)/);
|
|
2120
|
-
return match ? match[1] : null;
|
|
2121
|
-
}
|
|
2122
|
-
/**
|
|
2123
|
-
* Extracts a SQL literal value from an {% else %} branch body.
|
|
2124
|
-
* Looks for patterns like:
|
|
2125
|
-
* `= 'Attended'` → "Attended"
|
|
2126
|
-
* `= 42` → 42
|
|
2127
|
-
* `= 3.14` → 3.14
|
|
2128
|
-
*
|
|
2129
|
-
* Only returns a value when exactly one literal is found, to avoid
|
|
2130
|
-
* ambiguity from complex else bodies with multiple conditions.
|
|
2131
|
-
*/
|
|
2132
|
-
static extractLiteralFromElseBody(body) {
|
|
2133
|
-
// Match string literals: = 'value' (SQL single-quoted strings)
|
|
2134
|
-
const stringMatches = [...body.matchAll(/=\s*'([^']+)'/g)];
|
|
2135
|
-
if (stringMatches.length === 1) {
|
|
2136
|
-
return stringMatches[0][1];
|
|
2137
|
-
}
|
|
2138
|
-
// Match numeric literals: = 42 or = 3.14 (but not parts of column names)
|
|
2139
|
-
const numericMatches = [...body.matchAll(/=\s*(-?\d+(?:\.\d+)?)\b/g)];
|
|
2140
|
-
if (numericMatches.length === 1 && stringMatches.length === 0) {
|
|
2141
|
-
const num = Number(numericMatches[0][1]);
|
|
2142
|
-
return isNaN(num) ? null : num;
|
|
2143
|
-
}
|
|
2144
|
-
return null;
|
|
2145
|
-
}
|
|
2146
|
-
/**
|
|
2147
|
-
* Enriches parameters that lack default values by inspecting {% else %} branches
|
|
2148
|
-
* of conditional blocks. When a block guards a parameter with {% if Var %} and
|
|
2149
|
-
* the else branch contains a single literal value (e.g., `= 'Attended'`), that
|
|
2150
|
-
* literal is assigned as the parameter's default.
|
|
2151
|
-
*
|
|
2152
|
-
* Only sets defaults on parameters that don't already have one (from a `| default()` filter).
|
|
2153
|
-
*/
|
|
2154
|
-
static enrichDefaultsFromElseBranches(sql, paramMap) {
|
|
2155
|
-
const blocks = SQLParser.ExtractConditionalBlocks(sql);
|
|
2156
|
-
for (const block of blocks) {
|
|
2157
|
-
// Need at least 2 branches (if + else) and last branch must be else (condition === null)
|
|
2158
|
-
if (block.branches.length < 2)
|
|
2159
|
-
continue;
|
|
2160
|
-
const elseBranch = block.branches[block.branches.length - 1];
|
|
2161
|
-
if (elseBranch.condition !== null)
|
|
2162
|
-
continue;
|
|
2163
|
-
// Extract the variable from the if-condition
|
|
2164
|
-
const ifCondition = block.branches[0].condition;
|
|
2165
|
-
if (!ifCondition)
|
|
2166
|
-
continue;
|
|
2167
|
-
const varName = SQLParser.extractConditionVariable(ifCondition);
|
|
2168
|
-
if (!varName)
|
|
2169
|
-
continue;
|
|
2170
|
-
// Only enrich parameters that exist and don't already have a default
|
|
2171
|
-
const param = paramMap.get(varName);
|
|
2172
|
-
if (!param || param.defaultValue !== null)
|
|
2173
|
-
continue;
|
|
2174
|
-
const literal = SQLParser.extractLiteralFromElseBody(elseBranch.body.raw);
|
|
2175
|
-
if (literal !== null) {
|
|
2176
|
-
param.defaultValue = literal;
|
|
2177
|
-
}
|
|
2178
|
-
}
|
|
2179
|
-
}
|
|
2180
|
-
static findConditionalVariables(tokens) {
|
|
2181
|
-
const insideConditional = new Set();
|
|
2182
|
-
const outsideConditional = new Set();
|
|
2183
|
-
let conditionalDepth = 0;
|
|
2184
|
-
for (const token of tokens) {
|
|
2185
|
-
switch (token.type) {
|
|
2186
|
-
case 'MJ_IF_OPEN':
|
|
2187
|
-
conditionalDepth++;
|
|
2188
|
-
SQLParser.addConditionVariables(token, insideConditional);
|
|
2189
|
-
break;
|
|
2190
|
-
case 'MJ_ELIF':
|
|
2191
|
-
SQLParser.addConditionVariables(token, insideConditional);
|
|
2192
|
-
break;
|
|
2193
|
-
case 'MJ_ENDIF':
|
|
2194
|
-
conditionalDepth = Math.max(0, conditionalDepth - 1);
|
|
2195
|
-
break;
|
|
2196
|
-
case 'MJ_TEMPLATE_EXPR': {
|
|
2197
|
-
const parsed = token.parsed;
|
|
2198
|
-
if (conditionalDepth > 0) {
|
|
2199
|
-
insideConditional.add(parsed.variable);
|
|
2200
|
-
}
|
|
2201
|
-
else {
|
|
2202
|
-
outsideConditional.add(parsed.variable);
|
|
2203
|
-
}
|
|
2204
|
-
break;
|
|
2205
|
-
}
|
|
2206
|
-
}
|
|
2207
|
-
}
|
|
2208
|
-
const onlyInConditional = new Set();
|
|
2209
|
-
for (const v of insideConditional) {
|
|
2210
|
-
if (!outsideConditional.has(v))
|
|
2211
|
-
onlyInConditional.add(v);
|
|
2212
|
-
}
|
|
2213
|
-
return { onlyInConditional, outsideConditional };
|
|
2214
|
-
}
|
|
2215
|
-
/** Jinja2 keywords that should never be treated as user-defined variables. */
|
|
2216
|
-
static { this.JINJA_KEYWORDS = new Set([
|
|
2217
|
-
'and', 'or', 'not', 'in', 'is', 'true', 'false', 'none', 'null', 'undefined',
|
|
2218
|
-
'if', 'elif', 'else', 'endif', 'for', 'endfor',
|
|
2219
|
-
]); }
|
|
2220
|
-
static addConditionVariables(token, varSet) {
|
|
2221
|
-
const parsed = token.parsed;
|
|
2222
|
-
if (parsed.expression) {
|
|
2223
|
-
// Strip quoted string literals first so 'Year', "active", etc. don't
|
|
2224
|
-
// get mistaken for variable identifiers.
|
|
2225
|
-
const withoutStrings = parsed.expression.replace(/'[^']*'|"[^"]*"/g, '');
|
|
2226
|
-
const identifiers = withoutStrings.match(/\b[A-Za-z_]\w*\b/g) || [];
|
|
2227
|
-
for (const id of identifiers) {
|
|
2228
|
-
if (!SQLParser.JINJA_KEYWORDS.has(id.toLowerCase())) {
|
|
2229
|
-
varSet.add(id);
|
|
2230
|
-
}
|
|
2231
|
-
}
|
|
2232
|
-
}
|
|
2233
|
-
}
|
|
2234
|
-
// ═══════════════════════════════════════════════════
|
|
2235
|
-
// Private: Conditional Block Helpers
|
|
2236
|
-
// ═══════════════════════════════════════════════════
|
|
2237
|
-
static addNodeToFragment(token, branch) {
|
|
2238
|
-
if (token.type === 'MJ_TEMPLATE_EXPR') {
|
|
2239
|
-
const parsed = token.parsed;
|
|
2240
|
-
branch.body.nodes.push({
|
|
2241
|
-
type: 'mj_template_expr',
|
|
2242
|
-
variable: parsed.variable,
|
|
2243
|
-
filters: parsed.filters,
|
|
2244
|
-
raw: token.raw,
|
|
2245
|
-
});
|
|
2246
|
-
}
|
|
2247
|
-
else if (token.type === 'MJ_COMPOSITION_REF') {
|
|
2248
|
-
const parsed = token.parsed;
|
|
2249
|
-
branch.body.nodes.push({
|
|
2250
|
-
type: 'mj_composition_ref',
|
|
2251
|
-
categoryPath: parsed.categoryPath,
|
|
2252
|
-
queryName: parsed.queryName,
|
|
2253
|
-
parameters: parsed.parameters,
|
|
2254
|
-
raw: token.raw,
|
|
2255
|
-
});
|
|
2256
|
-
}
|
|
2257
|
-
}
|
|
2258
1159
|
}
|
|
2259
1160
|
//# sourceMappingURL=sql-parser.js.map
|