@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.
- package/dist/GenericDatabaseProvider.d.ts +226 -36
- package/dist/GenericDatabaseProvider.d.ts.map +1 -1
- package/dist/GenericDatabaseProvider.js +542 -105
- package/dist/GenericDatabaseProvider.js.map +1 -1
- package/dist/SqlLogger.js +2 -2
- package/dist/SqlLogger.js.map +1 -1
- package/dist/TransactionAffinity.d.ts +73 -0
- package/dist/TransactionAffinity.d.ts.map +1 -0
- package/dist/TransactionAffinity.js +120 -0
- package/dist/TransactionAffinity.js.map +1 -0
- package/dist/UserCache.d.ts +277 -11
- package/dist/UserCache.d.ts.map +1 -1
- package/dist/UserCache.js +610 -23
- package/dist/UserCache.js.map +1 -1
- package/dist/countOnlyBatch.d.ts +79 -0
- package/dist/countOnlyBatch.d.ts.map +1 -0
- package/dist/countOnlyBatch.js +153 -0
- package/dist/countOnlyBatch.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/queryCompositionEngine.d.ts +45 -8
- package/dist/queryCompositionEngine.d.ts.map +1 -1
- package/dist/queryCompositionEngine.js +161 -36
- package/dist/queryCompositionEngine.js.map +1 -1
- package/dist/queryPagingEngine.d.ts +147 -95
- package/dist/queryPagingEngine.d.ts.map +1 -1
- package/dist/queryPagingEngine.js +299 -254
- package/dist/queryPagingEngine.js.map +1 -1
- package/dist/renderPipeline.d.ts +24 -1
- package/dist/renderPipeline.d.ts.map +1 -1
- package/dist/renderPipeline.js +33 -4
- package/dist/renderPipeline.js.map +1 -1
- package/package.json +14 -14
|
@@ -1,21 +1,36 @@
|
|
|
1
|
-
import {
|
|
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
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
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** —
|
|
13
|
-
* `
|
|
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
|
-
*
|
|
17
|
-
*
|
|
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 =
|
|
46
|
+
const cleanedSQL = QueryPagingEngine.stripTrailingSemicolons(resolvedSQL);
|
|
32
47
|
const dialect = QueryPagingEngine.getDialect(platform);
|
|
33
|
-
const
|
|
34
|
-
|
|
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
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
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
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
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
|
-
*
|
|
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
|
-
|
|
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
|
|
72
|
-
if (
|
|
73
|
-
return
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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
|
-
|
|
96
|
-
|
|
97
|
-
|
|
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
|
-
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
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
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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
|
-
*
|
|
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
|
-
*
|
|
145
|
-
*
|
|
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
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
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
|
-
*
|
|
200
|
-
*
|
|
201
|
-
*
|
|
202
|
-
*
|
|
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
|
|
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
|
-
*
|
|
209
|
-
*
|
|
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
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
return
|
|
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
|
|
258
|
+
// Data SQL
|
|
252
259
|
// ════════════════════════════════════════════════════════════════════
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
//
|
|
256
|
-
|
|
257
|
-
|
|
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
|
-
|
|
260
|
-
|
|
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
|
-
|
|
266
|
-
|
|
267
|
-
|
|
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
|
-
*
|
|
271
|
-
*
|
|
272
|
-
*
|
|
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
|
|
275
|
-
const
|
|
276
|
-
if (
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
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
|
|
345
|
+
// Count SQL
|
|
289
346
|
// ════════════════════════════════════════════════════════════════════
|
|
290
347
|
/**
|
|
291
|
-
* Builds count
|
|
292
|
-
*
|
|
293
|
-
*
|
|
294
|
-
*
|
|
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(
|
|
353
|
+
static buildCountSQL(shape, dialect) {
|
|
301
354
|
const countCTEName = dialect.QuoteIdentifier('__count');
|
|
302
|
-
const
|
|
303
|
-
const
|
|
304
|
-
const
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
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
|
-
*
|
|
313
|
-
*
|
|
314
|
-
*
|
|
315
|
-
*
|
|
316
|
-
*
|
|
317
|
-
*
|
|
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
|
|
320
|
-
const
|
|
321
|
-
if (
|
|
322
|
-
|
|
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
|
-
|
|
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
|
// ════════════════════════════════════════════════════════════════════
|