@memberjunction/sql-parser 5.27.1 → 5.29.0

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.
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Composition IR — Typed intermediate representation for the composition engine.
3
+ *
4
+ * This IR is **deliberately not a full SQL AST.** It's a *structural* IR that
5
+ * knows about the bits of SQL the composition pipeline needs to manipulate:
6
+ * - CTEs (hoisting, renaming, dependency ordering)
7
+ * - Top-level ORDER BY (stripping for CTE legality)
8
+ * - Template expressions and block tags (preserved for Nunjucks)
9
+ * - Comments and string literals (context awareness)
10
+ *
11
+ * Expressions are treated as opaque SQL text. The IR's job is to understand
12
+ * *where* template tokens sit in the SQL structure (inside a string literal?
13
+ * inside a CTE body? inside a subquery?) so that composition can work
14
+ * correctly around them.
15
+ *
16
+ * The IR renderer emits SQL with {{ }}/{% %} tokens intact for Nunjucks
17
+ * evaluation downstream.
18
+ */
19
+ /** Opaque SQL text — treated as-is by the IR */
20
+ export interface SQLFragment {
21
+ Kind: 'sql';
22
+ /** Raw SQL text (may contain anything except MJ tokens) */
23
+ Text: string;
24
+ }
25
+ /** A Nunjucks template expression: {{ variable | filter1 | filter2 }} */
26
+ export interface TemplateExprFragment {
27
+ Kind: 'template-expr';
28
+ /** The raw text including {{ and }} */
29
+ Raw: string;
30
+ /** The variable name (first token after {{) */
31
+ Variable: string;
32
+ }
33
+ /** A Nunjucks block tag region: {% if/for/set %} ... {% endif/endfor %} */
34
+ export interface BlockFragment {
35
+ Kind: 'block';
36
+ /** The raw text of the entire block including tags */
37
+ Raw: string;
38
+ /** Block type */
39
+ BlockType: 'if' | 'for' | 'set' | 'other';
40
+ }
41
+ /** A SQL comment (line or block) */
42
+ export interface CommentFragment {
43
+ Kind: 'comment';
44
+ /** Raw comment text including delimiters */
45
+ Raw: string;
46
+ }
47
+ /** A composition reference: {{query:"..."}} — only present pre-resolution */
48
+ export interface CompositionRefFragment {
49
+ Kind: 'composition-ref';
50
+ /** The raw text including {{ and }} */
51
+ Raw: string;
52
+ /** Parsed query path */
53
+ QueryPath: string;
54
+ }
55
+ /** Union of all fragment types */
56
+ export type Fragment = SQLFragment | TemplateExprFragment | BlockFragment | CommentFragment | CompositionRefFragment;
57
+ /**
58
+ * A CTE definition in the WITH clause.
59
+ */
60
+ export interface CTENode {
61
+ /** Symbol-table-assigned unique identifier */
62
+ Id: string;
63
+ /** The CTE name as it should appear in rendered SQL (may be quoted) */
64
+ Name: string;
65
+ /** The canonical (unquoted, lowercased) name for comparison */
66
+ CanonicalName: string;
67
+ /** The CTE body as a sequence of fragments */
68
+ Body: Fragment[];
69
+ /** Optional column list */
70
+ Columns?: string[];
71
+ /** Provenance: who created this CTE */
72
+ Origin: CTEOrigin;
73
+ /** Whether this CTE has a top-level ORDER BY that was stripped */
74
+ OrderByStripped: boolean;
75
+ }
76
+ /** Where a CTE came from */
77
+ export type CTEOrigin = {
78
+ Kind: 'composition';
79
+ DepName: string;
80
+ CategoryPath: string;
81
+ } | {
82
+ Kind: 'hoisted';
83
+ SourceCTEId: string;
84
+ DepName: string;
85
+ } | {
86
+ Kind: 'user';
87
+ } | {
88
+ Kind: 'synthetic';
89
+ };
90
+ /**
91
+ * Top-level IR node — represents the entire SQL statement structure.
92
+ *
93
+ * The composition engine operates on this IR:
94
+ * 1. Parse raw SQL → QueryIR
95
+ * 2. Resolve composition refs → add CTEs, replace refs with CTE names
96
+ * 3. Strip illegal ORDER BYs from CTE bodies
97
+ * 4. Render QueryIR → SQL string (with {{ }}/{% %} intact)
98
+ */
99
+ export interface QueryIR {
100
+ /** WITH clause CTEs in dependency order */
101
+ CTEs: CTENode[];
102
+ /** The main statement body as fragments */
103
+ Body: Fragment[];
104
+ /** Whether the original SQL started with a WITH clause */
105
+ HasUserCTEs: boolean;
106
+ /** Trailing ORDER BY (if detected at top level) */
107
+ TrailingOrderBy: Fragment[] | null;
108
+ /** Whether the ORDER BY is legal in CTE context (TOP/OFFSET/FOR XML) */
109
+ OrderByIsLegalInCTE: boolean;
110
+ }
111
+ //# sourceMappingURL=compositionIR.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compositionIR.d.ts","sourceRoot":"","sources":["../src/compositionIR.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAMH,gDAAgD;AAChD,MAAM,WAAW,WAAW;IACxB,IAAI,EAAE,KAAK,CAAC;IACZ,2DAA2D;IAC3D,IAAI,EAAE,MAAM,CAAC;CAChB;AAED,yEAAyE;AACzE,MAAM,WAAW,oBAAoB;IACjC,IAAI,EAAE,eAAe,CAAC;IACtB,uCAAuC;IACvC,GAAG,EAAE,MAAM,CAAC;IACZ,+CAA+C;IAC/C,QAAQ,EAAE,MAAM,CAAC;CACpB;AAED,2EAA2E;AAC3E,MAAM,WAAW,aAAa;IAC1B,IAAI,EAAE,OAAO,CAAC;IACd,sDAAsD;IACtD,GAAG,EAAE,MAAM,CAAC;IACZ,iBAAiB;IACjB,SAAS,EAAE,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,OAAO,CAAC;CAC7C;AAED,oCAAoC;AACpC,MAAM,WAAW,eAAe;IAC5B,IAAI,EAAE,SAAS,CAAC;IAChB,4CAA4C;IAC5C,GAAG,EAAE,MAAM,CAAC;CACf;AAED,6EAA6E;AAC7E,MAAM,WAAW,sBAAsB;IACnC,IAAI,EAAE,iBAAiB,CAAC;IACxB,uCAAuC;IACvC,GAAG,EAAE,MAAM,CAAC;IACZ,wBAAwB;IACxB,SAAS,EAAE,MAAM,CAAC;CACrB;AAED,kCAAkC;AAClC,MAAM,MAAM,QAAQ,GACd,WAAW,GACX,oBAAoB,GACpB,aAAa,GACb,eAAe,GACf,sBAAsB,CAAC;AAM7B;;GAEG;AACH,MAAM,WAAW,OAAO;IACpB,8CAA8C;IAC9C,EAAE,EAAE,MAAM,CAAC;IACX,uEAAuE;IACvE,IAAI,EAAE,MAAM,CAAC;IACb,+DAA+D;IAC/D,aAAa,EAAE,MAAM,CAAC;IACtB,8CAA8C;IAC9C,IAAI,EAAE,QAAQ,EAAE,CAAC;IACjB,2BAA2B;IAC3B,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,uCAAuC;IACvC,MAAM,EAAE,SAAS,CAAC;IAClB,kEAAkE;IAClE,eAAe,EAAE,OAAO,CAAC;CAC5B;AAED,4BAA4B;AAC5B,MAAM,MAAM,SAAS,GACf;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GAC9D;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACzD;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,GAChB;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,CAAC;AAE5B;;;;;;;;GAQG;AACH,MAAM,WAAW,OAAO;IACpB,2CAA2C;IAC3C,IAAI,EAAE,OAAO,EAAE,CAAC;IAChB,2CAA2C;IAC3C,IAAI,EAAE,QAAQ,EAAE,CAAC;IACjB,0DAA0D;IAC1D,WAAW,EAAE,OAAO,CAAC;IACrB,mDAAmD;IACnD,eAAe,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;IACnC,wEAAwE;IACxE,mBAAmB,EAAE,OAAO,CAAC;CAChC"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Composition IR — Typed intermediate representation for the composition engine.
3
+ *
4
+ * This IR is **deliberately not a full SQL AST.** It's a *structural* IR that
5
+ * knows about the bits of SQL the composition pipeline needs to manipulate:
6
+ * - CTEs (hoisting, renaming, dependency ordering)
7
+ * - Top-level ORDER BY (stripping for CTE legality)
8
+ * - Template expressions and block tags (preserved for Nunjucks)
9
+ * - Comments and string literals (context awareness)
10
+ *
11
+ * Expressions are treated as opaque SQL text. The IR's job is to understand
12
+ * *where* template tokens sit in the SQL structure (inside a string literal?
13
+ * inside a CTE body? inside a subquery?) so that composition can work
14
+ * correctly around them.
15
+ *
16
+ * The IR renderer emits SQL with {{ }}/{% %} tokens intact for Nunjucks
17
+ * evaluation downstream.
18
+ */
19
+ export {};
20
+ //# sourceMappingURL=compositionIR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compositionIR.js","sourceRoot":"","sources":["../src/compositionIR.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,9 @@
1
1
  export { SQLParser } from './sql-parser.js';
