@memberjunction/sql-parser 6.2.0-edge.5 → 6.2.0-edge.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/README.md
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
# @memberjunction/sql-parser
|
|
2
|
+
|
|
3
|
+
Reads the SQL that MemberJunction stores and runs: saved queries written in the MJ Query language (SQL plus
|
|
4
|
+
template tags), the SQL a provider builds around them, and the fragments callers send in. The package lexes SQL by a
|
|
5
|
+
dialect's own rules, parses MJ Query templates, parses SQL into a lossless structural tree with analyses, edits that
|
|
6
|
+
SQL by exact text spans, and screens untrusted fragments with a strict, fail-closed parser.
|
|
7
|
+
|
|
8
|
+
Every reader in this package takes a dialect from `@memberjunction/sql-dialect` (`SQLServerDialect`,
|
|
9
|
+
`PostgreSQLDialect`, or a query-only dialect), so the same code reads `[bracket]` names on SQL Server and `$$dollar$$`
|
|
10
|
+
strings on PostgreSQL correctly.
|
|
11
|
+
|
|
12
|
+
## Layers
|
|
13
|
+
|
|
14
|
+
| Layer | Main exports | What it does |
|
|
15
|
+
|---|---|---|
|
|
16
|
+
| Token stream | `SqlTokens`, `SqlToken`, `IsSignificantToken` | Lexes SQL and MJ template tags together. Lossless, linear time, never throws. |
|
|
17
|
+
| MJ Query template | `QueryTemplate`, `TemplateExpressionParser`, template node types, `BranchVariantValues` | Parses the template layer: parameters, compositions, doc comments, branch variants, save-time validation. |
|
|
18
|
+
| SQL document | `SqlDocument` and its analyses | Tolerant structural parse of rendered SQL: table and column references, output columns, CTEs, ORDER BY, row caps, read-only check. |
|
|
19
|
+
| Edits | `EditSet`, `StripOrderBy`, `ReplaceSelectList`, `AppendTail`, `SetRowCap`, `HoistCTEs`, `RenameCTE`, `WrapAsDerivedTable`, `OutputOrderBy` | Changes SQL by replacing exact spans of the original text, so everything not edited stays as written. |
|
|
20
|
+
| Strict screen | `StrictFragmentValidator` | Reads untrusted caller SQL with node-sql-parser and refuses anything it cannot parse. |
|
|
21
|
+
| Diagnostics | `Diagnostic`, `Span`, `Analysis<T>`, `MJQueryDiagnosticCodes`, `SqlDocumentDiagnosticCodes` | One result and finding shape shared by every layer. |
|
|
22
|
+
|
|
23
|
+
The MJ Query language itself (tag forms, filters, parameters, composition, doc comments, every save-time rule and
|
|
24
|
+
diagnostic code) is specified in the [MJ Query Language guide](../../guides/MJ_QUERY_LANGUAGE.md). This README covers
|
|
25
|
+
the code API.
|
|
26
|
+
|
|
27
|
+
### Results and diagnostics
|
|
28
|
+
|
|
29
|
+
Analyses return an `Analysis<T>`: `{ Value, Complete, Diagnostics }`. `Complete` is `false` when part of the input
|
|
30
|
+
could not be read, so `Value` may be missing something. An analysis never answers "nothing found" when it means "could
|
|
31
|
+
not tell".
|
|
32
|
+
|
|
33
|
+
A `Diagnostic` has a stable `Code` (`MJQ_…` for the template layer, `SQL_…` for the SQL document), a `Severity`
|
|
34
|
+
(`Error`, `Warning` or `Info`), a `Span`, a `Message` and a `FixHint`. A `Span` is `{ Start, End }` in UTF-16 offsets
|
|
35
|
+
into the input, end exclusive. Codes are listed as constants in `MJQueryDiagnosticCodes` and
|
|
36
|
+
`SqlDocumentDiagnosticCodes`; a code is never renamed or reused.
|
|
37
|
+
|
|
38
|
+
## Lexing SQL
|
|
39
|
+
|
|
40
|
+
`SqlTokens.Lex(text, dialect)` splits the text into tokens. Joining the tokens' text gives the input back. SQL
|
|
41
|
+
comments are found first, so a template tag inside a `--` or `/* */` comment stays part of the comment and gets an
|
|
42
|
+
`Info` diagnostic (`MJQ_EXPRESSION_IN_COMMENT`).
|
|
43
|
+
|
|
44
|
+
```typescript
|
|
45
|
+
import { SqlTokens, IsSignificantToken } from '@memberjunction/sql-parser';
|
|
46
|
+
import { SQLServerDialect } from '@memberjunction/sql-dialect';
|
|
47
|
+
|
|
48
|
+
const dialect = new SQLServerDialect();
|
|
49
|
+
const tokens = SqlTokens.Lex(
|
|
50
|
+
`SELECT [Name] -- {{ Ignored }}\nFROM dbo.Users WHERE ID = {{ UserID | sqlString }}`,
|
|
51
|
+
dialect,
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
for (const token of tokens.Significant()) {
|
|
55
|
+
// Word "SELECT", QuotedIdentifier "[Name]", Word "FROM", ..., TemplateExpression "{{ UserID | sqlString }}"
|
|
56
|
+
console.log(token.Kind, token.Text, token.Span.Start, token.Depth);
|
|
57
|
+
}
|
|
58
|
+
tokens.HasTemplate; // true
|
|
59
|
+
tokens.Tokens.filter(t => !IsSignificantToken(t)).length; // whitespace and comment tokens
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Each `SqlToken` carries its `Kind`, exact `Text`, `Span`, parenthesis `Depth`, and, for template tags, a `Template`
|
|
63
|
+
record that says which SQL context the tag sits in (code, string literal, quoted identifier or comment).
|
|
64
|
+
|
|
65
|
+
## MJ Query templates
|
|
66
|
+
|
|
67
|
+
`QueryTemplate.Parse(text, dialect)` builds the template tree (`Nodes`) and computes analyses on first call. Parsing
|
|
68
|
+
never throws. The tree's node kinds are `SqlText`, `Expression`, `If`, `For`, `Set`, `Composition`, `DocComment` and
|
|
69
|
+
`Unknown`; `AllNodes`, `ChildBodies` and `NodeExpressions` walk it. `TemplateExpressionParser.Parse(source, start,
|
|
70
|
+
end)` parses one expression of the template grammar on its own, with absolute offsets.
|
|
71
|
+
|
|
72
|
+
| Method | Returns |
|
|
73
|
+
|---|---|
|
|
74
|
+
| `Parameters()` | Each parameter: `Name`, `Filters`, `InferredType`, `IsRequired`, `DefaultValue`, and every use with its span. |
|
|
75
|
+
| `CompositionReferences()` | Each `{{query:"…"}}`: `FullPath`, `CategoryPath`, `Name`, `Arguments`, `InTablePosition`, `InsideConditional`. |
|
|
76
|
+
| `ContextTokens()` | Each `Context.<Token>` read, and whether it is a known token. |
|
|
77
|
+
| `DocComments()` | The `Summary`, `@param` entries and `@field` entries, from `{# #}` headers and trailing `--:` comments. |
|
|
78
|
+
| `BranchVariants()` | A base parameter assignment plus one variant per `{% if %}`, so rendering them all shows every branch's SQL. |
|
|
79
|
+
| `Validate(options)` | Every save-time rule; `Value` is `{ IsValid, ErrorCount, WarningCount }`. |
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
import { QueryTemplate, BranchVariantValues } from '@memberjunction/sql-parser';
|
|
83
|
+
|
|
84
|
+
const sql = `{#
|
|
85
|
+
Orders for one region.
|
|
86
|
+
@param {string} Region The sales region code.
|
|
87
|
+
#}
|
|
88
|
+
SELECT o.OrderID, o.Total --: The order total.
|
|
89
|
+
FROM dbo.Orders o
|
|
90
|
+
JOIN {{query:"Sales/Targets/Regional Targets(Region=Region)"}} t ON t.Region = o.Region
|
|
91
|
+
WHERE o.Region = {{ Region | sqlString }}
|
|
92
|
+
{% if MinTotal %} AND o.Total >= {{ MinTotal | sqlNumber }}{% endif %}`;
|
|
93
|
+
|
|
94
|
+
const template = QueryTemplate.Parse(sql, dialect);
|
|
95
|
+
|
|
96
|
+
for (const p of template.Parameters().Value) {
|
|
97
|
+
console.log(p.Name, p.InferredType, p.IsRequired); // Region string true; MinTotal number false
|
|
98
|
+
}
|
|
99
|
+
for (const ref of template.CompositionReferences().Value) {
|
|
100
|
+
console.log(ref.FullPath, ref.Arguments.map(a => a.Name)); // Sales/Targets/Regional Targets ['Region']
|
|
101
|
+
}
|
|
102
|
+
const docs = template.DocComments().Value;
|
|
103
|
+
docs.Summary; // 'Orders for one region.'
|
|
104
|
+
docs.Fields.map(f => f.Name); // ['Total'] (from the trailing --: comment)
|
|
105
|
+
|
|
106
|
+
const variants = template.BranchVariants().Value;
|
|
107
|
+
for (const variant of variants.Variants) {
|
|
108
|
+
const values = BranchVariantValues(variants, variant); // the base values with this variant's overrides
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Validating a template
|
|
113
|
+
|
|
114
|
+
`Validate` applies the language's save-time rules. `Mode: 'Save'` (the default) is for a new or edited query, where
|
|
115
|
+
every rule is an error. `Mode: 'Refresh'` re-checks a query already saved, and turns the few rules existing queries
|
|
116
|
+
may rely on into warnings. Without `ResolveComposition`, composition targets are not checked and the result is not
|
|
117
|
+
`Complete`. The options are described in full in the guide's "Validating from code" section.
|
|
118
|
+
|
|
119
|
+
```typescript
|
|
120
|
+
const check = template.Validate({
|
|
121
|
+
Mode: 'Save',
|
|
122
|
+
DeclaredParameters: [
|
|
123
|
+
{ Name: 'Region', Type: 'string' },
|
|
124
|
+
{ Name: 'MinTotal', Type: 'number' },
|
|
125
|
+
],
|
|
126
|
+
QueryPath: 'Sales/Reports/Regional Orders',
|
|
127
|
+
ResolveComposition: fullPath => fullPath === 'Sales/Targets/Regional Targets'
|
|
128
|
+
? { Exists: true, Reusable: true, Parameters: [{ Name: 'Region', IsRequired: true }] }
|
|
129
|
+
: null,
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
if (!check.Value.IsValid) {
|
|
133
|
+
for (const d of check.Diagnostics.filter(d => d.Severity === 'Error')) {
|
|
134
|
+
console.log(`${d.Code} at ${d.Span.Start}: ${d.Message} ${d.FixHint ?? ''}`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## SqlDocument: reading SQL
|
|
140
|
+
|
|
141
|
+
`SqlDocument.Parse(text, dialect)` parses SQL with MJ's own structural parser. It is:
|
|
142
|
+
|
|
143
|
+
- **Lossless.** `Print()` returns the input byte for byte, and `Text(node)` returns the exact slice a node covers.
|
|
144
|
+
- **Tolerant.** It never throws. Syntax it does not know becomes an `Unknown` node plus a diagnostic, and the rest of
|
|
145
|
+
the statement is still read. `IsComplete` says whether everything was read.
|
|
146
|
+
- **For SQL, not templates.** Render the template first. A tag left in the text is read as an opaque value and reported
|
|
147
|
+
(`SQL_TEMPLATE_TOKEN`).
|
|
148
|
+
|
|
149
|
+
| Method | Returns |
|
|
150
|
+
|---|---|
|
|
151
|
+
| `TableReferences()` | Every table, CTE and table-valued function read anywhere, with `Kind` (`Table`, `CTE`, `Function`) and `Schema` (`null` when the name is unqualified). |
|
|
152
|
+
| `ColumnReferences()` | Every identifier path that can be a column, with its clause and the source it binds to when that can be resolved. |
|
|
153
|
+
| `OutputItems()` | The first statement's output columns (`Name`, `Alias`, `IsStar`, …); for a set operation, every branch's too. |
|
|
154
|
+
| `CTEs()` | Every CTE declared, leading or nested. |
|
|
155
|
+
| `TopLevelOrderBy()` | The first statement's top-level ORDER BY with its exact span, or `null`. |
|
|
156
|
+
| `RowCaps()` | The TOP, LIMIT, OFFSET and FETCH clauses the top-level query carries. |
|
|
157
|
+
| `IsReadOnly()` | Whether the document is exactly one read statement, with the reason when it is not. Fails closed. |
|
|
158
|
+
| `StatementKinds()`, `HasStackedStatements()` | The kind of each statement, and whether there is more than one. |
|
|
159
|
+
| `WholeRowConstructs()` | Stars, `FOR JSON` / `FOR XML`, `NATURAL JOIN`, set operations and other constructs that read whole rows. |
|
|
160
|
+
| `DuplicateOutputNames(options)` | Output names used more than once. Incomplete when the output has a star. |
|
|
161
|
+
| `Scope()`, `TopLevelQuery()`, `Statements` | Name resolution and the tree itself, for callers that need more than the analyses. |
|
|
162
|
+
|
|
163
|
+
```typescript
|
|
164
|
+
import { SqlDocument } from '@memberjunction/sql-parser';
|
|
165
|
+
|
|
166
|
+
const doc = SqlDocument.Parse(`WITH Recent AS (SELECT * FROM dbo.Orders WHERE OrderDate > '2024-01-01')
|
|
167
|
+
SELECT TOP 10 c.Name, r.Total AS OrderTotal
|
|
168
|
+
FROM Recent r JOIN Customers c ON c.ID = r.CustomerID
|
|
169
|
+
ORDER BY r.Total DESC`, dialect);
|
|
170
|
+
|
|
171
|
+
for (const ref of doc.TableReferences().Value) {
|
|
172
|
+
console.log(ref.Kind, ref.Schema, ref.Name.Parts.map(p => p.Value).join('.'));
|
|
173
|
+
// Table dbo dbo.Orders / CTE null Recent / Table null Customers
|
|
174
|
+
}
|
|
175
|
+
doc.OutputItems().Value.Items.map(i => i.Name); // ['Name', 'OrderTotal']
|
|
176
|
+
doc.RowCaps().Value.map(c => [c.Form, c.Rows]); // [['Top', 10]]
|
|
177
|
+
const orderBy = doc.TopLevelOrderBy().Value;
|
|
178
|
+
if (orderBy) doc.Text(orderBy.Span); // 'ORDER BY r.Total DESC'
|
|
179
|
+
doc.IsReadOnly().Value; // { IsReadOnly: true, Reason: null }
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
## Editing SQL
|
|
183
|
+
|
|
184
|
+
An `EditSet` is a set of edits to one text, kept as a value: each method returns a new set. Edits target a node (any
|
|
185
|
+
object with a `Span`) or a span of the original text, and overlapping edits throw an `EditConflictError`. `Apply()`
|
|
186
|
+
returns the new text and a `SpanMap` from old offsets to new ones. `Merge` combines two sets over the same text.
|
|
187
|
+
|
|
188
|
+
```typescript
|
|
189
|
+
const users = SqlDocument.Parse('SELECT Name FROM Users WHERE Active = 1', dialect);
|
|
190
|
+
const table = users.TableReferences().Value[0];
|
|
191
|
+
|
|
192
|
+
const applied = users.Edit()
|
|
193
|
+
.Replace(table.Name, 'dbo.ActiveUsers')
|
|
194
|
+
.InsertAfter(table.Name, ' u')
|
|
195
|
+
.Apply();
|
|
196
|
+
applied.Text; // 'SELECT Name FROM dbo.ActiveUsers u WHERE Active = 1'
|
|
197
|
+
applied.SpanMap.MapSpan(table.Span); // where the table name sits in the new text
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
The transforms build on edit sets and return a `SqlTransformResult`: `{ Text, Applied, Edits, Diagnostics }`. When a
|
|
201
|
+
transform does not fit the statement it returns the original text with `Applied: false`, and says why in
|
|
202
|
+
`Diagnostics` when there is something to report (`SQL_TRANSFORM_NOT_APPLICABLE`).
|
|
203
|
+
|
|
204
|
+
| Transform | Does |
|
|
205
|
+
|---|---|
|
|
206
|
+
| `StripOrderBy(doc, target?)` | Removes exactly the top-level ORDER BY. Later clauses (`OFFSET`, `FETCH`, `FOR`, `OPTION`) stay. |
|
|
207
|
+
| `ReplaceSelectList(doc, text)` | Replaces a plain select list, such as with `1` for a count. Not for set operations or `DISTINCT`. |
|
|
208
|
+
| `AppendTail(doc, dialect, options)` | Adds `OFFSET` / `FETCH` / `LIMIT` and query hints, with the ORDER BY the dialect needs for paging. |
|
|
209
|
+
| `SetRowCap(doc, dialect, rows)` | Tightens an existing numeric cap, or adds one in the dialect's form. |
|
|
210
|
+
| `HoistCTEs(doc)` | Splits the leading WITH clause from the query it feeds, as written. Returns `HoistedCTEs` or `null`. |
|
|
211
|
+
| `RenameCTE(doc, dialect, oldName, newName, cte?)` | Renames a CTE and every reference that binds to it. Strings, aliases and same-named columns are untouched. |
|
|
212
|
+
| `WrapAsDerivedTable(doc, dialect, alias, options?)` | `SELECT * FROM (query) AS alias`, with leading CTEs hoisted out and the ORDER BY moved, kept or dropped. |
|
|
213
|
+
| `OutputOrderBy(doc, orderBy)` | An ORDER BY's text with column qualifiers dropped, to order a query that wraps the original. |
|
|
214
|
+
|
|
215
|
+
```typescript
|
|
216
|
+
import { StripOrderBy, SetRowCap, WrapAsDerivedTable } from '@memberjunction/sql-parser';
|
|
217
|
+
|
|
218
|
+
StripOrderBy(doc).Text; // the same SQL without 'ORDER BY r.Total DESC'
|
|
219
|
+
SetRowCap(doc, dialect, 5).Text; // TOP 10 becomes TOP 5
|
|
220
|
+
const wrapped = WrapAsDerivedTable(doc, dialect, 'q');
|
|
221
|
+
if (wrapped.Applied) {
|
|
222
|
+
// WITH Recent AS (...) SELECT * FROM ( SELECT TOP 10 ... ORDER BY r.Total DESC ) AS [q] ORDER BY Total DESC
|
|
223
|
+
}
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
## StrictFragmentValidator: untrusted caller SQL
|
|
227
|
+
|
|
228
|
+
`StrictFragmentValidator` is the screen for SQL that a caller supplies: a WHERE or ORDER BY fragment, an aggregate
|
|
229
|
+
expression, or a whole read statement. It parses with node-sql-parser in the dialect's grammar and **refuses text it
|
|
230
|
+
cannot parse** rather than guessing. Use it where refusing unparseable input is the correct answer, and never to
|
|
231
|
+
rewrite SQL that MJ owns.
|
|
232
|
+
|
|
233
|
+
| Method | Checks |
|
|
234
|
+
|---|---|
|
|
235
|
+
| `ValidateFilter(filter, dialect, options?)` | A WHERE fragment, read as `SELECT 1 FROM … WHERE (fragment)`. |
|
|
236
|
+
| `ValidateOrderBy(orderBy, dialect, options?)` | An ORDER BY list. |
|
|
237
|
+
| `ValidateReadOnlyStatement(sql, dialect, options?)` | A whole statement: valid only as one plain read-only SELECT. |
|
|
238
|
+
| `ValidateAggregateExpression(expression, dialect, columns)` | One aggregate call over known columns; returns rebuilt `SQL` to run in place of the caller's text. |
|
|
239
|
+
|
|
240
|
+
A `StrictValidationResult` has `IsValid`, a `Refusal` (`NoGrammar`, `Unparseable`, `WriteStatement`,
|
|
241
|
+
`NotPlainSelect`, `NestedWrite`) with a `Reason` sentence, the statement facts the decision used, and, when asked for
|
|
242
|
+
with `CollectReads` / `CollectColumnReferences`, the relations read and the WHERE column references.
|
|
243
|
+
|
|
244
|
+
```typescript
|
|
245
|
+
import { StrictFragmentValidator } from '@memberjunction/sql-parser';
|
|
246
|
+
|
|
247
|
+
const filter = StrictFragmentValidator.ValidateFilter(`Status = 'Active' AND Total > 100`, dialect, {
|
|
248
|
+
CollectColumnReferences: true,
|
|
249
|
+
});
|
|
250
|
+
filter.IsValid; // true
|
|
251
|
+
filter.ColumnReferences; // ['Status', 'Total']
|
|
252
|
+
|
|
253
|
+
StrictFragmentValidator.ValidateFilter(`1=1; DROP TABLE Users`, dialect).Refusal; // 'Unparseable'
|
|
254
|
+
|
|
255
|
+
const statement = StrictFragmentValidator.ValidateReadOnlyStatement(
|
|
256
|
+
'SELECT u.ID FROM dbo.Users u JOIN dbo.Roles r ON r.ID = u.RoleID', dialect, { CollectReads: true });
|
|
257
|
+
statement.Reads?.Relations.map(r => `${r.SchemaName}.${r.TableName}`); // ['dbo.Users', 'dbo.Roles']
|
|
258
|
+
|
|
259
|
+
const aggregate = StrictFragmentValidator.ValidateAggregateExpression('SUM(Total)', dialect, ['Total', 'Status']);
|
|
260
|
+
aggregate.SQL; // 'SUM([Total])'
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
## Which read-only check to use when
|
|
264
|
+
|
|
265
|
+
Three checks answer "is this SQL a single read?". They differ in what they do with SQL they cannot fully read.
|
|
266
|
+
|
|
267
|
+
| Check | How it reads | Unreadable SQL | Use it for |
|
|
268
|
+
|---|---|---|---|
|
|
269
|
+
| `IsReadOnlyQuery(sql, dialect)` | Tokens only (the lexer) | Judged by its tokens; a construct the parsers do not know never makes a read fail | MJ's write gate on every query path: saved queries, composed queries and paged queries. It is the supported check and is **not** deprecated. |
|
|
270
|
+
| `SqlDocument.Parse(sql, dialect).IsReadOnly()` | The structural parser | **Refused** ("part of it could not be read") | Code that already has a `SqlDocument` and wants the stricter answer, including writes nested in CTEs and subqueries and row-locking clauses. |
|
|
271
|
+
| `StrictFragmentValidator.ValidateReadOnlyStatement` (and `ValidateFilter`, `ValidateOrderBy`) | node-sql-parser | **Refused** (`Unparseable`) | SQL from an untrusted caller, where refusing anything the grammar cannot read is correct. |
|
|
272
|
+
|
|
273
|
+
All three refuse stacked statements, `SELECT … INTO`, and statements that are not queries. For example:
|
|
274
|
+
|
|
275
|
+
| SQL | `IsReadOnlyQuery` | `SqlDocument.IsReadOnly()` | `ValidateReadOnlyStatement` |
|
|
276
|
+
|---|---|---|---|
|
|
277
|
+
| `SELECT TRY_CAST(x AS INT) FROM T` | read | read | refused: node-sql-parser cannot parse `TRY_CAST` |
|
|
278
|
+
| `SELECT a FROM t WHERE (b = 1` | read | refused: could not be read | refused |
|
|
279
|
+
| `UPDATE T SET A = 1` | refused | refused | refused |
|
|
280
|
+
|
|
281
|
+
None of these is a sandbox. A read query can still call a function with side effects; running caller SQL under a
|
|
282
|
+
read-only connection and a statement timeout is what contains that.
|
|
283
|
+
|
|
284
|
+
**Do not use `SQLParser.HasWriteStatement` to decide whether SQL is safe.** It returns `false` whenever node-sql-parser
|
|
285
|
+
cannot parse the SQL, so a write it cannot read passes. Use one of the three checks above instead.
|
|
286
|
+
|
|
287
|
+
## Frozen and deprecated APIs
|
|
288
|
+
|
|
289
|
+
Earlier versions of this package were built around the `SQLParser` class and node-sql-parser. Those members are kept
|
|
290
|
+
and keep working until 7.0, but are marked `@deprecated`; new code uses the layers above.
|
|
291
|
+
|
|
292
|
+
**Kept unchanged, node-sql-parser AST included,** for callers that walk that tree: `SQLParser.Astify`, `Sqlify`,
|
|
293
|
+
`ParseSQL`, `SqlifyAST`, `ExprToSQL`, `WalkAST`, `IsIdentifierAliasName`, and the instance `AST` and
|
|
294
|
+
`IdentifierAliases`. `Analyze` and `Substitute` are kept unchanged because they pair with `Astify`. `Tokenize` is kept
|
|
295
|
+
unchanged for callers that splice by its offsets; unlike the new template layer, it still reports tags inside SQL
|
|
296
|
+
comments. The exported `SQLAst` type is node-sql-parser's `AST`.
|
|
297
|
+
|
|
298
|
+
**Reimplemented on the new parser, same shapes:** `ExtractTableRefs`, `ExtractColumnRefs`, `ExtractSelectColumns`,
|
|
299
|
+
`ExtractCTEs`, `Parse` and `ParseWithTemplatePreprocessing` (static and instance forms), and the template helpers
|
|
300
|
+
`ExtractTemplateExpressions`, `ExtractCompositionRefs`, `ExtractConditionalBlocks` and `ExtractParameterInfo`.
|
|
301
|
+
|
|
302
|
+
| Deprecated | Replacement |
|
|
303
|
+
|---|---|
|
|
304
|
+
| `new SQLParser(sql, dialect)` | `SqlDocument.Parse(sql, dialect)` to read; `StrictFragmentValidator` to screen untrusted SQL |
|
|
305
|
+
| `IsValid` | `SqlDocument.IsComplete`, or `StrictFragmentValidator` |
|
|
306
|
+
| `Dialect`, `SQL` | `SqlDocument.Dialect`, `SqlDocument.Text()` |
|
|
307
|
+
| `StatementKind` | `SqlDocument.StatementKinds()` |
|
|
308
|
+
| `HasWriteStatement` | `SqlDocument.IsReadOnly()` or `StrictFragmentValidator.ValidateReadOnlyStatement` |
|
|
309
|
+
| `OuterCap` | `SqlDocument.RowCaps()` |
|
|
310
|
+
| `SetOuterCap`, `ClearOuterCap` | `SetRowCap` / `ReplaceSelectList` transforms |
|
|
311
|
+
| `ClearOrderBy` | `StripOrderBy` transform |
|
|
312
|
+
| `ToSQL` | `EditSet.Apply()` on the original text |
|
|
313
|
+
| `HasUnwrappableTrailingClause` | The top-level query's `For` and `Option` clauses in `SqlDocument` |
|
|
314
|
+
| `SQLParser.HasStackedStatements` | `SqlDocument.HasStackedStatements()` |
|
|
315
|
+
| `StripComments` | `SqlTokens.Lex(sql, dialect)`, keeping the tokens that are not comments |
|
|
316
|
+
| `Parse`, `ParseWithTemplatePreprocessing` | `SqlDocument` (`TableReferences()`, `ColumnReferences()`), with `QueryTemplate` for templated SQL |
|
|
317
|
+
| `ExtractTableRefs` | `SqlDocument.TableReferences()` |
|
|
318
|
+
| `ExtractColumnRefs` | `SqlDocument.ColumnReferences()` |
|
|
319
|
+
| `ExtractSelectColumns` | `SqlDocument.OutputItems()` |
|
|
320
|
+
| `ExtractCTEs`, `SplitLeadingCTEs` | `SqlDocument.CTEs()`, or the `HoistCTEs` transform |
|
|
321
|
+
| `Tokenize` | `QueryTemplate.Parse(sql, dialect)` (`Nodes` and `Tokens`) |
|
|
322
|
+
| `Analyze` | `SqlTokens.Lex(sql, dialect).HasTemplate` and `QueryTemplate` |
|
|
323
|
+
| `Substitute` | `QueryTemplate` |
|
|
324
|
+
| `ExtractTemplateExpressions`, `ExtractConditionalBlocks` | `QueryTemplate.Nodes` |
|
|
325
|
+
| `ExtractCompositionRefs` | `QueryTemplate.CompositionReferences()` |
|
|
326
|
+
| `ExtractParameterInfo` | `QueryTemplate.Parameters()` |
|
|
327
|
+
| `RenameTemplateVariable`, `SubstituteTemplateVariable` | `QueryTemplate.Parameters()` (every use's span) and an `EditSet` |
|
|
328
|
+
| `LexSQL`, `SignificantTokens`, `IsKeyword` | `SqlTokens.Lex(...)`, `.Significant()`, and comparing a `Word` token's `Text` |
|
|
329
|
+
| `AnalyzeTopLevelOrderBy`, `HasTopLevelOrderBy`, `ExtractOrderBy` | `SqlDocument.TopLevelOrderBy()` and the `StripOrderBy` transform |
|
|
330
|
+
| `FindOrderByStatement`, `IsOrderByLegalInCTE` (and lower-case aliases) | `SqlDocument.TopLevelOrderBy()` / `RowCaps()`, with the dialect grammar's `AllowsOrderByInCTE` |
|
|
331
|
+
| `AnalyzePagingShape` | `SqlDocument` (`RowCaps()`, `TopLevelOrderBy()`, `CTEs()`) and `SetRowCap` / `AppendTail` / `WrapAsDerivedTable` |
|
|
332
|
+
| `ParseToIR`, `RenderIR` | `QueryTemplate` and `SqlDocument`; `EditSet` to change query text |
|
|
333
|
+
| `CheckAggregateExpression` | `StrictFragmentValidator.ValidateAggregateExpression` |
|
|
334
|
+
|
|
335
|
+
`IsReadOnlyQuery`, `IsBalancedSQLFragment`, `SplitTopLevelAndTerms` and `FindForbiddenFunctionCalls` are not
|
|
336
|
+
deprecated.
|
|
337
|
+
|
|
338
|
+
### Knowing whether a legacy extraction was complete
|
|
339
|
+
|
|
340
|
+
`ExtractSelectColumns` and `ExtractColumnRefs` return `[]` both when there is nothing to find and when the SQL could
|
|
341
|
+
not be read. `SQLParser.ExtractSelectColumnsChecked(sql, dialect)` and `SQLParser.ExtractColumnRefsChecked(sql,
|
|
342
|
+
dialect)` return the same columns as `CheckedSelectColumns` / `CheckedColumnReferences`, which add `Complete` and
|
|
343
|
+
`Diagnostics`, so a caller can tell the two apart.
|
|
344
|
+
|
|
345
|
+
```typescript
|
|
346
|
+
import { SQLParser } from '@memberjunction/sql-parser';
|
|
347
|
+
|
|
348
|
+
const checked = SQLParser.ExtractSelectColumnsChecked('SELECT TRY_CAST(a AS INT) AS A FROM T', dialect);
|
|
349
|
+
checked.Complete; // true
|
|
350
|
+
checked.Columns.map(c => c.OutputName); // ['A']
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
### Behaviour notes for legacy extractor callers
|
|
354
|
+
|
|
355
|
+
The extractors keep their result shapes, but their answers are now correct in cases the old regex fallback got wrong:
|
|
356
|
+
|
|
357
|
+
- **CTE names are not returned as tables.** `WITH x AS (SELECT * FROM Orders) SELECT * FROM x` returns only `Orders`.
|
|
358
|
+
- **No invented `dbo` on PostgreSQL.** For an unqualified name, `SQLTableReference.SchemaName` is the dialect's default
|
|
359
|
+
schema: `dbo` on SQL Server, `public` on PostgreSQL. `SqlDocument.TableReferences()` returns `Schema: null` instead,
|
|
360
|
+
so new code can tell "unqualified" from "written as `dbo`".
|
|
361
|
+
- **Nothing is read from comments or string literals.** `/* FROM Phantom */` and `'from Fake'` produce no table.
|
|
362
|
+
Neither do `EXTRACT(… FROM …)`, `TRIM(… FROM …)` or `IS DISTINCT FROM`, and template placeholders are never
|
|
363
|
+
reported as tables or columns.
|
|
364
|
+
- **Real results where node-sql-parser failed.** SQL with `TRY_CAST`, `WITHIN GROUP`, `COLLATE` or a `FOR JSON`
|
|
365
|
+
subquery now returns its columns and references instead of `[]`.
|
|
366
|
+
- **Table references are also read from non-query statements** such as `CREATE VIEW` and DML, in source order, and a
|
|
367
|
+
three-part name reports its schema part correctly.
|
|
368
|
+
- **Template tags inside SQL comments are no longer reported** by `ExtractTemplateExpressions`,
|
|
369
|
+
`ExtractCompositionRefs` or `ExtractParameterInfo`: comments are removed before a template renders, so such a tag is
|
|
370
|
+
never live. A tag inside a string literal is still a tag (SQL quoting does not hide it) and is still reported; saving
|
|
371
|
+
a query with one is refused.
|
|
372
|
+
- **`ExtractCTEs` returns the author's exact text** for each definition and for the main statement, rather than SQL
|
|
373
|
+
regenerated from a parse tree.
|
|
374
|
+
|
|
375
|
+
## Installation
|
|
376
|
+
|
|
377
|
+
```bash
|
|
378
|
+
npm install @memberjunction/sql-parser
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
Or, in a MemberJunction workspace, add the dependency to your package's `package.json` and run `pnpm install` from the
|
|
382
|
+
repo root.
|
|
383
|
+
|
|
384
|
+
## Dependencies
|
|
385
|
+
|
|
386
|
+
- [`@memberjunction/sql-dialect`](../SQLDialect/README.md): the dialects every reader takes.
|
|
387
|
+
- [`node-sql-parser`](https://www.npmjs.com/package/node-sql-parser): used by `StrictFragmentValidator` and the
|
|
388
|
+
frozen AST members only.
|
|
389
|
+
|
|
390
|
+
## License
|
|
391
|
+
|
|
392
|
+
Business Source License 1.1 — see [LICENSE](../../LICENSE) for details.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { SQLParserDialect } from '@memberjunction/sql-dialect';
|
|
2
2
|
/** Result of {@link CheckAggregateExpression}. */
|
|
3
3
|
export interface AggregateExpressionCheck {
|
|
4
4
|
/** Whether the expression may be placed as one item of an aggregate SELECT list. */
|
|
@@ -30,10 +30,14 @@ export interface AggregateExpressionCheck {
|
|
|
30
30
|
* re-quoted or re-checked. So the database runs exactly the expression that was checked, even
|
|
31
31
|
* where the parser and the database would read the caller's text differently.
|
|
32
32
|
*
|
|
33
|
+
* The check is {@link StrictFragmentValidator.ValidateAggregateExpression}; this keeps its
|
|
34
|
+
* original result shape.
|
|
35
|
+
*
|
|
33
36
|
* @param expression The caller-supplied aggregate expression
|
|
34
37
|
* @param dialect The dialect the expression runs under
|
|
35
38
|
* @param columns The entity's column names (its base view's columns). A reference matches a column
|
|
36
39
|
* by `IdentifierMatches` from `@memberjunction/sql-dialect`, the field-level security gate's rule.
|
|
40
|
+
* @deprecated Use `StrictFragmentValidator.ValidateAggregateExpression`.
|
|
37
41
|
*/
|
|
38
42
|
export declare function CheckAggregateExpression(expression: string, dialect: SQLParserDialect, columns: Iterable<string>): AggregateExpressionCheck;
|
|
39
43
|
//# sourceMappingURL=aggregateExpression.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aggregateExpression.d.ts","sourceRoot":"","sources":["../src/aggregateExpression.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"aggregateExpression.d.ts","sourceRoot":"","sources":["../src/aggregateExpression.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAGpE,kDAAkD;AAClD,MAAM,WAAW,wBAAwB;IACrC,oFAAoF;IACpF,SAAS,EAAE,OAAO,CAAC;IACnB,iEAAiE;IACjE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB;;;OAGG;IACH,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;CACtB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,wBAAwB,CAG3I"}
|