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

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,637 @@
1
+ import { CurrentFieldSecurityGeneration, EntityPermissionType, IsPlatformSQL } from '@memberjunction/core';
2
+ import { FindForbiddenFunctionCalls, IsKeyword, LexSQL, SignificantTokens, SQLParser } from '@memberjunction/sql-parser';
3
+ import { PostgreSQLDialect, SQLServerDialect } from '@memberjunction/sql-dialect';
4
+ /** True when `provider` can screen client SQL clauses. */
5
+ export function IsClientClauseScreeningProvider(provider) {
6
+ return !!provider && 'ScreenClientClause' in provider && typeof provider.ScreenClientClause === 'function';
7
+ }
8
+ /** Allow-lists already built, per entity array (see {@link ClientClauseScreen.BuildEntityBaseViewAllowList}). */
9
+ const allowListCache = new WeakMap();
10
+ /**
11
+ * SECURITY — screens for SQL text that a client (or a client-saved record) supplies to RunView.
12
+ *
13
+ * {@link ClientClauseScreen.AssertClauseUsesEntityBaseViews} is the full screen: one statement,
14
+ * parsed as a read-only fragment, that calls no function the dialect forbids in caller SQL and
15
+ * whose table references are only entity base views the acting user can read unscoped (no row
16
+ * filter and no denied fields). Base tables and system catalogs are refused. Apply it at every
17
+ * point where client text enters RunView: the GraphQL and REST entry points, ad-hoc list sources,
18
+ * and the clauses a saved view stores (at save and when the view runs).
19
+ *
20
+ * {@link ClientClauseScreen.AssertSingleStatementFragment} is the light check the provider runs on
21
+ * every RunView, server-internal ones included: no statement separator and no comment outside a
22
+ * literal or quoted identifier. It cannot refuse a legitimate fragment, so it is safe for callers
23
+ * whose filters the full screen would refuse (base tables, entities the acting user cannot read).
24
+ *
25
+ * Both use dialect-aware lexing, so a quote inside a bracket identifier (`[a']`) or a PostgreSQL
26
+ * `E'\''` string cannot hide a statement the way it hides one from the keyword denylist.
27
+ */
28
+ export class ClientClauseScreen {
29
+ /**
30
+ * Built-in table functions that read only their arguments. A subquery may use one in its FROM
31
+ * when the name is unqualified; a subquery inside its arguments is screened like any other.
32
+ */
33
+ static { this.ARGUMENT_ONLY_TABLE_FUNCTIONS = new Set([
34
+ 'string_split', 'openjson', 'generate_series', 'unnest', 'regexp_split_to_table', 'string_to_table',
35
+ 'json_array_elements', 'json_array_elements_text', 'jsonb_array_elements', 'jsonb_array_elements_text',
36
+ 'json_each', 'json_each_text', 'jsonb_each', 'jsonb_each_text',
37
+ ]); }
38
+ static { this.WRITE_NODE_TYPES = new Set([
39
+ 'insert', 'update', 'delete', 'merge', 'replace', 'drop', 'create', 'alter', 'truncate',
40
+ 'rename', 'call', 'exec', 'execute', 'grant', 'revoke', 'use', 'load', 'copy', 'do',
41
+ ]); }
42
+ /**
43
+ * The parser dialect for a provider: from its `PlatformKey` when it has one, otherwise from its
44
+ * class name. Defaults to SQL Server.
45
+ */
46
+ static DialectFor(provider) {
47
+ const platform = provider && 'PlatformKey' in provider && typeof provider.PlatformKey === 'string' ? provider.PlatformKey : undefined;
48
+ const name = platform ?? provider?.constructor?.name ?? '';
49
+ return /postgres/i.test(name) ? new PostgreSQLDialect() : new SQLServerDialect();
50
+ }
51
+ /**
52
+ * The full screen for one client clause fragment; throws when it refuses. The label `OrderBy`
53
+ * screens the text as an ORDER BY list; any other label screens it as a WHERE predicate. When
54
+ * `user` is given, every entity the fragment reads must be readable by that user, unscoped
55
+ * ({@link AssertUnscopedRead}). That includes the entity the clause filters: a subquery over
56
+ * its base view is outside the row filter RunView applies to the outer query.
57
+ *
58
+ * The reads come from a walk of the whole parse tree ({@link CollectStatementReads}), and the
59
+ * clause is refused when that walk does not account for every SELECT in the text
60
+ * ({@link AssertEverySelectAccountedFor}). Only the parse wrapper's own FROM item is skipped,
61
+ * and no CTE reference is exempt. A name reserved for the parser
62
+ * ({@link AssertNoIdentifierAliasNames}) and a call to a function the dialect forbids
63
+ * ({@link AssertNoForbiddenFunctionCalls}) are refused first.
64
+ *
65
+ * With `LeaveUnparseableToProvider`, text the parser cannot read returns without a refusal;
66
+ * the caller's own per-item check must refuse it instead.
67
+ */
68
+ static AssertClauseUsesEntityBaseViews(clause, label, entities, dialect, user, options) {
69
+ if (!clause?.trim())
70
+ return;
71
+ if (SQLParser.HasStackedStatements(clause, dialect)) {
72
+ throw new Error(`Invalid ${label}: multiple statements are not permitted in client-supplied filters`);
73
+ }
74
+ const fragment = ClientClauseScreen.toDialectQuoting(clause, dialect);
75
+ ClientClauseScreen.AssertNoIdentifierAliasNames(fragment, dialect, label);
76
+ ClientClauseScreen.AssertNoForbiddenFunctionCalls(fragment, dialect, label);
77
+ const wrapped = label === 'OrderBy'
78
+ ? `SELECT 1 FROM __mj_clause_screen ORDER BY ${fragment}`
79
+ : `SELECT 1 FROM __mj_clause_screen WHERE (${fragment})`;
80
+ const parser = new SQLParser(wrapped, dialect);
81
+ if (!parser.IsValid && options?.LeaveUnparseableToProvider)
82
+ return;
83
+ if (!parser.IsValid || parser.HasWriteStatement || parser.StatementKind !== 'select') {
84
+ throw new Error(`Invalid ${label}: not a safe read-only filter fragment — refusing under uncertainty`);
85
+ }
86
+ if (ClientClauseScreen.AstContainsWriteNode(parser.AST)) {
87
+ throw new Error(`Invalid ${label}: write/DDL nested in a subquery is not permitted`);
88
+ }
89
+ const reads = ClientClauseScreen.CollectStatementReads(parser, ClientClauseScreen.wrapperFromItem(parser.AST));
90
+ ClientClauseScreen.AssertEverySelectAccountedFor(wrapped, dialect, reads, label);
91
+ const allowed = ClientClauseScreen.BuildEntityBaseViewAllowList(entities);
92
+ for (const relation of reads.Relations) {
93
+ const entity = ClientClauseScreen.AssertRelationReadable(allowed, relation, label, user);
94
+ if (entity && user)
95
+ ClientClauseScreen.AssertUnscopedRead(entity, user, label);
96
+ }
97
+ }
98
+ /**
99
+ * Screens a full client-supplied SQL statement (ad-hoc query path) so every table reference
100
+ * resolves to an entity BaseView that `user` can read unscoped (CanRead, no row-level filter,
101
+ * no denied fields), with in-scope CTE references permitted.
102
+ */
103
+ static AssertFullStatementUsesReadableEntityViews(sqlText, entities, dialect, user, label = 'SQL') {
104
+ if (!user) {
105
+ throw new Error(`Invalid ${label}: no acting user resolved for ad-hoc SQL — refusing`);
106
+ }
107
+ ClientClauseScreen.AssertNoIdentifierAliasNames(sqlText, dialect, label);
108
+ ClientClauseScreen.AssertNoForbiddenFunctionCalls(sqlText, dialect, label);
109
+ const parser = new SQLParser(sqlText, dialect);
110
+ if (!parser.IsValid || parser.HasWriteStatement || parser.StatementKind !== 'select') {
111
+ throw new Error(`Invalid ${label}: not a safe read-only statement — refusing under uncertainty`);
112
+ }
113
+ if (ClientClauseScreen.AstContainsWriteNode(parser.AST)) {
114
+ throw new Error(`Invalid ${label}: write/DDL nested in a subquery is not permitted`);
115
+ }
116
+ const reads = ClientClauseScreen.CollectStatementReads(parser);
117
+ ClientClauseScreen.AssertEverySelectAccountedFor(sqlText, dialect, reads, label);
118
+ const allowed = ClientClauseScreen.BuildEntityBaseViewAllowList(entities);
119
+ for (const relation of reads.Relations) {
120
+ if (relation.IsCTEReference)
121
+ continue;
122
+ const entity = ClientClauseScreen.AssertRelationReadable(allowed, relation, label, user);
123
+ if (entity)
124
+ ClientClauseScreen.AssertUnscopedRead(entity, user, label);
125
+ }
126
+ }
127
+ /**
128
+ * Applies {@link AssertClauseUsesEntityBaseViews} to every clause of a RunView request. A
129
+ * platform-specific clause has every variant screened, each under its own platform's dialect.
130
+ */
131
+ static ScreenViewClauses(clauses, entities, dialect, user) {
132
+ const labelled = [
133
+ ['ExtraFilter', clauses.ExtraFilter],
134
+ ['OrderBy', clauses.OrderBy],
135
+ ['OverrideExcludeFilter', clauses.OverrideExcludeFilter],
136
+ ];
137
+ for (const [label, value] of labelled) {
138
+ for (const variant of ClientClauseScreen.clauseVariants(value, label, dialect)) {
139
+ ClientClauseScreen.AssertClauseUsesEntityBaseViews(variant.Text, label, entities, variant.Dialect, user);
140
+ }
141
+ }
142
+ }
143
+ /**
144
+ * Refuses a statement separator or a comment outside literals and quoted identifiers. A filter
145
+ * or sort fragment never needs either, so this cannot refuse a legitimate clause.
146
+ */
147
+ static AssertSingleStatementFragment(clause, label, dialect) {
148
+ if (clause == null || clause === '')
149
+ return;
150
+ if (typeof clause !== 'string') {
151
+ throw new Error(`Invalid ${label}: expected SQL text`);
152
+ }
153
+ const token = LexSQL(clause, dialect).find((t) => t.Kind === 'semicolon' || t.Kind === 'comment');
154
+ if (token) {
155
+ const found = token.Kind === 'semicolon' ? 'statement separators' : 'comments';
156
+ throw new Error(`Invalid ${label}: ${found} are not permitted in a filter or sort clause`);
157
+ }
158
+ }
159
+ /**
160
+ * Refuses an identifier, quoted or bare, in the form of a name the SQL parser gives a bracket
161
+ * identifier it renames ({@link SQLParser.IsIdentifierAliasName}), in any case. Those names are
162
+ * reserved for the parser, so client SQL may not use them.
163
+ */
164
+ static AssertNoIdentifierAliasNames(sql, dialect, label) {
165
+ const token = LexSQL(sql, dialect).find((t) => (t.Kind === 'word' || t.Kind === 'identifier') && SQLParser.IsIdentifierAliasName(ClientClauseScreen.StripIdentifierQuotes(t.Text).trim()));
166
+ if (token) {
167
+ throw new Error(`Invalid ${label}: '${token.Text}' is a name reserved for the SQL parser — use another name`);
168
+ }
169
+ }
170
+ /**
171
+ * Refuses a call to a function the dialect forbids in caller-supplied SQL
172
+ * ({@link SQLParserDialect.CallerSQLForbiddenFunctions}). Such a function runs SQL given as a
173
+ * string, reads files or other databases, acts on the server, or pauses the query, so the
174
+ * table check cannot see what it reads.
175
+ */
176
+ static AssertNoForbiddenFunctionCalls(sql, dialect, label) {
177
+ const forbidden = FindForbiddenFunctionCalls(sql, dialect);
178
+ if (forbidden.length > 0) {
179
+ throw new Error(`Invalid ${label}: may not call ${forbidden.join(', ')} — such a function runs SQL given as a string, reads files or other databases, acts on the server, or pauses the query, so what it reads cannot be checked`);
180
+ }
181
+ }
182
+ /** True when a parsed AST contains a write or DDL node at any depth. */
183
+ static AstContainsWriteNode(node) {
184
+ if (!node || typeof node !== 'object')
185
+ return false;
186
+ if (Array.isArray(node))
187
+ return node.some((n) => ClientClauseScreen.AstContainsWriteNode(n));
188
+ const obj = node;
189
+ const type = obj.type;
190
+ if (typeof type === 'string' && ClientClauseScreen.WRITE_NODE_TYPES.has(type.toLowerCase())) {
191
+ return true;
192
+ }
193
+ return Object.values(obj).some((v) => ClientClauseScreen.AstContainsWriteNode(v));
194
+ }
195
+ /** Removes the bracket, double-quote or backtick quoting around one identifier. */
196
+ static StripIdentifierQuotes(name) {
197
+ if (!name)
198
+ return '';
199
+ return name.replace(/^\[|\]$/g, '').replace(/^"|"$/g, '').replace(/^`|`$/g, '');
200
+ }
201
+ /** True for a reference written with no schema. A schema, `dbo` included, is matched as written. */
202
+ static IsUnqualifiedSchema(schema) {
203
+ return !schema;
204
+ }
205
+ /**
206
+ * Builds the base-view allow-list for a set of entities, including both each entity's
207
+ * canonical `BaseView` and any registered, usable `AlternateBaseViews` (D13).
208
+ * Disabled alternate base views (`!abv.IsUsable`) are excluded. Canonical `BaseView`
209
+ * entries are registered first and never overwritten by alternate base views; cross-entity
210
+ * collisions on `(schema, viewName)` map to `null` (fail-closed). Memoized per entity array:
211
+ * reused while the array keeps its length and no `EntityInfo` has been built since (the
212
+ * field-security generation, which moves on every build, so a refreshed or replaced entity
213
+ * is noticed).
214
+ */
215
+ static BuildEntityBaseViewAllowList(entities) {
216
+ const generation = CurrentFieldSecurityGeneration();
217
+ const memo = allowListCache.get(entities);
218
+ if (memo && memo.Length === entities.length && memo.Generation === generation) {
219
+ return memo.List;
220
+ }
221
+ const list = ClientClauseScreen.buildAllowList(entities);
222
+ allowListCache.set(entities, { Length: entities.length, Generation: generation, List: list });
223
+ return list;
224
+ }
225
+ /** The uncached build behind {@link BuildEntityBaseViewAllowList}. */
226
+ static buildAllowList(entities) {
227
+ const qualified = new Map();
228
+ const bare = new Map();
229
+ const canonicalQualifiedKeys = new Set();
230
+ for (const e of entities) {
231
+ const view = ClientClauseScreen.StripIdentifierQuotes(e.BaseView);
232
+ if (!view)
233
+ continue;
234
+ const schema = ClientClauseScreen.StripIdentifierQuotes(e.SchemaName);
235
+ const bareKey = view.toLowerCase();
236
+ bare.set(bareKey, bare.has(bareKey) ? null : e);
237
+ if (schema) {
238
+ const qualKey = `${schema}.${view}`.toLowerCase();
239
+ canonicalQualifiedKeys.add(qualKey);
240
+ const existing = qualified.get(qualKey);
241
+ qualified.set(qualKey, existing === undefined || existing === e ? e : null);
242
+ }
243
+ }
244
+ for (const e of entities) {
245
+ for (const abv of e.AlternateBaseViews ?? []) {
246
+ if (!abv.IsUsable)
247
+ continue;
248
+ const altView = ClientClauseScreen.StripIdentifierQuotes(abv.ViewName);
249
+ if (!altView)
250
+ continue;
251
+ const altSchema = ClientClauseScreen.StripIdentifierQuotes(abv.EffectiveSchemaName || e.SchemaName);
252
+ const altBareKey = altView.toLowerCase();
253
+ const existingBare = bare.get(altBareKey);
254
+ bare.set(altBareKey, existingBare === undefined || existingBare === e ? e : null);
255
+ if (altSchema) {
256
+ const qualKey = `${altSchema}.${altView}`.toLowerCase();
257
+ if (canonicalQualifiedKeys.has(qualKey))
258
+ continue;
259
+ const existingQual = qualified.get(qualKey);
260
+ qualified.set(qualKey, existingQual === undefined || existingQual === e ? e : null);
261
+ }
262
+ }
263
+ }
264
+ return { Qualified: qualified, Bare: bare };
265
+ }
266
+ /**
267
+ * Resolves a table reference against the allow-list and returns its entity; throws when it is
268
+ * not an entity base view, or when `user` is given and lacks CanRead on that entity.
269
+ *
270
+ * A schema-qualified reference, `dbo` included, must match an entity in that exact schema. An
271
+ * unqualified one resolves only when the view name is unique across schemas, because the
272
+ * database's default-schema resolution, not this screen, would pick which view runs.
273
+ */
274
+ static AssertTableRefReadable(allowed, schema, table, label, user) {
275
+ const unqualified = ClientClauseScreen.IsUnqualifiedSchema(schema);
276
+ const entity = unqualified
277
+ ? allowed.Bare.get(table.toLowerCase())
278
+ : allowed.Qualified.get(`${schema}.${table}`.toLowerCase());
279
+ const reference = `${schema ? schema + '.' : ''}${table}`;
280
+ if (entity === null) {
281
+ throw new Error(unqualified
282
+ ? `Invalid ${label}: '${table}' is a base view in more than one schema — qualify it with its schema`
283
+ : `Invalid ${label}: '${reference}' is registered as a base view on more than one entity`);
284
+ }
285
+ if (!entity) {
286
+ throw new Error(`Invalid ${label}: subquery must use an entity base view, not '${reference}'`);
287
+ }
288
+ if (user && !entity.GetUserPermisions(user).CanRead) {
289
+ throw new Error(`Invalid ${label}: you do not have read permission on entity '${entity.Name}' referenced by '${reference}'`);
290
+ }
291
+ return entity;
292
+ }
293
+ /**
294
+ * Refuses an entity whose read `user` holds under a row filter (role row-level security or an
295
+ * API-key row filter) or with denied fields. SQL that reads the entity's base view directly, such
296
+ * as a subquery in a client clause or an ad-hoc query, applies neither; RunView on that entity
297
+ * does. For any other entity, a granted read covers every row and field of its base view.
298
+ */
299
+ static AssertUnscopedRead(entity, user, label) {
300
+ if (entity.GetEffectiveRowFilterWhereClause(user, EntityPermissionType.Read, '').length > 0) {
301
+ throw new Error(`Invalid ${label}: entity '${entity.Name}' is row-level-security filtered for you — SQL that reads its base view directly cannot apply that filter; read that entity with RunView`);
302
+ }
303
+ if (entity.GetDeniedReadFields(user).size > 0) {
304
+ throw new Error(`Invalid ${label}: entity '${entity.Name}' has fields you are not permitted to read — SQL that reads its base view directly cannot project them away; read that entity with RunView`);
305
+ }
306
+ }
307
+ /**
308
+ * The full screen for a whole caller-written statement (ad-hoc SQL), run on the SQL as it will
309
+ * execute: one read statement, no write or DDL at any depth, no name reserved for the parser,
310
+ * every SELECT accounted for, and every FROM item that is not a CTE in scope an entity base view
311
+ * `user` can read unscoped ({@link AssertUnscopedRead}). Base tables, system catalogs and table
312
+ * functions are refused. Throws on the first refusal.
313
+ */
314
+ static AssertStatementReadsUnscopedEntityViews(sql, entities, dialect, user, label) {
315
+ ClientClauseScreen.AssertNoIdentifierAliasNames(sql, dialect, label);
316
+ const parser = new SQLParser(sql, dialect);
317
+ if (!parser.IsValid || parser.HasWriteStatement || parser.StatementKind !== 'select') {
318
+ throw new Error(`Invalid ${label}: not a safe read-only statement — refusing under uncertainty`);
319
+ }
320
+ if (ClientClauseScreen.AstContainsWriteNode(parser.AST)) {
321
+ throw new Error(`Invalid ${label}: write/DDL nested in a subquery is not permitted`);
322
+ }
323
+ const reads = ClientClauseScreen.CollectStatementReads(parser);
324
+ ClientClauseScreen.AssertEverySelectAccountedFor(sql, dialect, reads, label);
325
+ const allowed = ClientClauseScreen.BuildEntityBaseViewAllowList(entities);
326
+ for (const relation of reads.Relations) {
327
+ if (relation.IsCTEReference)
328
+ continue;
329
+ const entity = ClientClauseScreen.AssertRelationReadable(allowed, relation, label, user);
330
+ if (entity)
331
+ ClientClauseScreen.AssertUnscopedRead(entity, user, label);
332
+ }
333
+ }
334
+ /**
335
+ * Every FROM item in a parsed statement, and the number of SELECT nodes. The walk visits every
336
+ * property of every node, so it finds a FROM list wherever the grammar puts one: a subquery in a
337
+ * CASE branch, HAVING, a window's ORDER BY or PARTITION BY, a function argument, IN, EXISTS, a
338
+ * set operation or a CTE body. Every FROM item is kept, even when its alias repeats. Names the
339
+ * fallback parse renamed are read back through {@link SQLParser.IdentifierAliases}, which holds
340
+ * only names the parser put in the tree. `skip` is a FROM item node to leave out (the screen's
341
+ * parse wrapper).
342
+ *
343
+ * Each FROM item records whether it reads a CTE in scope there
344
+ * ({@link StatementRelation.IsCTEReference}). A WITH covers its own SELECT, everything below it,
345
+ * and the following set-operation branches unless its SELECT is a parenthesized branch. A CTE
346
+ * body sees the CTEs before it, itself on SQL Server, and every CTE of a PostgreSQL WITH
347
+ * RECURSIVE list. Names match by the dialect's identifier rules ({@link cteNameRules}). The walk
348
+ * keeps a count of the CTEs of each name in scope as it goes, so its time is linear in the tree.
349
+ */
350
+ static CollectStatementReads(parser, skip) {
351
+ const aliases = parser.IdentifierAliases;
352
+ const walk = {
353
+ Reads: { Relations: [], SelectCount: 0 },
354
+ Visited: new WeakSet(),
355
+ Aliases: aliases,
356
+ Names: ClientClauseScreen.cteNameRules(parser, aliases),
357
+ Skip: skip,
358
+ InScope: new Map(),
359
+ };
360
+ ClientClauseScreen.visitNode(walk, parser.AST);
361
+ return walk.Reads;
362
+ }
363
+ /**
364
+ * Refuses SQL whose SELECT keywords, outside literals, quoted identifiers and comments, differ
365
+ * in number from the SELECT nodes a walk of its parse tree found. A subquery the walk cannot
366
+ * see would otherwise go unchecked, so a mismatch fails closed.
367
+ */
368
+ static AssertEverySelectAccountedFor(sql, dialect, reads, label) {
369
+ const keywords = SignificantTokens(LexSQL(sql, dialect)).filter((token) => IsKeyword(token, 'SELECT')).length;
370
+ if (keywords !== reads.SelectCount) {
371
+ throw new Error(`Invalid ${label}: could not account for every subquery in it — refusing under uncertainty`);
372
+ }
373
+ }
374
+ /**
375
+ * The entity one FROM item reads, or null for an unqualified built-in table function that
376
+ * reads only its arguments. Throws for any other function or row source, and when
377
+ * {@link AssertTableRefReadable} refuses a table name.
378
+ */
379
+ static AssertRelationReadable(allowed, relation, label, user) {
380
+ if (relation.TableName) {
381
+ return ClientClauseScreen.AssertTableRefReadable(allowed, relation.SchemaName, relation.TableName, label, user);
382
+ }
383
+ const name = relation.FunctionName;
384
+ if (name && !relation.SchemaName && ClientClauseScreen.ARGUMENT_ONLY_TABLE_FUNCTIONS.has(name.toLowerCase())) {
385
+ return null;
386
+ }
387
+ const source = name ? `the table function '${[relation.SchemaName, name].filter(Boolean).join('.')}'` : 'a row source it cannot identify';
388
+ throw new Error(`Invalid ${label}: a subquery may read only entity base views, not ${source}`);
389
+ }
390
+ /** Visits one node of the parse tree. */
391
+ static visitNode(walk, node) {
392
+ if (!node || typeof node !== 'object' || walk.Visited.has(node))
393
+ return;
394
+ walk.Visited.add(node);
395
+ if (Array.isArray(node)) {
396
+ node.forEach((child) => ClientClauseScreen.visitNode(walk, child));
397
+ return;
398
+ }
399
+ const record = node;
400
+ if (record.type === 'select') {
401
+ ClientClauseScreen.visitSelect(walk, record);
402
+ return;
403
+ }
404
+ Object.values(record).forEach((child) => ClientClauseScreen.visitNode(walk, child));
405
+ }
406
+ /**
407
+ * Visits a SELECT node: counts it, adds its FROM items, and visits its CTE bodies and every
408
+ * other property with the CTE names each one can see. The CTEs of its WITH are in scope from
409
+ * their place in the list until the walk leaves the SELECT.
410
+ */
411
+ static visitSelect(walk, select) {
412
+ walk.Reads.SelectCount++;
413
+ const ctes = Array.isArray(select.with) ? select.with : [];
414
+ const declared = ctes.map((cte) => walk.Names.DeclaredName(ClientClauseScreen.cteNameNode(cte)));
415
+ ClientClauseScreen.enterScope(walk, declared);
416
+ ClientClauseScreen.addFromItems(walk, select.from);
417
+ ClientClauseScreen.leaveScope(walk, declared);
418
+ ClientClauseScreen.visitCTEBodies(walk, ctes, declared);
419
+ const ownBranchOnly = ctes.length > 0 && select.parentheses_symbol === true;
420
+ for (const [key, child] of Object.entries(select)) {
421
+ if (key === 'with')
422
+ continue;
423
+ const outsideWith = key === '_next' && ownBranchOnly;
424
+ if (outsideWith)
425
+ ClientClauseScreen.leaveScope(walk, declared);
426
+ ClientClauseScreen.visitNode(walk, child);
427
+ if (outsideWith)
428
+ ClientClauseScreen.enterScope(walk, declared);
429
+ }
430
+ ClientClauseScreen.leaveScope(walk, declared);
431
+ }
432
+ /**
433
+ * Visits the bodies of one WITH list, whose CTE names are `declared`. Body `i` sees the CTEs
434
+ * before it, itself too on SQL Server, and every CTE of a RECURSIVE list. Each CTE comes into
435
+ * scope once, at its place in the list, and all of them are in scope afterwards.
436
+ */
437
+ static visitCTEBodies(walk, ctes, declared) {
438
+ const recursive = ctes.some((cte) => ClientClauseScreen.isRecursiveCTE(cte));
439
+ let entered = 0;
440
+ ctes.forEach((cte, i) => {
441
+ const visible = recursive ? ctes.length : walk.Names.BodySeesItself ? i + 1 : i;
442
+ for (; entered < visible; entered++)
443
+ ClientClauseScreen.countName(walk, declared[entered], 1);
444
+ ClientClauseScreen.visitNode(walk, cte);
445
+ });
446
+ for (; entered < ctes.length; entered++)
447
+ ClientClauseScreen.countName(walk, declared[entered], 1);
448
+ }
449
+ /** Adds the relation each FROM item names, marking an unqualified reference to a CTE in scope. */
450
+ static addFromItems(walk, from) {
451
+ const items = Array.isArray(from) ? from : from ? [from] : [];
452
+ for (const item of items) {
453
+ if (!item || typeof item !== 'object' || item === walk.Skip)
454
+ continue;
455
+ const relation = ClientClauseScreen.relationOf(item, walk.Aliases);
456
+ if (!relation)
457
+ continue;
458
+ const name = relation.TableName && !relation.SchemaName ? walk.Names.ReferenceName(relation.TableName) : null;
459
+ relation.IsCTEReference = name !== null && (walk.InScope.get(name) ?? 0) > 0;
460
+ walk.Reads.Relations.push(relation);
461
+ }
462
+ }
463
+ /** Brings each readable name among `names` into scope once more. */
464
+ static enterScope(walk, names) {
465
+ for (const name of names)
466
+ ClientClauseScreen.countName(walk, name, 1);
467
+ }
468
+ /** Takes each readable name among `names` out of scope once. */
469
+ static leaveScope(walk, names) {
470
+ for (const name of names)
471
+ ClientClauseScreen.countName(walk, name, -1);
472
+ }
473
+ /**
474
+ * Adds `delta` to the in-scope count of `name` when it is readable. A count that drops to zero
475
+ * stays in the map: in V8, each delete of a key leaves an entry that later lookups of that key
476
+ * step over until the map is rebuilt.
477
+ */
478
+ static countName(walk, name, delta) {
479
+ if (name)
480
+ walk.InScope.set(name, (walk.InScope.get(name) ?? 0) + delta);
481
+ }
482
+ /** The name node of one item of a `with` list. */
483
+ static cteNameNode(cte) {
484
+ return cte && typeof cte === 'object' ? cte.name : undefined;
485
+ }
486
+ /** True for the item of a `with` list that carries RECURSIVE (the parser marks the first). */
487
+ static isRecursiveCTE(cte) {
488
+ return !!cte && typeof cte === 'object' && cte.recursive === true;
489
+ }
490
+ /**
491
+ * How the parser's dialect matches a FROM item to a CTE. SQL Server ignores case, and a CTE
492
+ * body reads its own CTE. PostgreSQL folds an unquoted name to lower case and matches a quoted
493
+ * one exactly ({@link postgresNameRules}). A dialect that quotes identifiers any other way
494
+ * matches no CTE.
495
+ */
496
+ static cteNameRules(parser, aliases) {
497
+ const quote = parser.Dialect.QuoteIdentifier('x');
498
+ if (quote.startsWith('[')) {
499
+ return {
500
+ DeclaredName: (node) => ClientClauseScreen.asciiLower(ClientClauseScreen.identifierText(node, aliases)) || null,
501
+ ReferenceName: (text) => ClientClauseScreen.asciiLower(text) || null,
502
+ BodySeesItself: true,
503
+ };
504
+ }
505
+ if (quote.startsWith('"'))
506
+ return ClientClauseScreen.postgresNameRules(parser, aliases);
507
+ return { DeclaredName: () => null, ReferenceName: () => null, BodySeesItself: false };
508
+ }
509
+ /**
510
+ * PostgreSQL's CTE name rules. A CTE name node says whether it was quoted. A FROM item's name
511
+ * does not, so its quoting comes from the SQL's tokens: a name with upper-case letters that the
512
+ * SQL writes only quoted is exact, one it writes only unquoted folds to lower case, and one it
513
+ * writes both ways, or not as a token at all, matches no CTE.
514
+ */
515
+ static postgresNameRules(parser, aliases) {
516
+ const quoted = new Set();
517
+ const bare = new Set();
518
+ for (const token of LexSQL(parser.SQL, parser.Dialect)) {
519
+ if (token.Kind === 'word')
520
+ bare.add(token.Text);
521
+ else if (token.Kind === 'identifier' && token.Text.startsWith('"'))
522
+ quoted.add(token.Text.slice(1, -1).split('""').join('"'));
523
+ }
524
+ const referenceName = (text) => {
525
+ const folded = ClientClauseScreen.asciiLower(text);
526
+ if (folded === text)
527
+ return text || null;
528
+ if (quoted.has(text) && !bare.has(text))
529
+ return text;
530
+ if (bare.has(text) && !quoted.has(text))
531
+ return folded;
532
+ return null;
533
+ };
534
+ const declaredName = (node) => {
535
+ const name = node && typeof node === 'object' ? node : null;
536
+ if (typeof name?.value === 'string' && name.type === 'double_quote_string')
537
+ return name.value || null;
538
+ if (typeof name?.value === 'string' && name.type === 'default')
539
+ return ClientClauseScreen.asciiLower(name.value) || null;
540
+ return referenceName(ClientClauseScreen.identifierText(node, aliases));
541
+ };
542
+ return { DeclaredName: declaredName, ReferenceName: referenceName, BodySeesItself: false };
543
+ }
544
+ /** `text` with ASCII upper-case letters in lower case: PostgreSQL's folding of an unquoted name. */
545
+ static asciiLower(text) {
546
+ return text.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
547
+ }
548
+ /**
549
+ * The relation one FROM item names. A derived table and a VALUES list name none; the walk
550
+ * reaches any subquery inside them.
551
+ */
552
+ static relationOf(item, aliases) {
553
+ const table = ClientClauseScreen.identifierText(item.table, aliases);
554
+ if (table) {
555
+ const database = ClientClauseScreen.identifierText(item.db, aliases);
556
+ const schema = ClientClauseScreen.identifierText(item.schema, aliases);
557
+ return { SchemaName: schema ? `${database}.${schema}` : database, TableName: table, FunctionName: '', IsCTEReference: false };
558
+ }
559
+ const expr = item.expr && typeof item.expr === 'object' ? item.expr : null;
560
+ if (expr?.ast || expr?.type === 'values')
561
+ return null;
562
+ if (expr?.type === 'function')
563
+ return ClientClauseScreen.functionRelation(expr.name, aliases);
564
+ return { SchemaName: '', TableName: '', FunctionName: '', IsCTEReference: false };
565
+ }
566
+ /** The relation a table function names. Leading name parts join the schema, so a qualified name never matches a built-in. */
567
+ static functionRelation(name, aliases) {
568
+ if (typeof name === 'string')
569
+ return { SchemaName: '', TableName: '', FunctionName: name, IsCTEReference: false };
570
+ const record = name && typeof name === 'object' ? name : {};
571
+ const parts = Array.isArray(record.name) ? record.name.map((part) => ClientClauseScreen.identifierText(part, aliases)) : [];
572
+ const qualifiers = [ClientClauseScreen.identifierText(record.schema, aliases), ...parts.slice(0, -1)].filter(Boolean);
573
+ return { SchemaName: qualifiers.join('.'), TableName: '', FunctionName: parts[parts.length - 1] ?? '', IsCTEReference: false };
574
+ }
575
+ /**
576
+ * The text of an identifier node (a string, or the PostgreSQL grammar's `{ value }` node), with
577
+ * a name the fallback parse renamed read back from `aliases`; empty when unreadable.
578
+ */
579
+ static identifierText(value, aliases) {
580
+ let text = '';
581
+ if (typeof value === 'string') {
582
+ text = value;
583
+ }
584
+ else if (value && typeof value === 'object') {
585
+ const node = value;
586
+ if (typeof node.value === 'string')
587
+ text = node.value;
588
+ else if (node.expr)
589
+ return ClientClauseScreen.identifierText(node.expr, aliases);
590
+ }
591
+ return ClientClauseScreen.StripIdentifierQuotes(aliases?.get(text) ?? text);
592
+ }
593
+ /** The FROM item of the screen's parse wrapper: the root statement's only FROM item, when it is `__mj_clause_screen`. */
594
+ static wrapperFromItem(ast) {
595
+ const root = Array.isArray(ast) ? ast[0] : ast;
596
+ const from = root && typeof root === 'object' ? root.from : undefined;
597
+ if (!Array.isArray(from) || from.length !== 1 || !from[0] || typeof from[0] !== 'object')
598
+ return undefined;
599
+ const item = from[0];
600
+ const isWrapper = ClientClauseScreen.identifierText(item.table, null).toLowerCase() === '__mj_clause_screen' &&
601
+ !ClientClauseScreen.identifierText(item.db, null) &&
602
+ !ClientClauseScreen.identifierText(item.schema, null);
603
+ return isWrapper ? item : undefined;
604
+ }
605
+ /** The text variants of one clause; a platform-specific clause yields each of its variants. */
606
+ static clauseVariants(value, label, dialect) {
607
+ if (value == null)
608
+ return [];
609
+ if (typeof value === 'string')
610
+ return [{ Text: value, Dialect: dialect }];
611
+ if (!IsPlatformSQL(value) || typeof value.default !== 'string') {
612
+ throw new Error(`Invalid ${label}: expected SQL text`);
613
+ }
614
+ const variants = [{ Text: value.default, Dialect: dialect }];
615
+ for (const [variant, variantDialect] of [[value.sqlserver, new SQLServerDialect()], [value.postgresql, new PostgreSQLDialect()]]) {
616
+ if (variant == null)
617
+ continue;
618
+ if (typeof variant !== 'string')
619
+ throw new Error(`Invalid ${label}: expected SQL text`);
620
+ variants.push({ Text: variant, Dialect: variantDialect });
621
+ }
622
+ return variants;
623
+ }
624
+ /**
625
+ * The clause with T-SQL bracket identifiers in the dialect's own quoting, for a dialect that
626
+ * does not quote with brackets. The PostgreSQL provider accepts `[Name]` in a client clause and
627
+ * converts it the same way before running it (`PostgreSQLDataProvider.quoteIdentifiersInSQL`).
628
+ * Only a bracket around a plain name changes; any other bracket stays as written, and the
629
+ * grammar refuses it.
630
+ */
631
+ static toDialectQuoting(clause, dialect) {
632
+ if (dialect.QuoteIdentifier('x').startsWith('['))
633
+ return clause;
634
+ return clause.replace(/\[(\w[\w\s]*)\]/g, (_bracketed, name) => dialect.QuoteIdentifier(name));
635
+ }
636
+ }
637
+ //# sourceMappingURL=clientClauseScreen.js.map