2
+ export type { SQLParserDialect } from '@memberjunction/sql-dialect';
3
+ export { AnalyzeTopLevelOrderBy, HasTopLevelOrderBy, ExtractOrderBy, findOrderByStatement, isOrderByLegalInCTE } from './orderByAnalyzer.js';
4
+ export type { OrderByAnalysis } from './orderByAnalyzer.js';
5
+ export { ParseToIR, RenderIR } from './structuralParser.js';
6
+ export type { QueryIR, CTENode, Fragment, SQLFragment, TemplateExprFragment, BlockFragment, CommentFragment, CompositionRefFragment, CTEOrigin } from './compositionIR.js';
2
7
  export type { MJAstifyResult, SQLTableReference, SQLColumnReference, SQLSelectColumn, SQLCTEExtraction, MJParameterInfo, SQLParseResult, SQLParseOptions, } from './sql-parser.js';
3
8
  export type { AST as SQLAst } from 'node-sql-parser';
4
9
  export type { MJNode, MJNodeType, MJTemplateExpr, MJFilter, MJCompositionRef, MJCompositionParam, MJConditionalBlock, MJBranch, MJLoopBlock, MJComment, MJSetBlock, MJSQLFragment, MJRawSQL, MJTokenType, MJToken, MJTokenParsedContent, MJTemplateExprContent, MJCompositionRefContent, MJBlockTagContent, MJCommentContent, MJSetContent, MJSQLTextContent, PlaceholderContext, PlaceholderEntry, PlaceholderSubstitutionResult, MJParseResult, SQLClauseContext, MJASTAnnotation, MJASTWalkResult, } from './mj-ast-types.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAA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,EACjB,kBAAkB,EAClB,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,cAAc,EACd,eAAe,GAClB,MAAM,iBAAiB,CAAC;AAGzB,YAAY,EAAE,GAAG,IAAI,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAGrD,YAAY,EAER,MAAM,EACN,UAAU,EACV,cAAc,EACd,QAAQ,EACR,gBAAgB,EAChB,kBAAkB,EAClB,kBAAkB,EAClB,QAAQ,EACR,WAAW,EACX,SAAS,EACT,UAAU,EACV,aAAa,EACb,QAAQ,EAER,WAAW,EACX,OAAO,EACP,oBAAoB,EACpB,qBAAqB,EACrB,uBAAuB,EACvB,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,EAEhB,kBAAkB,EAClB,gBAAgB,EAChB,6BAA6B,EAE7B,aAAa,EAEb,gBAAgB,EAChB,eAAe,EACf,eAAe,GAClB,MAAM,mBAAmB,CAAC"}
