@memberjunction/sql-parser 6.1.5 → 6.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,39 @@
1
+ import { type SQLParserDialect } from '@memberjunction/sql-dialect';
2
+ /** Result of {@link CheckAggregateExpression}. */
3
+ export interface AggregateExpressionCheck {
4
+ /** Whether the expression may be placed as one item of an aggregate SELECT list. */
5
+ IsAllowed: boolean;
6
+ /** Why the expression was refused; `null` when it is allowed. */
7
+ Reason: string | null;
8
+ /**
9
+ * The SQL to run in place of the caller's text: the expression rebuilt from its checked parse
10
+ * tree, with the dialect's quoting. `null` when the expression is refused.
11
+ */
12
+ SQL: string | null;
13
+ }
14
+ /**
15
+ * Whether `expression` may be placed as one item of an aggregate SELECT list —
16
+ * `SELECT <expression> AS [Agg_0] FROM <entity view> WHERE …` — for an entity whose columns are
17
+ * `columns`, and the SQL to run for it.
18
+ *
19
+ * Allowed: exactly one call to an aggregate function (COUNT, SUM, AVG, MIN, MAX, STDEV, VAR,
20
+ * STRING_AGG, …) with nothing before or after it. Inside the call: the given columns, `*` for
21
+ * COUNT, DISTINCT, constants, arithmetic, comparison and logical operators, CASE, CAST, and a
22
+ * fixed set of pure scalar functions. Everything else is refused: statement separators, comments,
23
+ * backslashes inside quoted strings or identifiers, subqueries, other tables, qualified names,
24
+ * variables, aliases, window clauses, and any shape the parser produces that this check does not
25
+ * read.
26
+ *
27
+ * The caller's text is never run. {@link AggregateExpressionCheck.SQL} is rebuilt from the
28
+ * checked parse tree: columns come from `columns` and are quoted for the dialect; function names,
29
+ * type names, operators and keywords come from fixed lists; string and number constants are
30
+ * re-quoted or re-checked. So the database runs exactly the expression that was checked, even
31
+ * where the parser and the database would read the caller's text differently.
32
+ *
33
+ * @param expression The caller-supplied aggregate expression
34
+ * @param dialect The dialect the expression runs under
35
+ * @param columns The entity's column names (its base view's columns). A reference matches a column
36
+ * by `IdentifierMatches` from `@memberjunction/sql-dialect`, the field-level security gate's rule.
37
+ */
38
+ export declare function CheckAggregateExpression(expression: string, dialect: SQLParserDialect, columns: Iterable<string>): AggregateExpressionCheck;
39
+ //# sourceMappingURL=aggregateExpression.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aggregateExpression.d.ts","sourceRoot":"","sources":["../src/aggregateExpression.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,KAAK,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAIvF,kDAAkD;AAClD,MAAM,WAAW,wBAAwB;IACrC,oFAAoF;IACpF,SAAS,EAAE,OAAO,CAAC;IACnB,iEAAiE;IACjE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB;;;OAGG;IACH,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;CACtB;AAyED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,wBAAwB,CAY3I"}
@@ -0,0 +1,447 @@
1
+ import { IdentifierMatches } from '@memberjunction/sql-dialect';
2
+ import { SQLParser } from './sql-parser.js';
3
+ import { LexSQL, SignificantTokens } from './sqlLexer.js';
4
+ /** Aggregate functions an aggregate expression may call at its top level. */
5
+ const AGGREGATE_FUNCTIONS = new Set([
6
+ 'COUNT', 'COUNT_BIG', 'SUM', 'AVG', 'MIN', 'MAX', 'STDEV', 'STDEVP', 'VAR', 'VARP', 'STRING_AGG', 'CHECKSUM_AGG',
7
+ ]);
8
+ /** Scalar functions an aggregate expression may call inside its aggregate. Each is pure and reads no table. */
9
+ const SCALAR_FUNCTIONS = new Set([
10
+ 'ISNULL', 'COALESCE', 'NULLIF', 'IIF',
11
+ 'ABS', 'CEILING', 'CEIL', 'FLOOR', 'ROUND', 'POWER', 'SQRT', 'SIGN', 'EXP', 'LOG', 'LOG10',
12
+ 'LEN', 'LENGTH', 'UPPER', 'LOWER', 'LTRIM', 'RTRIM', 'TRIM', 'LEFT', 'RIGHT', 'SUBSTRING', 'CHARINDEX', 'REPLACE', 'CONCAT',
13
+ 'YEAR', 'MONTH', 'DAY', 'DATEPART', 'DATEDIFF', 'DATEADD', 'EOMONTH', 'DATE_PART', 'DATE_TRUNC',
14
+ 'GETDATE', 'GETUTCDATE', 'SYSDATETIME', 'NOW',
15
+ // The parser reads `NOT (x)` as a call to a function named NOT.
16
+ 'NOT',
17
+ ]);
18
+ /** Types a CAST inside an aggregate may convert to. */
19
+ const CAST_TYPES = new Set([
20
+ 'INT', 'INTEGER', 'BIGINT', 'SMALLINT', 'TINYINT', 'BIT', 'DECIMAL', 'NUMERIC', 'MONEY', 'SMALLMONEY', 'FLOAT', 'REAL',
21
+ 'DATE', 'TIME', 'DATETIME', 'DATETIME2', 'DATETIMEOFFSET', 'SMALLDATETIME', 'TIMESTAMP', 'TIMESTAMPTZ',
22
+ 'CHAR', 'VARCHAR', 'NCHAR', 'NVARCHAR', 'TEXT', 'UNIQUEIDENTIFIER', 'UUID', 'BOOLEAN', 'BOOL',
23
+ ]);
24
+ /** SQL Server functions whose first argument is a date-part keyword (`DATEDIFF(day, a, b)`), which the parser reads as a column. */
25
+ const DATE_PART_FUNCTIONS = new Set(['DATEPART', 'DATEDIFF', 'DATEADD']);
26
+ /** The date-part keywords {@link DATE_PART_FUNCTIONS} accept, lower case. */
27
+ const DATE_PARTS = new Set([
28
+ 'year', 'yy', 'yyyy', 'quarter', 'qq', 'q', 'month', 'mm', 'm', 'dayofyear', 'dy', 'y', 'day', 'dd', 'd',
29
+ 'week', 'wk', 'ww', 'weekday', 'dw', 'w', 'hour', 'hh', 'minute', 'mi', 'n', 'second', 'ss', 's',
30
+ 'millisecond', 'ms', 'microsecond', 'mcs', 'nanosecond', 'ns', 'iso_week', 'isowk', 'isoww',
31
+ ]);
32
+ const BINARY_OPERATORS = new Set([
33
+ '+', '-', '*', '/', '%', '||', '=', '<>', '!=', '<', '>', '<=', '>=',
34
+ 'AND', 'OR', 'IS', 'IS NOT', 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN',
35
+ ]);
36
+ const UNARY_OPERATORS = new Set(['-', '+', 'NOT']);
37
+ /** A numeric literal the way both databases read one. */
38
+ const NUMBER_TEXT = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;
39
+ /**
40
+ * The keys of each node shape that hold a sub-expression the renderer reads. Any other key whose
41
+ * value is an object (a COLLATE, OVER, FILTER or ORDER BY clause, and anything the parser adds
42
+ * later) refuses the expression.
43
+ */
44
+ const AGGREGATE_KEYS = new Set(['name', 'args']);
45
+ const AGGREGATE_ARG_KEYS = new Set(['expr', 'separator']);
46
+ const CALL_KEYS = new Set(['name', 'args']);
47
+ const COLUMN_KEYS = new Set(['column']);
48
+ const BINARY_KEYS = new Set(['left', 'right']);
49
+ const UNARY_KEYS = new Set(['expr']);
50
+ const LIST_KEYS = new Set(['value']);
51
+ const CASE_KEYS = new Set(['expr', 'args']);
52
+ const BRANCH_KEYS = new Set(['cond', 'result']);
53
+ const CAST_KEYS = new Set(['expr', 'target']);
54
+ const SEPARATOR_KEYS = new Set(['delimiter']);
55
+ const TYPE_KEYS = new Set(['suffix']);
56
+ const CONSTANT_KEYS = new Set(['value']);
57
+ /** The only table the expression is parsed against. */
58
+ const SCREEN_TABLE = '__mj_aggregate_screen';
59
+ const SINGLE_CALL = 'it must be a single aggregate function call, with nothing before or after it';
60
+ const BACKSLASH = 'it contains a backslash inside a quoted string or identifier';
61
+ /**
62
+ * Whether `expression` may be placed as one item of an aggregate SELECT list —
63
+ * `SELECT <expression> AS [Agg_0] FROM <entity view> WHERE …` — for an entity whose columns are
64
+ * `columns`, and the SQL to run for it.
65
+ *
66
+ * Allowed: exactly one call to an aggregate function (COUNT, SUM, AVG, MIN, MAX, STDEV, VAR,
67
+ * STRING_AGG, …) with nothing before or after it. Inside the call: the given columns, `*` for
68
+ * COUNT, DISTINCT, constants, arithmetic, comparison and logical operators, CASE, CAST, and a
69
+ * fixed set of pure scalar functions. Everything else is refused: statement separators, comments,
70
+ * backslashes inside quoted strings or identifiers, subqueries, other tables, qualified names,
71
+ * variables, aliases, window clauses, and any shape the parser produces that this check does not
72
+ * read.
73
+ *
74
+ * The caller's text is never run. {@link AggregateExpressionCheck.SQL} is rebuilt from the
75
+ * checked parse tree: columns come from `columns` and are quoted for the dialect; function names,
76
+ * type names, operators and keywords come from fixed lists; string and number constants are
77
+ * re-quoted or re-checked. So the database runs exactly the expression that was checked, even
78
+ * where the parser and the database would read the caller's text differently.
79
+ *
80
+ * @param expression The caller-supplied aggregate expression
81
+ * @param dialect The dialect the expression runs under
82
+ * @param columns The entity's column names (its base view's columns). A reference matches a column
83
+ * by `IdentifierMatches` from `@memberjunction/sql-dialect`, the field-level security gate's rule.
84
+ */
85
+ export function CheckAggregateExpression(expression, dialect, columns) {
86
+ if (typeof expression !== 'string' || expression.trim().length === 0)
87
+ return refuse('it is empty');
88
+ const tokenProblem = checkTokens(expression, dialect);
89
+ if (tokenProblem)
90
+ return refuse(tokenProblem);
91
+ const call = parseSingleItem(expression, dialect);
92
+ if (typeof call === 'string')
93
+ return refuse(call);
94
+ try {
95
+ return { IsAllowed: true, Reason: null, SQL: new AggregateRenderer(dialect, columns).RenderCall(call) };
96
+ }
97
+ catch (e) {
98
+ if (e instanceof AggregateRefusal)
99
+ return refuse(e.message);
100
+ throw e;
101
+ }
102
+ }
103
+ function refuse(reason) {
104
+ return { IsAllowed: false, Reason: reason, SQL: null };
105
+ }
106
+ /** Refuses an expression from inside {@link AggregateRenderer}; {@link CheckAggregateExpression} turns it into a refusal. */
107
+ class AggregateRefusal extends Error {
108
+ }
109
+ function refuseWith(reason) {
110
+ throw new AggregateRefusal(reason);
111
+ }
112
+ /**
113
+ * Refuses comments, statement separators and backslashes inside quoted spans, and requires
114
+ * `name(…)` with nothing outside its parentheses. The parser and the database engines read
115
+ * backslashes inside plain string literals differently, so a quoted span with a backslash is refused.
116
+ */
117
+ function checkTokens(expression, dialect) {
118
+ const tokens = LexSQL(expression, dialect);
119
+ if (tokens.some(t => t.Kind === 'comment'))
120
+ return 'it contains a comment';
121
+ if (tokens.some(t => t.Kind === 'semicolon'))
122
+ return 'it contains a statement separator (;)';
123
+ if (tokens.some(t => (t.Kind === 'string' || t.Kind === 'identifier') && t.Text.includes('\\')))
124
+ return BACKSLASH;
125
+ const significant = SignificantTokens(tokens);
126
+ const last = significant[significant.length - 1];
127
+ const isOneCall = significant.length >= 3 &&
128
+ significant[0].Kind === 'word' &&
129
+ significant[1].Kind === 'open' &&
130
+ last.Kind === 'close' && last.Depth === 0 &&
131
+ significant.slice(2, -1).every(t => t.Depth > 0);
132
+ return isOneCall ? null : SINGLE_CALL;
133
+ }
134
+ /** Parses the expression as the only item of `SELECT … FROM <screen table>`; returns the item's node or why it was refused. */
135
+ function parseSingleItem(expression, dialect) {
136
+ const ast = SQLParser.ParseSQL(`SELECT ${expression} FROM ${SCREEN_TABLE}`, dialect);
137
+ if (!ast)
138
+ return 'it could not be parsed as SQL';
139
+ const statements = Array.isArray(ast) ? ast : [ast];
140
+ if (statements.length !== 1)
141
+ return 'it contains more than one statement';
142
+ const select = statements[0];
143
+ if (!isNode(select) || select.type !== 'select' || !readsOnlyScreenTable(select.from))
144
+ return SINGLE_CALL;
145
+ const items = select.columns;
146
+ if (!Array.isArray(items) || items.length !== 1)
147
+ return SINGLE_CALL;
148
+ const item = items[0];
149
+ if (!isNode(item) || item.as || !isNode(item.expr))
150
+ return SINGLE_CALL;
151
+ return item.expr;
152
+ }
153
+ function readsOnlyScreenTable(from) {
154
+ if (!Array.isArray(from) || from.length !== 1)
155
+ return false;
156
+ const source = from[0];
157
+ return isNode(source) && typeof source.table === 'string' && source.table.toLowerCase() === SCREEN_TABLE && !source.db && !source.join;
158
+ }
159
+ function isNode(value) {
160
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
161
+ }
162
+ /** Refuses a node that holds an object under a key outside `type` and `read`: a clause the renderer does not read. */
163
+ function assertRead(node, read) {
164
+ for (const [key, value] of Object.entries(node)) {
165
+ if (key !== 'type' && !read.has(key) && typeof value === 'object' && value !== null) {
166
+ refuseWith(`it uses ${key.replace(/_/g, ' ').toUpperCase()}, which aggregate expressions do not allow`);
167
+ }
168
+ }
169
+ }
170
+ /** The name a call node invokes, as written (`SUM`, `dbo.fnX`), or null when the node is not a readable call. */
171
+ function callName(node) {
172
+ if (node.type === 'aggr_func')
173
+ return typeof node.name === 'string' ? node.name : null;
174
+ if (node.type !== 'function' || !isNode(node.name))
175
+ return null;
176
+ const nameParts = node.name.name;
177
+ if (!Array.isArray(nameParts) || nameParts.length === 0)
178
+ return null;
179
+ const parts = node.name.schema ? [node.name.schema, ...nameParts] : [...nameParts];
180
+ const names = parts.map(namePart);
181
+ return names.every((n) => n !== null) ? names.join('.') : null;
182
+ }
183
+ function namePart(part) {
184
+ return isNode(part) && typeof part.value === 'string' ? part.value : null;
185
+ }
186
+ /** The column a `column_ref` names: a plain string on SQL Server, `{ expr: { value } }` on PostgreSQL. */
187
+ function columnName(node) {
188
+ if (typeof node.column === 'string')
189
+ return node.column;
190
+ return isNode(node.column) && isNode(node.column.expr) ? node.column.expr.value : undefined;
191
+ }
192
+ /** The date-part keyword a {@link DATE_PART_FUNCTIONS} call starts with, lower case, or null. */
193
+ function datePartOf(value) {
194
+ if (!isNode(value) || value.type !== 'column_ref' || value.table)
195
+ return null;
196
+ const name = columnName(value);
197
+ return typeof name === 'string' && DATE_PARTS.has(name.toLowerCase()) ? name.toLowerCase() : null;
198
+ }
199
+ function parenthesize(sql, operand) {
200
+ return operand ? `(${sql})` : sql;
201
+ }
202
+ /** The upper-case operator of an operation node, refused unless it is in `allowed`. */
203
+ function operatorOf(node, allowed) {
204
+ const operator = typeof node.operator === 'string' ? node.operator.toUpperCase() : '';
205
+ return allowed.has(operator) ? operator : refuseWith(`it uses the operator "${operator}", which aggregate expressions do not allow`);
206
+ }
207
+ /** Rebuilds a constant: numbers re-checked, strings re-quoted, NULL and booleans as keywords. */
208
+ function renderConstant(node) {
209
+ assertRead(node, CONSTANT_KEYS);
210
+ switch (node.type) {
211
+ case 'number':
212
+ case 'bigint': return renderNumber(node.value);
213
+ case 'single_quote_string': return `'${requote(node.value)}'`;
214
+ case 'var_string': return `N'${requote(node.value)}'`;
215
+ case 'bool': return renderBoolean(node.value);
216
+ case 'null': return 'NULL';
217
+ default: return refuseWith(`it contains an expression of type "${String(node.type)}", which aggregate expressions do not allow`);
218
+ }
219
+ }
220
+ function renderNumber(value) {
221
+ const text = typeof value === 'number' && Number.isFinite(value) ? String(value) : typeof value === 'string' ? value : '';
222
+ return NUMBER_TEXT.test(text) ? text : refuseWith('it contains a number the parser could not read');
223
+ }
224
+ function renderBoolean(value) {
225
+ return typeof value === 'boolean' ? (value ? 'TRUE' : 'FALSE') : refuseWith('it contains a boolean the parser could not read');
226
+ }
227
+ /** A string constant as the inside of a quoted literal: the parser's doubled quotes undone, then every quote doubled. */
228
+ function requote(raw) {
229
+ if (typeof raw !== 'string')
230
+ return refuseWith('it contains a string the parser could not read');
231
+ if (raw.includes('\\'))
232
+ return refuseWith(BACKSLASH);
233
+ return raw.replace(/''/g, "'").replace(/'/g, "''");
234
+ }
235
+ function isStringConstant(value) {
236
+ return isNode(value) && (value.type === 'single_quote_string' || value.type === 'var_string');
237
+ }
238
+ /** The right side of `IS` / `IS NOT`: only NULL, TRUE or FALSE. */
239
+ function renderIsOperand(value) {
240
+ if (isNode(value) && value.type === 'null')
241
+ return 'NULL';
242
+ if (isNode(value) && value.type === 'bool')
243
+ return renderBoolean(value.value);
244
+ return refuseWith('it uses IS with something other than NULL, TRUE or FALSE');
245
+ }
246
+ /** A CAST target: an allowed type name with an optional length and scale. */
247
+ function renderType(target) {
248
+ if (!isNode(target) || typeof target.dataType !== 'string')
249
+ return refuseWith('it casts to a type the parser could not read');
250
+ assertRead(target, TYPE_KEYS);
251
+ const type = target.dataType.toUpperCase();
252
+ if (!CAST_TYPES.has(type))
253
+ return refuseWith(`it casts to ${type}, which aggregate expressions do not allow`);
254
+ const suffix = target.suffix;
255
+ if (suffix !== undefined && suffix !== null && !(Array.isArray(suffix) && suffix.length === 0))
256
+ return refuseWith('it casts with a type suffix');
257
+ if (target.length === undefined || target.length === null) {
258
+ return target.scale === undefined || target.scale === null ? type : refuseWith('it casts with a scale but no length');
259
+ }
260
+ const scale = target.scale === undefined || target.scale === null ? '' : `, ${renderTypeSize(target.scale)}`;
261
+ return `${type}(${renderTypeSize(target.length)}${scale})`;
262
+ }
263
+ function renderTypeSize(value) {
264
+ if (typeof value === 'number' && Number.isInteger(value) && value >= 0)
265
+ return String(value);
266
+ if (typeof value === 'string' && value.toUpperCase() === 'MAX')
267
+ return 'MAX';
268
+ return refuseWith('it casts with a size the parser could not read');
269
+ }
270
+ /** A call's argument nodes; an empty list when it has none. */
271
+ function callArguments(node, upperName) {
272
+ const args = node.args;
273
+ if (args === null || args === undefined)
274
+ return [];
275
+ if (!isNode(args) || args.type !== 'expr_list' || !Array.isArray(args.value)) {
276
+ return refuseWith(`it calls ${upperName} with arguments the parser could not read`);
277
+ }
278
+ assertRead(args, LIST_KEYS);
279
+ return args.value;
280
+ }
281
+ /**
282
+ * Walks one aggregate call, allowing only the node shapes {@link CheckAggregateExpression} documents,
283
+ * and rebuilds its SQL. An operation that is the operand of another operation is parenthesized, so
284
+ * the rebuilt SQL keeps the parse tree's grouping.
285
+ */
286
+ class AggregateRenderer {
287
+ constructor(dialect, columns) {
288
+ this.dialect = dialect;
289
+ this.columns = Array.from(columns, column => column.trim()).filter(column => column.length > 0);
290
+ }
291
+ /** Rebuilds the top-level aggregate call. */
292
+ RenderCall(call) {
293
+ const name = callName(call);
294
+ if (name === null)
295
+ return refuseWith(SINGLE_CALL);
296
+ const upper = name.toUpperCase();
297
+ if (!AGGREGATE_FUNCTIONS.has(upper))
298
+ return refuseWith(`${name} is not an aggregate function`);
299
+ // STDEV, VAR and their siblings parse as plain function calls rather than aggr_func.
300
+ return call.type === 'aggr_func' ? this.renderAggregate(upper, call) : this.renderCall(upper, call);
301
+ }
302
+ renderAggregate(upperName, call) {
303
+ assertRead(call, AGGREGATE_KEYS);
304
+ const args = call.args;
305
+ if (!isNode(args))
306
+ return refuseWith(SINGLE_CALL);
307
+ assertRead(args, AGGREGATE_ARG_KEYS);
308
+ const distinct = this.renderDistinct(args.distinct);
309
+ if ((upperName === 'COUNT' || upperName === 'COUNT_BIG') && !distinct && isNode(args.expr) && args.expr.type === 'star') {
310
+ return `${upperName}(*)`;
311
+ }
312
+ const separator = args.separator === null || args.separator === undefined ? '' : `, ${this.renderSeparator(args.separator)}`;
313
+ return `${upperName}(${distinct}${this.render(args.expr)}${separator})`;
314
+ }
315
+ renderDistinct(value) {
316
+ if (value === null || value === undefined)
317
+ return '';
318
+ return typeof value === 'string' && value.toUpperCase() === 'DISTINCT' ? 'DISTINCT ' : refuseWith(`it uses ${String(value)} inside the aggregate`);
319
+ }
320
+ renderSeparator(separator) {
321
+ if (!isNode(separator))
322
+ return refuseWith('it uses a STRING_AGG separator the parser could not read');
323
+ assertRead(separator, SEPARATOR_KEYS);
324
+ return isStringConstant(separator.delimiter) ? this.render(separator.delimiter) : refuseWith('it uses a STRING_AGG separator that is not a constant');
325
+ }
326
+ /** Rebuilds one expression inside the aggregate call; `operand` parenthesizes an operation. */
327
+ render(node, operand = false) {
328
+ if (!isNode(node))
329
+ return refuseWith('it contains an expression the parser could not read');
330
+ if ('ast' in node)
331
+ return refuseWith('it contains a subquery');
332
+ switch (node.type) {
333
+ case 'column_ref': return this.renderColumn(node);
334
+ // A T-SQL "x" is a quoted identifier.
335
+ case 'double_quote_string':
336
+ assertRead(node, CONSTANT_KEYS);
337
+ return this.renderColumnName(node.value);
338
+ case 'binary_expr': return parenthesize(this.renderBinary(node), operand);
339
+ case 'unary_expr': return parenthesize(this.renderUnary(node), operand);
340
+ case 'case': return this.renderCase(node);
341
+ case 'cast': return this.renderCast(node);
342
+ // The parser reads `NOT (x)` as a call; as an operand it needs its own parentheses.
343
+ case 'function': return parenthesize(this.renderScalarCall(node), operand && callName(node)?.toUpperCase() === 'NOT');
344
+ case 'aggr_func': return refuseWith('aggregate functions cannot be nested');
345
+ default: return renderConstant(node);
346
+ }
347
+ }
348
+ renderColumn(node) {
349
+ assertRead(node, COLUMN_KEYS);
350
+ if (node.table || node.db || node.schema)
351
+ return refuseWith('it uses a qualified column name; name the column alone');
352
+ return this.renderColumnName(columnName(node));
353
+ }
354
+ renderColumnName(name) {
355
+ if (typeof name !== 'string')
356
+ return refuseWith('it contains a column reference the parser could not read');
357
+ return this.dialect.QuoteIdentifier(this.resolveColumn(name));
358
+ }
359
+ /**
360
+ * The entity column `name` refers to. Every column is compared with {@link IdentifierMatches},
361
+ * the rule the field-level security gate reports with, so a reference resolves only to a column
362
+ * the gate reports in the caller's text. An exact spelling only chooses between columns that
363
+ * both match.
364
+ */
365
+ resolveColumn(name) {
366
+ const matches = this.columns.filter(column => IdentifierMatches(name, column));
367
+ if (matches.length === 1)
368
+ return matches[0];
369
+ if (matches.length === 0)
370
+ return refuseWith(`it references "${name}", which is not a column of this entity`);
371
+ const exact = matches.find(column => column === name.trim());
372
+ return exact ?? refuseWith(`it references "${name}", which matches more than one column of this entity`);
373
+ }
374
+ renderBinary(node) {
375
+ const operator = operatorOf(node, BINARY_OPERATORS);
376
+ assertRead(node, BINARY_KEYS);
377
+ const left = this.render(node.left, true);
378
+ if (operator === 'IN' || operator === 'NOT IN')
379
+ return `${left} ${operator} (${this.renderList(node.right).join(', ')})`;
380
+ if (operator === 'BETWEEN' || operator === 'NOT BETWEEN') {
381
+ const bounds = this.renderList(node.right, true);
382
+ return bounds.length === 2 ? `${left} ${operator} ${bounds[0]} AND ${bounds[1]}` : refuseWith(`it uses ${operator} without two bounds`);
383
+ }
384
+ if (operator === 'IS' || operator === 'IS NOT')
385
+ return `${left} ${operator} ${renderIsOperand(node.right)}`;
386
+ return `${left} ${operator} ${this.render(node.right, true)}`;
387
+ }
388
+ renderUnary(node) {
389
+ const operator = operatorOf(node, UNARY_OPERATORS);
390
+ assertRead(node, UNARY_KEYS);
391
+ // The space keeps a minus before a negative number from forming the comment marker `--`.
392
+ return `${operator} ${this.render(node.expr, true)}`;
393
+ }
394
+ renderList(node, operands = false) {
395
+ if (isNode(node) && 'ast' in node)
396
+ return refuseWith('it contains a subquery');
397
+ if (!isNode(node) || node.type !== 'expr_list' || !Array.isArray(node.value))
398
+ return refuseWith('it contains a list the parser could not read');
399
+ assertRead(node, LIST_KEYS);
400
+ return node.value.map((value) => this.render(value, operands));
401
+ }
402
+ renderCase(node) {
403
+ assertRead(node, CASE_KEYS);
404
+ const subject = node.expr === null || node.expr === undefined ? '' : ` ${this.render(node.expr)}`;
405
+ if (!Array.isArray(node.args) || node.args.length === 0)
406
+ return refuseWith('it contains a CASE the parser could not read');
407
+ const branches = node.args.map((branch) => this.renderBranch(branch));
408
+ return `CASE${subject} ${branches.join(' ')} END`;
409
+ }
410
+ renderBranch(branch) {
411
+ if (!isNode(branch) || (branch.type !== 'when' && branch.type !== 'else'))
412
+ return refuseWith('it contains a CASE the parser could not read');
413
+ assertRead(branch, BRANCH_KEYS);
414
+ return branch.type === 'when'
415
+ ? `WHEN ${this.render(branch.cond)} THEN ${this.render(branch.result)}`
416
+ : `ELSE ${this.render(branch.result)}`;
417
+ }
418
+ renderCast(node) {
419
+ assertRead(node, CAST_KEYS);
420
+ if (!Array.isArray(node.target) || node.target.length !== 1)
421
+ return refuseWith('it casts to a type the parser could not read');
422
+ return `CAST(${this.render(node.expr)} AS ${renderType(node.target[0])})`;
423
+ }
424
+ renderScalarCall(node) {
425
+ const name = callName(node);
426
+ if (name === null)
427
+ return refuseWith('it calls a function whose name the parser could not read');
428
+ const upper = name.toUpperCase();
429
+ if (SCALAR_FUNCTIONS.has(upper))
430
+ return this.renderCall(upper, node);
431
+ return refuseWith(AGGREGATE_FUNCTIONS.has(upper) ? 'aggregate functions cannot be nested' : `it calls ${name}(), which aggregate expressions do not allow`);
432
+ }
433
+ /** Rebuilds a function call; a date-part keyword may lead a {@link DATE_PART_FUNCTIONS} call. */
434
+ renderCall(upperName, node) {
435
+ assertRead(node, CALL_KEYS);
436
+ const values = callArguments(node, upperName);
437
+ if (upperName === 'NOT') {
438
+ return values.length === 1 ? `NOT (${this.render(values[0])})` : refuseWith('it uses NOT with more than one operand');
439
+ }
440
+ const datePart = DATE_PART_FUNCTIONS.has(upperName) ? datePartOf(values[0]) : null;
441
+ const rendered = datePart === null
442
+ ? values.map(value => this.render(value))
443
+ : [datePart, ...values.slice(1).map(value => this.render(value))];
444
+ return `${upperName}(${rendered.join(', ')})`;
445
+ }
446
+ }
447
+ //# sourceMappingURL=aggregateExpression.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aggregateExpression.js","sourceRoot":"","sources":["../src/aggregateExpression.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAyB,MAAM,6BAA6B,CAAC;AACvF,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAe1D,6EAA6E;AAC7E,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC;IAChC,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,cAAc;CACnH,CAAC,CAAC;AAEH,+GAA+G;AAC/G,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC;IAC7B,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK;IACrC,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,O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CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACzC,CAAC,CAAC,CAAC,QAAQ,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACtE,OAAO,GAAG,SAAS,IAAI,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;IAClD,CAAC;CACJ"}
@@ -0,0 +1,51 @@
1
+ import type { SQLParserDialect } from '@memberjunction/sql-dialect';
2
+ /** Result of {@link IsBalancedSQLFragment}. */
3
+ export interface BalancedFragmentCheck {
4
+ IsBalanced: boolean;
5
+ /** Why the fragment was refused; `null` when it is balanced. */
6
+ Reason: string | null;
7
+ }
8
+ /** Options for {@link IsBalancedSQLFragment}. */
9
+ export interface BalancedFragmentOptions {
10
+ /**
11
+ * Accept comments. Off by default, because a filter from a caller never needs one. Turn it on
12
+ * only for text an administrator wrote, such as a custom view WhereClause.
13
+ */
14
+ AllowComments?: boolean;
15
+ }
16
+ /**
17
+ * Whether `fragment`, a WHERE-clause expression a caller supplied, stays inside one pair of
18
+ * parentheses put around it. Code that builds `(<fragment>) AND (<server filter>)` depends on this:
19
+ * a fragment such as `1=1) OR (1=1` closes the parentheses early, so the server filter narrows only
20
+ * one side of an OR the fragment controls.
21
+ *
22
+ * The fragment is read with the dialect's lexer ({@link LexSQL}), so a parenthesis inside a string
23
+ * literal, quoted identifier or comment does not count. Text the lexer may not read the way the
24
+ * database does is refused rather than guessed at. The fragment is refused when it:
25
+ * - ends inside a string literal, quoted identifier or comment, which would take in the SQL that
26
+ * follows it;
27
+ * - contains a comment, unless {@link BalancedFragmentOptions.AllowComments} is set;
28
+ * - closes a parenthesis it did not open, or leaves one open;
29
+ * - contains a statement separator (`;`);
30
+ * - on PostgreSQL (a dialect with escape or dollar-quoted strings):
31
+ * - has a character outside ASCII anywhere but inside a string literal, quoted identifier or
32
+ * comment. PostgreSQL reads every such character as part of a name, Unicode spaces included;
33
+ * the lexer does not;
34
+ * - has a dollar-quoted string, or a `$` anywhere but inside a name;
35
+ * - follows an escape string (`E'…'`) with another string literal. PostgreSQL joins literals that
36
+ * a line break separates and reads the second in escape mode; the lexer reads it as plain;
37
+ * - puts a string directly after a name that contains `@` or `#`, or after a number ending in `e`.
38
+ * The lexer reads `@` and `#` as name characters, but PostgreSQL reads them as operators (and
39
+ * splits `1e` before a quote).
40
+ */
41
+ export declare function IsBalancedSQLFragment(fragment: string, dialect: SQLParserDialect, options?: BalancedFragmentOptions): BalancedFragmentCheck;
42
+ /**
43
+ * Splits `fragment` at its top-level ANDs: those outside parentheses and outside CASE … END, other
44
+ * than the AND of a BETWEEN. Where the lexer reads `[` and `]` as operators (PostgreSQL), an AND or
45
+ * OR between them outside parentheses is part of a bracket name, not a top-level one. Returns the
46
+ * terms as written, or `null` when the fragment has a top-level OR, because putting each term in
47
+ * its own parentheses would then change its meaning. A fragment with no top-level AND comes back as
48
+ * its only term.
49
+ */
50
+ export declare function SplitTopLevelAndTerms(fragment: string, dialect: SQLParserDialect): string[] | null;
51
+ //# sourceMappingURL=balancedFragment.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"balancedFragment.d.ts","sourceRoot":"","sources":["../src/balancedFragment.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAIpE,+CAA+C;AAC/C,MAAM,WAAW,qBAAqB;IAClC,UAAU,EAAE,OAAO,CAAC;IACpB,gEAAgE;IAChE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB;AAED,iDAAiD;AACjD,MAAM,WAAW,uBAAuB;IACpC;;;OAGG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;CAC3B;AASD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,qBAAqB,CACjC,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,gBAAgB,EACzB,OAAO,CAAC,EAAE,uBAAuB,GAClC,qBAAqB,CAWvB;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,GAAG,MAAM,EAAE,GAAG,IAAI,CAWlG"}