@memberjunction/generic-database-provider 6.2.0-edge.2 → 6.2.0-edge.4

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.
@@ -1,21 +1,36 @@
1
- import { SQLParser, AnalyzeTopLevelOrderBy } from '@memberjunction/sql-parser';
1
+ import { AnalyzeTopLevelOrderBy, AnalyzePagingShape, IsReadOnlyQuery, LexSQL } from '@memberjunction/sql-parser';
2
2
  import { GetDialect, SQLServerDialect } from '@memberjunction/sql-dialect';
3
+ function capped(sql, method) {
4
+ return { SQL: sql, Outcome: { Applied: true, Method: method, Reason: null } };
5
+ }
6
+ function notCapped(sql, reason) {
7
+ return { SQL: sql, Outcome: { Applied: false, Method: 'none', Reason: reason } };
8
+ }
3
9
  /**
4
10
  * Handles server-side pagination for query SQL by applying platform-specific
5
11
  * paging clauses.
6
12
  *
7
- * **Data SQL** — appends OFFSET/FETCH (SQL Server) or LIMIT/OFFSET (PostgreSQL)
8
- * directly to the original SQL. The query is not wrapped in a CTE, so all column
9
- * scopes, ORDER BY references, and table aliases remain valid. TOP is stripped on
10
- * SQL Server since it conflicts with OFFSET.
13
+ * The statement is read from tokens ({@link AnalyzePagingShape}), so paging works the same way
14
+ * on SQL the AST parser cannot read, and the query's own text is kept as written: nothing is
15
+ * re-emitted from a syntax tree.
16
+ *
17
+ * **The query's own row cap is part of what it means.** `StartRow` and `MaxRows` page within the
18
+ * capped result, so the smaller of the query's cap and `MaxRows` wins, and the total row count is
19
+ * the size of the capped result. A numeric cap (`TOP n`, `LIMIT n [OFFSET k]`, `OFFSET k … FETCH
20
+ * NEXT n`) is replaced by the page's own clause with the arithmetic folded in; a page past the
21
+ * cap is an empty result. Any other cap (`TOP … PERCENT`, `WITH TIES`, an expression) is kept, and
22
+ * the query is paged as a derived table.
23
+ *
24
+ * **Data SQL** — appends OFFSET/FETCH (SQL Server) or LIMIT/OFFSET (PostgreSQL) to the
25
+ * statement, after its ORDER BY (a default one is added when it has none) and before any clause
26
+ * that must stay last (`OPTION (…)`, `FOR UPDATE`). Column scopes, ORDER BY references and table
27
+ * aliases stay valid because the query is not wrapped.
11
28
  *
12
- * **Count SQL** — wraps the original SQL (minus ORDER BY) in a CTE and produces
13
- * `SELECT COUNT(*) AS TotalRowCount FROM [__count]`. ORDER BY is irrelevant for
14
- * counting and must be removed since SQL Server forbids it in CTEs without TOP.
29
+ * **Count SQL** — puts the query (without its ORDER BY, unless its own cap needs it) in a
30
+ * `[__count]` CTE beside the query's own CTEs and selects `COUNT(*) AS TotalRowCount`.
15
31
  *
16
- * This approach eliminates the need for ORDER BY remapping (mapping column
17
- * references from the inner query scope to the outer CTE scope), which was the
18
- * primary source of paging bugs.
32
+ * A query that ends in `FOR JSON` / `FOR XML` returns a document, not rows, and cannot be paged;
33
+ * asking to page one is an error.
19
34
  */