package/dist/index.js CHANGED
@@ -1,3 +1,7 @@
1
1
  // MJ SQL Parser — unified parser for MJ's SQL superset
2
2
  export { SQLParser } from './sql-parser.js';
3
+ // ORDER BY analysis (shared between composition and paging engines)
4
+ export { AnalyzeTopLevelOrderBy, HasTopLevelOrderBy, ExtractOrderBy, findOrderByStatement, isOrderByLegalInCTE } from './orderByAnalyzer.js';
5
+ // Structural parser and composition IR
6
+ export { ParseToIR, RenderIR } from './structuralParser.js';
3
7
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAG5C,oEAAoE;AACpE,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,cAAc,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAE7I,uCAAuC;AACvC,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC"}
@@ -0,0 +1,64 @@
1
+ import type { SQLParserDialect } from '@memberjunction/sql-dialect';
2
+ /**
3
+ * Result of analyzing a SQL string for top-level ORDER BY clauses.
4
+ */
5
+ export interface OrderByAnalysis {
6
+ /** Character positions of all top-level ORDER BY keywords in the original SQL */
7
+ Positions: number[];
8
+ /** SQL with the last top-level ORDER BY clause stripped (or original if none found) */
9
+ SqlWithoutOrderBy: string;
10
+ /** The extracted ORDER BY clause text (everything after "ORDER BY "), or null if none */
11
+ OrderByClause: string | null;
12
+ /** Whether the ORDER BY is legal in CTE context (TOP, OFFSET, or FOR XML present) */
13
+ IsLegalInCTE: boolean;
14
+ }
15
+ /**
16
+ * Shared ORDER BY analysis for both the composition engine and the paging engine.
17
+ *
18
+ * Uses a two-tier strategy:
19
+ * **Tier 1**: `node-sql-parser` AST parsing (with Nunjucks placeholder preprocessing
20
+ * if MJ tokens are detected). Most accurate; handles UNION/EXCEPT chains, window
21
+ * functions, and CTE-internal ORDER BYs via the AST.
22
+ *
23
+ * **Tier 2**: `MJLexer.Tokenize` → scan `SQL_TEXT` tokens with **carried**
24
+ * `inString` / `inBlockComment` / `inLineComment` state across MJ token boundaries.
25
+ * Fixes Bug D (Nunjucks expression inside SQL string literal breaks ORDER BY detection).
26
+ *
27
+ * This utility is the single implementation of ORDER BY analysis shared by both
28
+ * `queryCompositionEngine.ts` and `queryPagingEngine.ts`. Both engines delegate
29
+ * here instead of maintaining separate scanners.
30
+ */
31
+ /**
32
+ * Analyzes SQL for top-level ORDER BY clauses, handling both SQL+Nunjucks
33
+ * (composition engine's input) and clean SQL (paging engine's input).
34
+ *
35
+ * @param sql - SQL to analyze (may contain MJ template tokens)
36
+ * @param parserDialect - node-sql-parser dialect ('TransactSQL' or 'PostgresQL')
37
+ * @returns Full analysis including positions, stripped SQL, and CTE legality
38
+ */
39
+ export declare function AnalyzeTopLevelOrderBy(sql: string, dialect: SQLParserDialect): OrderByAnalysis;
40
+ /**
41
+ * Checks whether the given SQL has any top-level ORDER BY clause.
42
+ * Convenience wrapper around {@link AnalyzeTopLevelOrderBy}.
43
+ */
44
+ export declare function HasTopLevelOrderBy(sql: string, dialect: SQLParserDialect): boolean;
45
+ /**
46
+ * Extracts the ORDER BY clause and returns SQL without it.
47
+ * Convenience wrapper around {@link AnalyzeTopLevelOrderBy}.
48
+ */
49
+ export declare function ExtractOrderBy(sql: string, dialect: SQLParserDialect): {
50
+ sqlWithoutOrder: string;
51
+ orderByClause: string | null;
52
+ };
53
+ /**
54
+ * Walks the `_next` chain (UNION/EXCEPT/INTERSECT) to find the statement
55
+ * that carries the ORDER BY clause. This is the single shared implementation
56
+ * replacing the duplicated versions in both engines.
57
+ */
58
+ export declare function findOrderByStatement(stmt: Record<string, unknown>): Record<string, unknown> | null;
59
+ /**
60
+ * Checks AST properties to determine if ORDER BY is legal in a CTE context.
61
+ * TOP, OFFSET/LIMIT, or FOR XML make ORDER BY legal inside a CTE.
62
+ */
63
+ export declare function isOrderByLegalInCTE(stmt: Record<string, unknown>): boolean;
64
+ //# sourceMappingURL=orderByAnalyzer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orderByAnalyzer.d.ts","sourceRoot":"","sources":["../src/orderByAnalyzer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAEpE;;GAEG;AACH,MAAM,WAAW,eAAe;IAC5B,iFAAiF;IACjF,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,uFAAuF;IACvF,iBAAiB,EAAE,MAAM,CAAC;IAC1B,yFAAyF;IACzF,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,qFAAqF;IACrF,YAAY,EAAE,OAAO,CAAC;CACzB;AAED;;;;;;;;;;;;;;;GAeG;AAMH;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAClC,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,gBAAgB,GAC1B,eAAe,CAkBjB;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAElF;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC1B,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,gBAAgB,GAC1B;IAAE,eAAe,EAAE,MAAM,CAAC;IAAC,aAAa,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAG3D;AAgPD;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAIlG;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAY1E"}
@@ -0,0 +1,346 @@
1
+ import { SQLParser } from './sql-parser.js';
2
+ /**
3
+ * Shared ORDER BY analysis for both the composition engine and the paging engine.
4
+ *
5
+ * Uses a two-tier strategy:
6
+ * **Tier 1**: `node-sql-parser` AST parsing (with Nunjucks placeholder preprocessing
7
+ * if MJ tokens are detected). Most accurate; handles UNION/EXCEPT chains, window
8
+ * functions, and CTE-internal ORDER BYs via the AST.
9
+ *
10
+ * **Tier 2**: `MJLexer.Tokenize` → scan `SQL_TEXT` tokens with **carried**
11
+ * `inString` / `inBlockComment` / `inLineComment` state across MJ token boundaries.
12
+ * Fixes Bug D (Nunjucks expression inside SQL string literal breaks ORDER BY detection).
13
+ *
14
+ * This utility is the single implementation of ORDER BY analysis shared by both
15
+ * `queryCompositionEngine.ts` and `queryPagingEngine.ts`. Both engines delegate
16
+ * here instead of maintaining separate scanners.
17
+ */
18
+ // ════════════════════════════════════════════════════════════════════
19
+ // Public API
20
+ // ════════════════════════════════════════════════════════════════════
21
+ /**
22
+ * Analyzes SQL for top-level ORDER BY clauses, handling both SQL+Nunjucks
23
+ * (composition engine's input) and clean SQL (paging engine's input).
24
+ *
25
+ * @param sql - SQL to analyze (may contain MJ template tokens)
26
+ * @param parserDialect - node-sql-parser dialect ('TransactSQL' or 'PostgresQL')
27
+ * @returns Full analysis including positions, stripped SQL, and CTE legality
28
+ */
29
+ export function AnalyzeTopLevelOrderBy(sql, dialect) {
30
+ if (!sql || sql.trim().length === 0) {
31
+ return { Positions: [], SqlWithoutOrderBy: sql, OrderByClause: null, IsLegalInCTE: false };
32
+ }
33
+ const trimmed = sql.trimEnd();
34
+ // Fast exit: no ORDER keyword anywhere → no ORDER BY to analyze
35
+ if (!/ORDER/i.test(trimmed)) {
36
+ return { Positions: [], SqlWithoutOrderBy: sql, OrderByClause: null, IsLegalInCTE: false };
37
+ }
38
+ // Tier 1: AST-based analysis
39
+ const astResult = analyzeViaAST(trimmed, dialect);
40
+ if (astResult !== null)
41
+ return astResult;
42
+ // Tier 2: MJLexer-based scanner (handles SQL+Nunjucks, carries state across token boundaries)
43
+ return analyzeViaScanner(trimmed, sql);
44
+ }
45
+ /**
46
+ * Checks whether the given SQL has any top-level ORDER BY clause.
47
+ * Convenience wrapper around {@link AnalyzeTopLevelOrderBy}.
48
+ */
49
+ export function HasTopLevelOrderBy(sql, dialect) {
50
+ return AnalyzeTopLevelOrderBy(sql, dialect).Positions.length > 0;
51
+ }
52
+ /**
53
+ * Extracts the ORDER BY clause and returns SQL without it.
54
+ * Convenience wrapper around {@link AnalyzeTopLevelOrderBy}.
55
+ */
56
+ export function ExtractOrderBy(sql, dialect) {
57
+ const analysis = AnalyzeTopLevelOrderBy(sql, dialect);
58
+ return { sqlWithoutOrder: analysis.SqlWithoutOrderBy, orderByClause: analysis.OrderByClause };
59
+ }
60
+ // ════════════════════════════════════════════════════════════════════
61
+ // Tier 1: AST-based analysis
62
+ // ════════════════════════════════════════════════════════════════════
63
+ /**
64
+ * Attempts to analyze ORDER BY via node-sql-parser AST.
65
+ * Returns null if parsing fails (caller should fall back to Tier 2).
66
+ */
67
+ function analyzeViaAST(sql, dialect) {
68
+ // Try direct parsing first
69
+ const directResult = tryDirectAST(sql, dialect);
70
+ if (directResult !== null)
71
+ return directResult;
72
+ // If MJ extensions detected, try with Nunjucks preprocessing
73
+ const mjParse = SQLParser.Analyze(sql);
74
+ if (mjParse.hasMJExtensions) {
75
+ return tryNunjucksAwareAST(sql, dialect);
76
+ }
77
+ return null;
78
+ }
79
+ /**
80
+ * Direct AST parsing attempt — works for clean SQL without MJ tokens.
81
+ */
82
+ function tryDirectAST(sql, dialect) {
83
+ try {
84
+ const ast = SQLParser.ParseSQL(sql, dialect);
85
+ if (!ast)
86
+ return null;
87
+ const stmt = Array.isArray(ast) ? ast[0] : ast;
88
+ if (!stmt)
89
+ return buildNoOrderByResult(sql);
90
+ return buildASTAnalysis(stmt, sql);
91
+ }
92
+ catch {
93
+ return null;
94
+ }
95
+ }
96
+ /**
97
+ * Nunjucks-preprocessed AST parsing — substitutes MJ tokens with safe
98
+ * placeholders, parses the resulting clean SQL, then maps results back.
99
+ */
100
+ function tryNunjucksAwareAST(sql, dialect) {
101
+ const preprocessed = SQLParser.Substitute(sql).cleanSQL;
102
+ try {
103
+ const ast = SQLParser.ParseSQL(preprocessed, dialect);
104
+ if (!ast)
105
+ return null;
106
+ const stmt = Array.isArray(ast) ? ast[0] : ast;
107
+ if (!stmt)
108
+ return buildNoOrderByResult(sql);
109
+ const stmtRecord = stmt;
110
+ const orderByStmt = findOrderByStatement(stmtRecord);
111
+ if (!orderByStmt)
112
+ return buildNoOrderByResult(sql);
113
+ const isLegal = isOrderByLegalInCTE(orderByStmt);
114
+ if (isLegal) {
115
+ // ORDER BY is legal — find positions via scanner for completeness
116
+ const positions = findTopLevelOrderByPositions(sql);
117
+ return {
118
+ Positions: positions,
119
+ SqlWithoutOrderBy: sql,
120
+ OrderByClause: extractOrderByClauseText(sql, positions),
121
+ IsLegalInCTE: true,
122
+ };
123
+ }
124
+ // ORDER BY should be stripped — use scanner to find exact position
125
+ const positions = findTopLevelOrderByPositions(sql);
126
+ if (positions.length === 0) {
127
+ // AST says ORDER BY exists, scanner can't find it — inconsistency
128
+ // Fall back to no-op to avoid data loss
129
+ return null;
130
+ }
131
+ return buildStrippedResult(sql, positions);
132
+ }
133
+ catch {
134
+ return null;
135
+ }
136
+ }
137
+ /**
138
+ * Builds the analysis result from an AST statement.
139
+ *
140
+ * Uses AST only for detection (does ORDER BY exist? is it legal in CTE?).
141
+ * Always uses position-based stripping to preserve original SQL formatting —
142
+ * AST regeneration via `SqlifyAST` changes formatting (e.g., adds bracket
143
+ * quoting, normalizes whitespace) which breaks callers that expect the
144
+ * original SQL text to be preserved.
145
+ */
146
+ function buildASTAnalysis(stmt, sql) {
147
+ const orderByStmt = findOrderByStatement(stmt);
148
+ if (!orderByStmt)
149
+ return buildNoOrderByResult(sql);
150
+ const isLegal = isOrderByLegalInCTE(orderByStmt);
151
+ // Use scanner for precise character positions
152
+ const positions = findTopLevelOrderByPositions(sql);
153
+ if (isLegal || positions.length === 0) {
154
+ return {
155
+ Positions: positions,
156
+ SqlWithoutOrderBy: sql,
157
+ OrderByClause: extractOrderByClauseText(sql, positions),
158
+ IsLegalInCTE: isLegal,
159
+ };
160
+ }
161
+ // Always use position-based stripping to preserve original formatting
162
+ return buildStrippedResult(sql, positions);
163
+ }
164
+ // ════════════════════════════════════════════════════════════════════
165
+ // Tier 2: MJLexer-based scanner
166
+ // ════════════════════════════════════════════════════════════════════
167
+ /**
168
+ * Scans SQL using MJLexer tokens with carried lexical state across MJ token
169
+ * boundaries. This is the Bug D fix: `inString`, `inBlockComment`, and
170
+ * `inLineComment` persist across SQL_TEXT token boundaries so that patterns
171
+ * like `'{{ MembershipType }}'` (Nunjucks inside a SQL string literal) don't
172
+ * break ORDER BY detection.
173
+ */
174
+ function analyzeViaScanner(trimmed, originalSQL) {
175
+ const positions = findTopLevelOrderByPositions(trimmed);
176
+ if (positions.length === 0) {
177
+ return { Positions: [], SqlWithoutOrderBy: originalSQL, OrderByClause: null, IsLegalInCTE: false };
178
+ }
179
+ return buildStrippedResult(trimmed, positions);
180
+ }
181
+ /**
182
+ * Finds character positions of all top-level ORDER BY keywords.
183
+ *
184
+ * Uses MJLexer to tokenize the SQL, then scans SQL_TEXT tokens while carrying
185
+ * `inString`, `inBlockComment`, `inLineComment`, and `parenDepth` state
186
+ * across MJ token boundaries.
187
+ */
188
+ function findTopLevelOrderByPositions(sql) {
189
+ const tokens = SQLParser.Tokenize(sql);
190
+ const positions = [];
191
+ let parenDepth = 0;
192
+ let inString = false;
193
+ let inBlockComment = false;
194
+ let inLineComment = false;
195
+ for (const token of tokens) {
196
+ if (token.type !== 'SQL_TEXT') {
197
+ // MJ tokens reset line comment state (an MJ token can't be inside a line comment)
198
+ inLineComment = false;
199
+ continue;
200
+ }
201
+ const text = token.raw;
202
+ let i = 0;
203
+ while (i < text.length) {
204
+ const ch = text[i];
205
+ if (inBlockComment) {
206
+ if (ch === '*' && i + 1 < text.length && text[i + 1] === '/') {
207
+ inBlockComment = false;
208
+ i += 2;
209
+ }
210
+ else {
211
+ i++;
212
+ }
213
+ continue;
214
+ }
215
+ if (inLineComment) {
216
+ if (ch === '\n') {
217
+ inLineComment = false;
218
+ }
219
+ i++;
220
+ continue;
221
+ }
222
+ if (inString) {
223
+ if (ch === "'" && i + 1 < text.length && text[i + 1] === "'") {
224
+ i += 2;
225
+ }
226
+ else if (ch === "'") {
227
+ inString = false;
228
+ i++;
229
+ }
230
+ else {
231
+ i++;
232
+ }
233
+ continue;
234
+ }
235
+ if (ch === "'") {
236
+ inString = true;
237
+ i++;
238
+ continue;
239
+ }
240
+ // Skip bracket-quoted identifiers: [Order By Description] etc.
241
+ // These don't carry across MJ token boundaries in practice.
242
+ if (ch === '[') {
243
+ i++;
244
+ while (i < text.length && text[i] !== ']')
245
+ i++;
246
+ if (i < text.length)
247
+ i++;
248
+ continue;
249
+ }
250
+ // Skip double-quoted identifiers: "Order" etc.
251
+ if (ch === '"') {
252
+ i++;
253
+ while (i < text.length && text[i] !== '"')
254
+ i++;
255
+ if (i < text.length)
256
+ i++;
257
+ continue;
258
+ }
259
+ if (ch === '-' && i + 1 < text.length && text[i + 1] === '-') {
260
+ inLineComment = true;
261
+ i += 2;
262
+ continue;
263
+ }
264
+ if (ch === '/' && i + 1 < text.length && text[i + 1] === '*') {
265
+ inBlockComment = true;
266
+ i += 2;
267
+ continue;
268
+ }
269
+ if (ch === '(') {
270
+ parenDepth++;
271
+ i++;
272
+ continue;
273
+ }
274
+ if (ch === ')') {
275
+ parenDepth--;
276
+ i++;
277
+ continue;
278
+ }
279
+ if (parenDepth === 0 && /^ORDER\s+BY\b/i.test(text.substring(i))) {
280
+ const absPos = token.start + i;
281
+ if (absPos === 0 || /[\s,;()\n]/.test(sql[absPos - 1])) {
282
+ positions.push(absPos);
283
+ }
284
+ }
285
+ i++;
286
+ }
287
+ }
288
+ return positions;
289
+ }
290
+ // ════════════════════════════════════════════════════════════════════
291
+ // AST helpers (shared between composition and paging engines)
292
+ // ════════════════════════════════════════════════════════════════════
293
+ /**
294
+ * Walks the `_next` chain (UNION/EXCEPT/INTERSECT) to find the statement
295
+ * that carries the ORDER BY clause. This is the single shared implementation
296
+ * replacing the duplicated versions in both engines.
297
+ */
298
+ export function findOrderByStatement(stmt) {
299
+ if (stmt.orderby)
300
+ return stmt;
301
+ if (stmt._next)
302
+ return findOrderByStatement(stmt._next);
303
+ return null;
304
+ }
305
+ /**
306
+ * Checks AST properties to determine if ORDER BY is legal in a CTE context.
307
+ * TOP, OFFSET/LIMIT, or FOR XML make ORDER BY legal inside a CTE.
308
+ */
309
+ export function isOrderByLegalInCTE(stmt) {
310
+ if (stmt.top)
311
+ return true;
312
+ if (stmt.limit)
313
+ return true;
314
+ if (stmt.offset)
315
+ return true;
316
+ const forClause = stmt.for;
317
+ if (forClause && typeof forClause === 'object' && forClause.type &&
318
+ String(forClause.type).toLowerCase().includes('xml')) {
319
+ return true;
320
+ }
321
+ return false;
322
+ }
323
+ // ════════════════════════════════════════════════════════════════════
324
+ // Result builders
325
+ // ════════════════════════════════════════════════════════════════════
326
+ function buildNoOrderByResult(sql) {
327
+ return { Positions: [], SqlWithoutOrderBy: sql, OrderByClause: null, IsLegalInCTE: false };
328
+ }
329
+ function buildStrippedResult(sql, positions) {
330
+ const lastPos = positions[positions.length - 1];
331
+ return {
332
+ Positions: positions,
333
+ SqlWithoutOrderBy: sql.substring(0, lastPos).trimEnd(),
334
+ OrderByClause: extractOrderByClauseText(sql, positions),
335
+ IsLegalInCTE: false,
336
+ };
337
+ }
338
+ function extractOrderByClauseText(sql, positions) {
339
+ if (positions.length === 0)
340
+ return null;
341
+ const lastPos = positions[positions.length - 1];
342
+ // Skip past "ORDER BY " (8 chars for "ORDER BY" + whitespace)
343
+ const afterKeyword = sql.substring(lastPos).replace(/^ORDER\s+BY\s+/i, '');
344
+ return afterKeyword.trim() || null;
345
+ }
346
+ //# sourceMappingURL=orderByAnalyzer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orderByAnalyzer.js","sourceRoot":"","sources":["../src/orderByAnalyzer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAiB5C;;;;;;;;;;;;;;;GAeG;AAEH,uEAAuE;AACvE,aAAa;AACb,uEAAuE;AAEvE;;;;;;;GAOG;AACH,MAAM,UAAU,sBAAsB,CAClC,GAAW,EACX,OAAyB;IAEzB,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAClC,OAAO,EAAE,SAAS,EAAE,EAAE,EAAE,iBAAiB,EAAE,GAAG,EAAE,aAAa,EAAE,IAAI,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC;IAC/F,CAAC;IAED,MAAM,O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