20
35
  export class QueryPagingEngine {
21
36
  /**
@@ -28,198 +43,190 @@ export class QueryPagingEngine {
28
43
  * @returns DataSQL for paged results and CountSQL for total row count
29
44
  */
30
45
  static WrapWithPaging(resolvedSQL, startRow, maxRows, platform) {
31
- const cleanedSQL = resolvedSQL.trimEnd().replace(/;\s*$/, '');
46
+ const cleanedSQL = QueryPagingEngine.stripTrailingSemicolons(resolvedSQL);
32
47
  const dialect = QueryPagingEngine.getDialect(platform);
33
- const dataSQL = QueryPagingEngine.buildDataSQL(cleanedSQL, startRow, maxRows, dialect);
34
- const countSQL = QueryPagingEngine.buildCountSQL(cleanedSQL, dialect);
48
+ const shape = AnalyzePagingShape(cleanedSQL, dialect);
49
+ if (shape.ReturnsDocument) {
50
+ throw new Error(`QueryPagingEngine: this query ends in FOR ${shape.ReturnsDocument.toUpperCase()}, so it returns a document ` +
51
+ 'rather than rows and cannot be paged. Run it without StartRow / MaxRows.');
52
+ }
53
+ const dataSQL = QueryPagingEngine.buildDataSQL(shape, startRow, maxRows, dialect);
54
+ const countSQL = QueryPagingEngine.buildCountSQL(shape, dialect);
35
55
  return { DataSQL: dataSQL, CountSQL: countSQL, Offset: startRow, PageSize: maxRows };
36
56
  }
37
57
  /**
38
- * Applies a row cap to the outermost SELECT.
58
+ * Applies a row cap to the outermost SELECT: the result returns at most `maxRows` rows.
39
59
  *
40
- * `maxRows` is treated as a hard ceiling: the result is guaranteed to
41
- * return at most `maxRows` rows whenever the SQL shape can be capped
42
- * without corrupting the query.
60
+ * The statement is edited in place, from tokens, so the caller's SQL is kept exactly as
61
+ * written apart from the cap, and SQL the AST parser cannot read is capped the same way:
62
+ * - No cap of its own: `TOP n` goes after `SELECT [ALL | DISTINCT]` on SQL Server, and
63
+ * `LIMIT n` at the end on PostgreSQL. A SQL Server set operation (which has no single
64
+ * SELECT to put TOP on) gets `OFFSET 0 ROWS FETCH NEXT n ROWS ONLY` after its ORDER BY.
65
+ * - A numeric cap of its own: the tighter of the two wins.
66
+ * - Any other cap of its own (`TOP … PERCENT`, `WITH TIES`, an expression, caps on more than
67
+ * one branch): the statement is capped as a derived table.
68
+ * Clauses that must stay last (`OPTION (…)`, `FOR UPDATE`) stay last.
43
69
  *
44
- * Strategy:
45
- * 1. Parse via AST. If the outermost SELECT has no existing cap,
46
- * inject `TOP N` (SQL Server) or `LIMIT N` (PostgreSQL).
47
- * 2. If an existing numeric `TOP`/`LIMIT` is present, reduce it to
48
- * `min(existing, maxRows)`. The tighter cap wins.
49
- * 3. If the AST recognizes the shape but can't inject (`TOP PERCENT`,
50
- * non-numeric `TOP`, `UNION`, `WITH TIES`, etc.), wrap with an
51
- * outer `SELECT TOP N * FROM (…) AS _mj_capped` (or LIMIT on PG).
52
- * 4. If the parser can't handle the input but the SQL is CTE-headed,
53
- * append `OFFSET 0 ROWS FETCH NEXT N ROWS ONLY` via {@link buildDataSQL}.
54
- * 5. Shapes that can't legally appear inside a derived table
55
- * (`FOR JSON`, `FOR XML`, `OPTION (...)`, `SELECT INTO`,
56
- * mutations) are returned unchanged — the cap is moot
57
- * (FOR JSON/XML return one row) or the validator should have
58
- * rejected them earlier (mutations, SELECT INTO).
70
+ * A statement that ends in `FOR JSON` / `FOR XML` returns one document built from its rows;
71
+ * it is capped in place (bounding the rows the document is built from) and left unchanged
72
+ * where only a derived table or a set-operation clause could cap it. Anything that is not a
73
+ * single read query (a write, `SELECT … INTO`) is left unchanged; the render pipeline refuses
74
+ * those before this point anyway.
59
75
  *
60
- * Non-positive, non-finite, or fractional `maxRows` are sanitized
61
- * (`<= 0` and non-finite are no-ops; fractional values are floored).
76
+ * Non-positive, non-finite, or fractional `maxRows` are sanitized (`<= 0` and non-finite are
77
+ * no-ops; fractional values are floored).
62
78
  */
63
79
  static WrapWithMaxRows(resolvedSQL, maxRows, platform) {
64
- const cleanedSQL = resolvedSQL.trimEnd().replace(/;\s*$/, '');
80
+ return QueryPagingEngine.ApplyMaxRows(resolvedSQL, maxRows, platform).SQL;
81
+ }
82
+ /**
83
+ * Applies a row cap exactly as {@link WrapWithMaxRows} does, and also reports whether the cap
84
+ * holds and how, so a caller that asked for a cap can tell whether it got one.
85
+ */
86
+ static ApplyMaxRows(resolvedSQL, maxRows, platform) {
87
+ const cleanedSQL = QueryPagingEngine.stripTrailingSemicolons(resolvedSQL);
65
88
  if (!Number.isFinite(maxRows) || maxRows <= 0)
66
- return cleanedSQL;
89
+ return notCapped(cleanedSQL, 'MaxRows is not a positive number');
67
90
  if (cleanedSQL.trim().length === 0)
68
- return cleanedSQL;
91
+ return notCapped(cleanedSQL, 'the statement is empty');
69
92
  const cap = Math.floor(maxRows);
70
93
  const dialect = QueryPagingEngine.getDialect(platform);
71
- const astResult = QueryPagingEngine.applyMaxRowsViaAST(cleanedSQL, cap, dialect);
72
- if (astResult.outcome === 'capped')
73
- return astResult.sql;
74
- if (astResult.outcome === 'pass-through')
75
- return cleanedSQL;
76
- // Both `wrap` and `unparseable` outcomes may try the outer-wrap path.
77
- // First, check for clauses that cannot legally appear inside a derived
78
- // table — wrapping such queries would produce invalid SQL.
79
- const unwrappable = SQLParser.HasUnwrappableTrailingClause(cleanedSQL, dialect);
80
- if (astResult.outcome === 'wrap') {
81
- if (unwrappable)
82
- return cleanedSQL;
83
- return QueryPagingEngine.outerWrap(cleanedSQL, cap, dialect);
84
- }
85
- // unparseable — try the CTE-fallback path first.
86
- const isCTE = SQLParser.ExtractCTEs(cleanedSQL, dialect) !== null;
87
- if (isCTE) {
88
- try {
89
- return QueryPagingEngine.buildDataSQL(cleanedSQL, 0, cap, dialect);
90
- }
91
- catch {
92
- return cleanedSQL;
94
+ const readCheck = IsReadOnlyQuery(cleanedSQL, dialect);
95
+ if (!readCheck.IsReadOnly)
96
+ return notCapped(cleanedSQL, `the statement is not a single read query: ${readCheck.Reason}`);
97
+ const shape = AnalyzePagingShape(cleanedSQL, dialect);
98
+ const caps = shape.OwnCaps;
99
+ if (caps.length === 0)
100
+ return QueryPagingEngine.addCap(shape, cap, dialect);
101
+ if (caps.length === 1 && caps[0].Numeric)
102
+ return QueryPagingEngine.tightenCap(shape, caps[0], cap, dialect);
103
+ return QueryPagingEngine.capAsDerivedTable(shape, cap, dialect);
104
+ }
105
+ /** Caps a statement that has no cap of its own. */
106
+ static addCap(shape, cap, dialect) {
107
+ const limit = dialect.LimitClause(cap);
108
+ if (limit.prefix) {
109
+ if (shape.IsSetOperation && shape.ReturnsDocument) {
110
+ return notCapped(shape.Statement, `a set operation that ends in FOR ${shape.ReturnsDocument.toUpperCase()} returns one document and has no single SELECT to cap`);
93
111
  }
112
+ if (shape.IsSetOperation)
113
+ return capped(QueryPagingEngine.appendPage(shape, QueryPagingEngine.head(shape), 0, cap, dialect), 'fetch');
114
+ if (shape.SelectListStart === null)
115
+ return QueryPagingEngine.capAsDerivedTable(shape, cap, dialect);
116
+ const at = shape.SelectListStart;
117
+ return capped(`${shape.Statement.substring(0, at)} ${limit.prefix}${shape.Statement.substring(at)}`, 'top');
118
+ }
119
+ return capped(`${QueryPagingEngine.head(shape)}\n${limit.suffix}${QueryPagingEngine.tail(shape)}`, 'limit');
120
+ }
121
+ /** Lowers a numeric cap of the query's own to `cap`, or leaves it when it is already tighter. */
122
+ static tightenCap(shape, own, cap, dialect) {
123
+ if (own.Rows !== null && own.Rows <= cap)
124
+ return capped(shape.Statement, 'own-cap');
125
+ const statement = shape.Statement;
126
+ if (own.Form === 'top') {
127
+ return capped(`${statement.substring(0, own.Start)}${dialect.LimitClause(cap).prefix}${statement.substring(own.End)}`, 'top');
94
128
  }
95
- if (unwrappable)
96
- return cleanedSQL;
97
- return QueryPagingEngine.outerWrap(cleanedSQL, cap, dialect);
129
+ const limit = dialect.LimitClause(cap, own.Skip);
130
+ return capped(`${statement.substring(0, own.Start)}${limit.suffix}${QueryPagingEngine.tail(shape)}`, QueryPagingEngine.suffixMethod(limit.suffix));
131
+ }
132
+ /** How a row-limit suffix from the dialect's `LimitClause` caps rows: `FETCH` or `LIMIT`. */
133
+ static suffixMethod(suffix) {
134
+ return /\bFETCH\b/i.test(suffix) ? 'fetch' : 'limit';
98
135
  }
99
136
  /**
100
- * Wraps `sql` in an outer SELECT that enforces the row cap.
101
- * Used when the AST recognises the shape but cannot inject the cap
102
- * cleanly, or when the AST can't parse the input but the SQL is known
103
- * to be wrap-safe (no FOR JSON/FOR XML/OPTION at top level).
104
- *
105
- * Strips any top-level ORDER BY before wrapping: ORDER BY is illegal
106
- * inside a derived table on SQL Server (unless TOP/OFFSET/FOR XML is
107
- * present), and the outer SELECT doesn't preserve inner ordering anyway.
108
- * The ORDER BY is moved to the outer SELECT so the final result retains
109
- * the intended sort order.
137
+ * Caps the statement as a derived table, for shapes that cannot be capped in place. The
138
+ * query's CTEs stay in front and its trailing clause stays last. Its ORDER BY stays inside,
139
+ * where SQL Server allows it beside the query's own TOP; a set operation's ORDER BY is
140
+ * repeated outside (see {@link derivedTableParts}).
110
141
  */
111
- static outerWrap(sql, cap, dialect) {
112
- // Route the cap form through the dialect's LimitClause so there is a
113
- // single source of truth for "TOP vs LIMIT" — no PlatformKey probe here.
114
- const lc = dialect.LimitClause(cap);
115
- const prefix = lc.prefix ? `${lc.prefix} ` : ''; // 'TOP N ' (SQL Server) or ''
116
- const suffix = lc.suffix ? ` ${lc.suffix}` : ''; // ' LIMIT N' (PostgreSQL) or ''
117
- // Strip top-level ORDER BY from the inner SQL to avoid SQL Server error:
118
- // "The ORDER BY clause is invalid in views, inline functions, derived tables,
119
- // subqueries, and common table expressions, unless TOP, OFFSET or FOR XML
120
- // is also specified."
121
- // Uses the lexer-based Tier 2 scanner which handles unparseable SQL
122
- // (TRY_CAST, IIF, STRING_AGG, etc.) that the AST path cannot parse.
123
- const orderByAnalysis = AnalyzeTopLevelOrderBy(sql, dialect);
124
- const innerSQL = orderByAnalysis.OrderByClause && !orderByAnalysis.IsLegalInCTE
125
- ? orderByAnalysis.SqlWithoutOrderBy
126
- : sql;
127
- const outerOrderBy = orderByAnalysis.OrderByClause && !orderByAnalysis.IsLegalInCTE
128
- ? `\nORDER BY ${orderByAnalysis.OrderByClause}`
129
- : '';
130
- return `SELECT ${prefix}* FROM (\n${innerSQL}\n) AS _mj_capped${suffix}${outerOrderBy}`;
142
+ static capAsDerivedTable(shape, cap, dialect) {
143
+ const statement = shape.Statement;
144
+ if (shape.ReturnsDocument) {
145
+ return notCapped(statement, `the statement ends in FOR ${shape.ReturnsDocument.toUpperCase()}, which cannot appear inside a derived table`);
146
+ }
147
+ const prefix = statement.substring(0, shape.MainStart);
148
+ const { Inner: inner, OuterOrderBy: outerOrderBy } = QueryPagingEngine.derivedTableParts(shape, dialect);
149
+ const orderBy = outerOrderBy ? `\n${outerOrderBy}` : '';
150
+ const limit = dialect.LimitClause(cap);
151
+ const top = limit.prefix ? `${limit.prefix} ` : '';
152
+ const suffix = limit.suffix ? `\n${limit.suffix}` : '';
153
+ const sql = `${prefix}SELECT ${top}* FROM (\n${inner}\n) AS ${dialect.QuoteIdentifier('_mj_capped')}${orderBy}${suffix}${QueryPagingEngine.tail(shape)}`;
154
+ return capped(sql, 'derived-table');
131
155
  }
132
156
  /**
133
- * AST-based row-cap injection.
134
- * `capped` — `sql` contains the input with TOP/LIMIT injected
135
- * or reduced to `min(existing, cap)`.
136
- * `wrap` — AST recognized the shape but the cap can't be
137
- * safely injected inline (`TOP PERCENT`, non-numeric
138
- * `TOP`/`LIMIT`); caller should outer-wrap.
139
- * `pass-through` — shape can't be capped at all without corrupting
140
- * the query (SELECT INTO, mutation).
141
- * `unparseable` — parser could not handle the input; caller may
142
- * attempt a CTE-fallback or outer wrap.
157
+ * Splits the main statement into the body of a derived table and the ORDER BY to put outside it.
143
158
  *
144
- * All AST shape inspection is delegated to {@link SQLParser} primitives —
145
- * this method contains no `node-sql-parser` field knowledge.
159
+ * Only a set operation's ORDER BY goes outside: it orders the combined result, which a derived
160
+ * table does not preserve. Outside, the set operation's table aliases are out of scope, so its
161
+ * column references lose their qualifiers (`a.Name` → `Name`) and name the derived table's
162
+ * output columns instead.
163
+ *
164
+ * The ORDER BY is cut from the inside, where SQL Server rejects it. When the set operation also
165
+ * has its own `OFFSET … FETCH` / `LIMIT` after that ORDER BY, that cap still has to pick the
166
+ * rows, so the inside becomes a second derived table that applies it with the same, unqualified,
167
+ * ORDER BY. Keeping the set operation's own text there instead would put its branches' `TOP`
168
+ * and its `OFFSET` in one subquery, which SQL Server refuses even though it accepts them as a
169
+ * whole statement.
146
170
  */
147
- static applyMaxRowsViaAST(sql, cap, dialect) {
148
- // The instance parser applies preprocessing fallbacks on a direct-parse
149
- // failure (bracket-identifier aliasing for Skip-style CTE names, trailing
150
- // OPTION splitting); ToSQL restores them. This widens the set of shapes
151
- // that reach the precise AST-inject path instead of the outer-wrap path.
152
- const parsed = new SQLParser(sql, dialect);
153
- if (!parsed.IsValid)
154
- return { outcome: 'unparseable' };
155
- const kind = parsed.StatementKind;
156
- if (kind === 'mutation' || kind === 'select-into')
157
- return { outcome: 'pass-through' };
158
- if (kind === 'set-op')
159
- return { outcome: 'unparseable' };
160
- if (kind !== 'select')
161
- return { outcome: 'pass-through' };
162
- const existing = parsed.OuterCap;
163
- // PERCENT and non-numeric (opaque) caps can't be reasoned about as row
164
- // counts; let the caller outer-wrap them.
165
- if (existing && existing.form !== 'numeric')
166
- return { outcome: 'wrap' };
167
- // Existing numeric cap — only modify when the requested cap is tighter.
168
- if (existing && existing.value <= cap)
169
- return { outcome: 'capped', sql };
170
- // No cap at all, on a dialect that caps with a trailing clause — append it as TEXT.
171
- //
172
- // `SetOuterCap` + `ToSQL()` below re-emits the WHOLE statement from the AST, and
173
- // node-sql-parser normalizes as it generates: keywords come back upper-cased and
174
- // identifiers re-quoted. Appending one clause should not rewrite the caller's SQL, and
175
- // on PostgreSQL that rewrite is not cosmetic — it is a correctness bug, because the
176
- // provider's identifier auto-quoter runs afterwards over an upper-cased statement and
177
- // quotes any keyword its allowlist is missing. A query written `ORDER BY x ASC nulls
178
- // last` came back `ASC NULLS LAST`, was quoted to `ASC "NULLS" "LAST"`, and failed with
179
- // `syntax error at or near ""NULLS""` — SQL the caller never wrote.
180
- //
181
- // The append is only taken where it is provably equivalent to the AST injection; every
182
- // other shape falls through to the existing path, so this can narrow the blast radius
183
- // but never change a result.
184
- if (!existing) {
185
- const appended = QueryPagingEngine.appendTrailingCap(sql, cap, dialect);
186
- if (appended)
187
- return { outcome: 'capped', sql: appended };
188
- }
189
- // No cap (or a looser one) — inject/replace.
190
- parsed.SetOuterCap(cap);
191
- try {
192
- return { outcome: 'capped', sql: parsed.ToSQL() };
193
- }
194
- catch {
195
- return { outcome: 'unparseable' };
171
+ static derivedTableParts(shape, dialect) {
172
+ const statement = shape.Statement;
173
+ const orderBy = shape.IsSetOperation ? shape.OrderBy : null;
174
+ if (!orderBy) {
175
+ return { Inner: statement.substring(shape.MainStart, shape.TailStart).trim(), OuterOrderBy: '' };
196
176
  }
177
+ const body = statement.substring(shape.MainStart, orderBy.Start).trim();
178
+ const outerOrderBy = QueryPagingEngine.unqualifyColumnReferences(statement.substring(orderBy.Start, orderBy.End).trim(), dialect);
179
+ const ownClauseCap = statement.substring(orderBy.End, shape.TailStart).trim();
180
+ const inner = ownClauseCap
181
+ ? `SELECT * FROM (\n${body}\n) AS ${dialect.QuoteIdentifier('_mj_set')}\n${outerOrderBy}\n${ownClauseCap}`
182
+ : body;
183
+ return { Inner: inner, OuterOrderBy: outerOrderBy };
197
184
  }
198
185
  /**
199
- * Clauses that must come AFTER `LIMIT` in PostgreSQL, so a bare append would be illegal.
200
- *
201
- * Matched loosely and deliberately: a false positive (the word inside a string literal, a
202
- * column alias, or a nested subquery) costs only a fall-through to the AST path, which is
203
- * the behaviour that shipped before. A false negative would emit invalid SQL, so the test
204
- * errs heavily toward abstaining.
186
+ * Drops the table or schema qualifier from every dotted column name in `sql`, keeping its last
187
+ * part: `a.Name` → `Name`, `[dbo].[A].[Name]` → `[Name]`. A dotted name followed by `(` is a
188
+ * function call such as `dbo.fnLen(Name)`, whose schema SQL Server requires, so it is kept.
189
+ * Whitespace, comments and every other token are kept as written.
205
190
  */
206
- static { this.CLAUSES_THAT_FOLLOW_LIMIT = /\b(?:OFFSET|FETCH|FOR\s+(?:UPDATE|SHARE|NO\s+KEY\s+UPDATE|KEY\s+SHARE))\b/i; }
191
+ static unqualifyColumnReferences(sql, dialect) {
192
+ const tokens = LexSQL(sql, dialect);
193
+ let result = '';
194
+ let i = 0;
195
+ while (i < tokens.length) {
196
+ const end = QueryPagingEngine.dottedNameEnd(tokens, i);
197
+ if (end > i && !QueryPagingEngine.isFollowedByOpenParen(tokens, end)) {
198
+ result += tokens[end - 1].Text;
199
+ }
200
+ else {
201
+ for (let k = i; k < Math.max(end, i + 1); k++)
202
+ result += tokens[k].Text;
203
+ }
204
+ i = Math.max(end, i + 1);
205
+ }
206
+ return result;
207
+ }
207
208
  /**
208
- * Returns `sql` with the row cap appended as a trailing clause, or `null` when that is not
209
- * provably safe and the caller should fall back to AST injection.
210
- *
211
- * Applies only to dialects whose cap is a suffix (`LIMIT N`). SQL Server caps with a `TOP N`
212
- * prefix that has to go between `SELECT` and the select list — a position no append can
213
- * reach — so it is left to the AST path, where the round-trip is harmless anyway because
214
- * T-SQL is not case-sensitive about the identifiers involved.
209
+ * The index just past the dotted name (`part.part[.part…]`) that starts at `start`, or `start`
210
+ * when no name of two or more parts starts there.
215
211
  */
216
- static appendTrailingCap(sql, cap, dialect) {
217
- const limit = dialect.LimitClause(cap);
218
- if (!limit.suffix || limit.prefix)
219
- return null;
220
- if (QueryPagingEngine.CLAUSES_THAT_FOLLOW_LIMIT.test(sql))
221
- return null;
222
- return `${sql}\n${limit.suffix}`;
212
+ static dottedNameEnd(tokens, start) {
213
+ if (!QueryPagingEngine.isNamePart(tokens[start]))
214
+ return start;
215
+ let end = start + 1;
216
+ while (tokens[end]?.Kind === 'dot' && QueryPagingEngine.isNamePart(tokens[end + 1]))
217
+ end += 2;
218
+ return end > start + 1 ? end : start;
219
+ }
220
+ /** Whether the next token at or after `index`, other than whitespace and comments, opens a parenthesis. */
221
+ static isFollowedByOpenParen(tokens, index) {
222
+ let k = index;
223
+ while (tokens[k]?.Kind === 'whitespace' || tokens[k]?.Kind === 'comment')
224
+ k++;
225
+ return tokens[k]?.Kind === 'open';
226
+ }
227
+ /** Whether a token can be one part of a dotted name: a bare word or a quoted identifier. */
228
+ static isNamePart(token) {
229
+ return token?.Kind === 'word' || token?.Kind === 'identifier';
223
230
  }
224
231
  /**
225
232
  * Determines whether the given params indicate paging should be applied.
@@ -248,87 +255,139 @@ export class QueryPagingEngine {
248
255
  return startRow != null && startRow >= 0 ? startRow : 0;
249
256
  }
250
257
  // ════════════════════════════════════════════════════════════════════
251
- // Data SQL — append paging clause directly to original SQL
258
+ // Data SQL
252
259
  // ════════════════════════════════════════════════════════════════════
253
- static buildDataSQL(sql, startRow, maxRows, dialect) {
254
- let dataSQL = sql;
255
- // Strip TOP clause on SQL Server — it conflicts with OFFSET/FETCH.
256
- if (dialect.PlatformKey === 'sqlserver') {
257
- dataSQL = QueryPagingEngine.stripTopFromMainSelect(dataSQL, dialect);
260
+ /** Removes trailing semicolons and whitespace; a statement-ending `;` cannot precede a paging clause. */
261
+ static stripTrailingSemicolons(sql) {
262
+ // A loop from the end rather than a `[\s;]+$` regex, which backtracks on long whitespace runs.
263
+ let end = sql.length;
264
+ while (end > 0 && (sql[end - 1] === ';' || /\s/.test(sql[end - 1])))
265
+ end--;
266
+ return sql.substring(0, end);
267
+ }
268
+ /**
269
+ * Builds the SQL for one page. A query without a cap of its own gets the paging clause
270
+ * appended; a single numeric cap is replaced by the page's clause with the arithmetic folded
271
+ * in; anything else is paged as a derived table.
272
+ */
273
+ static buildDataSQL(shape, startRow, maxRows, dialect) {
274
+ const caps = shape.OwnCaps;
275
+ if (caps.length === 0) {
276
+ return QueryPagingEngine.appendPage(shape, QueryPagingEngine.head(shape), startRow, maxRows, dialect);
258
277
  }
259
- // Ensure there's an ORDER BY — required for OFFSET/FETCH on SQL Server,
260
- // and strongly recommended for deterministic LIMIT/OFFSET on PostgreSQL.
261
- const hasOrderBy = AnalyzeTopLevelOrderBy(dataSQL, dialect).Positions.length > 0;
262
- if (!hasOrderBy) {
263
- dataSQL = `${dataSQL}\nORDER BY ${dialect.DefaultPagingOrderBy}`;
278
+ if (caps.length === 1 && caps[0].Numeric) {
279
+ return QueryPagingEngine.pageWithinCap(shape, caps[0], startRow, maxRows, dialect);
264
280
  }
265
- // Append paging clause via dialect
266
- const limitResult = dialect.LimitClause(maxRows, startRow);
267
- return `${dataSQL}\n${limitResult.suffix}`;
281
+ return QueryPagingEngine.wrapAndPage(shape, startRow, maxRows, dialect);
282
+ }
283
+ /** The statement up to the clause that must stay last. */
284
+ static head(shape) {
285
+ return shape.Statement.substring(0, shape.TailStart).trimEnd();
286
+ }
287
+ /** The clause that must stay last (`OPTION (…)`, `FOR UPDATE`), with its leading newline, or ''. */
288
+ static tail(shape) {
289
+ const tail = shape.Statement.substring(shape.TailStart).trim();
290
+ return tail ? `\n${tail}` : '';
291
+ }
292
+ /** Appends ORDER BY (when the statement has none), the paging clause and the trailing clause. */
293
+ static appendPage(shape, head, offset, rows, dialect) {
294
+ const orderBy = shape.OrderBy ? '' : `\nORDER BY ${QueryPagingEngine.defaultOrderBy(shape, dialect)}`;
295
+ const limit = dialect.LimitClause(rows, offset);
296
+ return `${head}${orderBy}\n${limit.suffix}${QueryPagingEngine.tail(shape)}`;
268
297
  }
269
298
  /**
270
- * Strips a TOP clause from the outermost SELECT statement.
271
- * Handles `TOP N` and `TOP (N)`, with or without DISTINCT.
272
- * Does not affect TOP in subqueries or CTEs.
299
+ * The ORDER BY to page by when the statement has none: the dialect's
300
+ * {@link SQLDialect.SelectListPagingOrderBy} for a set operation or SELECT DISTINCT when it
301
+ * has one (a platform that only accepts select-list items there), otherwise its
302
+ * {@link SQLDialect.DefaultPagingOrderBy}.
273
303
  */
274
- static stripTopFromMainSelect(sql, dialect) {
275
- const extraction = SQLParser.ExtractCTEs(sql, dialect);
276
- if (extraction) {
277
- const { sql: cleanMain, topRemoved } = QueryPagingEngine.stripTopClause(extraction.MainStatement);
278
- if (topRemoved) {
279
- const ctePrefix = sql.substring(0, sql.length - extraction.MainStatement.length).trimEnd();
280
- return `${ctePrefix}\n${cleanMain}`;
281
- }
282
- return sql;
283
- }
284
- const { sql: cleanSQL } = QueryPagingEngine.stripTopClause(sql);
285
- return cleanSQL;
304
+ static defaultOrderBy(shape, dialect) {
305
+ const selectListOrderBy = dialect.SelectListPagingOrderBy;
306
+ if (selectListOrderBy !== null && (shape.IsSetOperation || shape.IsDistinct))
307
+ return selectListOrderBy;
308
+ return dialect.DefaultPagingOrderBy;
309
+ }
310
+ /**
311
+ * Pages within a numeric cap of the query's own: the page starts `startRow` rows into the
312
+ * capped result and stops at the cap. A page that starts at or past the cap is empty.
313
+ */
314
+ static pageWithinCap(shape, cap, startRow, maxRows, dialect) {
315
+ const remaining = cap.Rows === null ? maxRows : cap.Rows - startRow;
316
+ const rows = Math.min(maxRows, remaining);
317
+ if (rows <= 0)
318
+ return QueryPagingEngine.emptyResultSQL(dialect);
319
+ const statement = shape.Statement;
320
+ const capEnd = cap.Form === 'top' ? cap.End : shape.TailStart;
321
+ const head = (statement.substring(0, cap.Start) + statement.substring(capEnd, shape.TailStart)).trimEnd();
322
+ return QueryPagingEngine.appendPage(shape, head, cap.Skip + startRow, rows, dialect);
323
+ }
324
+ /**
325
+ * Pages a query whose own cap cannot be reasoned about as a row count (`TOP … PERCENT`, `WITH
326
+ * TIES`, an expression, or a cap on more than one branch of a set operation) by selecting the
327
+ * page from it as a derived table. Its CTEs stay in front, its trailing clause stays last, and
328
+ * the ORDER BY of a set operation is repeated outside (see {@link derivedTableParts}).
329
+ */
330
+ static wrapAndPage(shape, startRow, maxRows, dialect) {
331
+ const statement = shape.Statement;
332
+ const prefix = statement.substring(0, shape.MainStart);
333
+ const { Inner: inner, OuterOrderBy: outerOrderBy } = QueryPagingEngine.derivedTableParts(shape, dialect);
334
+ const orderBy = outerOrderBy
335
+ || (dialect.PagingRequiresOrderBy ? `ORDER BY ${dialect.DefaultPagingOrderBy}` : '');
336
+ const limit = dialect.LimitClause(maxRows, startRow);
337
+ const page = `SELECT * FROM (\n${inner}\n) AS ${dialect.QuoteIdentifier('__mj_page')}${orderBy ? `\n${orderBy}` : ''}\n${limit.suffix}`;
338
+ return `${prefix}${page}${QueryPagingEngine.tail(shape)}`;
339
+ }
340
+ /** A statement that returns no rows, for a page that starts past the query's own cap. */
341
+ static emptyResultSQL(dialect) {
342
+ return `SELECT NULL AS ${dialect.QuoteIdentifier('__mj_empty')} WHERE 1 = 0`;
286
343
  }
287
344
  // ════════════════════════════════════════════════════════════════════
288
- // Count SQL — wrap in CTE, strip ORDER BY, SELECT COUNT(*)
345
+ // Count SQL
289
346
  // ════════════════════════════════════════════════════════════════════
290
347
  /**
291
- * Builds count SQL that wraps the (cap-free, ORDER-BY-free) query in a
292
- * `[__count]` CTE and selects `COUNT(*)`. A single instance-API path:
293
- * 1. `ExtractCTEs` hoists any user CTEs as siblings (a CTE body can't
294
- * contain its own WITH) — AST parse first, paren-depth regex fallback.
295
- * 2. `stripCountBody` removes the top-level ORDER BY (irrelevant for a
296
- * count, and illegal in a SQL Server CTE without TOP) and any outer
297
- * TOP / LIMIT (so the count reflects the full set, consistent with the
298
- * paged data query).
348
+ * Builds the count query: the main statement in a `[__count]` CTE placed after the query's
349
+ * own CTEs (a CTE body cannot contain its own WITH), and `SELECT COUNT(*) AS TotalRowCount`.
350
+ * The ORDER BY is removed — it does not change a count, and SQL Server forbids it in a CTE —
351
+ * unless the query's own cap needs it to choose its rows. A trailing `OPTION (…)` stays last.
299
352
  */
300
- static buildCountSQL(sql, dialect) {
353
+ static buildCountSQL(shape, dialect) {
301
354
  const countCTEName = dialect.QuoteIdentifier('__count');
302
- const extraction = SQLParser.ExtractCTEs(sql, dialect);
303
- const mainStatement = extraction ? extraction.MainStatement : sql;
304
- const cteDefs = extraction
305
- ? extraction.CTEDefinitions.map(def => QueryPagingEngine.quoteCteName(def, dialect))
306
- : [];
307
- const countBody = QueryPagingEngine.stripCountBody(mainStatement, dialect);
308
- const allCTEs = [...cteDefs, `${countCTEName} AS (\n${countBody}\n)`];
309
- return `WITH ${allCTEs.join(',\n')}\nSELECT COUNT(*) AS TotalRowCount FROM ${countCTEName}`;
355
+ const body = QueryPagingEngine.countBody(shape, dialect);
356
+ const ownCTEs = shape.CTEs ? shape.CTEs.Definitions.map(d => d.Text) : [];
357
+ const recursive = shape.CTEs?.Recursive ? 'RECURSIVE ' : '';
358
+ const allCTEs = [...ownCTEs, `${countCTEName} AS (\n${body}\n)`];
359
+ const hint = /^OPTION\b/i.test(shape.Statement.substring(shape.TailStart).trim()) ? QueryPagingEngine.tail(shape) : '';
360
+ return `WITH ${recursive}${allCTEs.join(',\n')}\nSELECT COUNT(*) AS TotalRowCount FROM ${countCTEName}${hint}`;
310
361
  }
311
362
  /**
312
- * Strips the ORDER BY and any outer row cap (TOP on SQL Server, LIMIT on
313
- * PostgreSQL) from the statement being counted, via a single parser
314
- * round-trip — so the count reflects the full set rather than the capped
315
- * subset. Falls back to a string-based ORDER BY strip when the statement
316
- * can't be parsed (e.g. TRY_CAST, unresolved templates); the cap can't be
317
- * reliably removed without a parse, matching the prior regex behavior.
363
+ * The main statement as the count query sees it. With a cap of its own the statement is kept
364
+ * whole (its ORDER BY picks the capped rows, and is legal in a CTE beside TOP or OFFSET),
365
+ * except that a set operation's trailing ORDER BY is dropped; otherwise the ORDER BY is cut.
366
+ *
367
+ * A set operation with both branch `TOP`s and its own `OFFSET` / `LIMIT` cannot be kept whole:
368
+ * SQL Server refuses the two in one CTE. It is counted through the same second derived table
369
+ * the data query uses (see {@link derivedTableParts}).
318
370
  */
319
- static stripCountBody(sql, dialect) {
320
- const parser = new SQLParser(sql, dialect);
321
- if (parser.IsValid) {
322
- parser.ClearOuterCap();
323
- parser.ClearOrderBy();
324
- try {
325
- return parser.ToSQL();
326
- }
327
- catch {
328
- // fall through to the string-based fallback
329
- }
371
+ static countBody(shape, dialect) {
372
+ const statement = shape.Statement;
373
+ if (QueryPagingEngine.hasBranchTopAndOwnClauseCap(shape)) {
374
+ return QueryPagingEngine.derivedTableParts(shape, dialect).Inner;
330
375
  }
331
- return QueryPagingEngine.extractOrderBy(sql, dialect).sqlWithoutOrder;
376
+ const capped = shape.OwnCaps.length > 0;
377
+ const keepsOrderBy = capped && !(shape.IsSetOperation && shape.OwnCaps.every(c => c.Form === 'top'));
378
+ const end = shape.OrderBy && !keepsOrderBy ? shape.OrderBy.Start : shape.TailStart;
379
+ const body = statement.substring(shape.MainStart, end).trim();
380
+ if (shape.OrderBy && !keepsOrderBy && shape.OrderBy.End < shape.TailStart) {
381
+ // The query's own LIMIT / OFFSET clause follows the ORDER BY being cut; keep it.
382
+ return `${body} ${statement.substring(shape.OrderBy.End, shape.TailStart).trim()}`.trim();
383
+ }
384
+ return body;
385
+ }
386
+ /** Whether a set operation ordered by its own ORDER BY caps both its branches (`TOP`) and itself (`OFFSET` / `LIMIT`). */
387
+ static hasBranchTopAndOwnClauseCap(shape) {
388
+ return shape.IsSetOperation && shape.OrderBy !== null
389
+ && shape.OwnCaps.some(c => c.Form === 'top')
390
+ && shape.OwnCaps.some(c => c.Form === 'clause');
332
391
  }
333
392
  // ════════════════════════════════════════════════════════════════════
334
393
  // SQL analysis helpers — delegate to shared orderByAnalyzer
@@ -368,20 +427,6 @@ export class QueryPagingEngine {
368
427
  static stripTopClause(sql) {
369
428
  return this.StripTopClause(sql);
370
429
  }
371
- /**
372
- * ExtractCTEs returns CTE definitions with unquoted names (e.g. `myName AS (...)`).
373
- * Apply dialect-specific identifier quoting to the CTE name.
374
- */
375
- static quoteCteName(cteDefinition, dialect) {
376
- const match = cteDefinition.match(/^(\[([^\]]+)\]|"([^"]+)"|([A-Za-z_]\w*))\s+AS\s*\(/i);
377
- if (!match)
378
- return cteDefinition;
379
- const bareName = match[2] ?? match[3] ?? match[4];
380
- if (!bareName)
381
- return cteDefinition;
382
- const quotedName = dialect.QuoteIdentifier(bareName);
383
- return quotedName + cteDefinition.substring(match[1].length);
384
- }
385
430
  // ════════════════════════════════════════════════════════════════════
386
431
  // Dialect resolution
387
432
  // ════════════════════════════════════════════════════════════════════