sfmc-sql-converter 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1771 @@
1
+ /**
2
+ * Parser for the Automation Studio / T-SQL style SELECT subset that can be turned into
3
+ * data extension reads.
4
+ *
5
+ * `parseSql(text)` never throws. It returns `{ ast, messages }`; `ast` is `null` whenever at
6
+ * least one message has severity `error`. Parsing stops at the first error.
7
+ */
8
+
9
+ import {
10
+ EMPTY_IDENTIFIER,
11
+ EMPTY_INPUT,
12
+ EXPECTED_FROM,
13
+ EXPECTED_IDENTIFIER,
14
+ EXPECTED_OPERATOR,
15
+ EXPECTED_SELECT,
16
+ EXPECTED_STRING,
17
+ EXPECTED_VALUE,
18
+ INTERNAL_ERROR,
19
+ INVALID_TOP,
20
+ LITERAL_ON_LEFT,
21
+ MISSING_CLOSING_PAREN,
22
+ NESTING_TOO_DEEP,
23
+ NULL_COMPARISON,
24
+ NULL_FALLBACK_REWRITTEN,
25
+ SYNTAX_ERROR,
26
+ SYSTEM_DATA_VIEW,
27
+ TABLE_HINT_IGNORED,
28
+ UNEXPECTED_CHARACTER,
29
+ UNSUPPORTED_AGGREGATE,
30
+ UNSUPPORTED_ALIAS,
31
+ UNSUPPORTED_COLUMN_COMPARISON,
32
+ UNSUPPORTED_DISTINCT,
33
+ UNSUPPORTED_FUNCTION,
34
+ UNSUPPORTED_GROUP_BY,
35
+ UNSUPPORTED_HAVING,
36
+ UNSUPPORTED_JOIN,
37
+ UNSUPPORTED_LINE_SEPARATOR,
38
+ UNSUPPORTED_MULTIPLE_STATEMENTS,
39
+ UNSUPPORTED_NOT_BETWEEN,
40
+ UNSUPPORTED_NOT_CONDITION,
41
+ UNSUPPORTED_NOT_LIKE,
42
+ UNSUPPORTED_OFFSET_FETCH,
43
+ UNSUPPORTED_QUALIFIED_NAME,
44
+ UNSUPPORTED_STAR_WITH_COLUMNS,
45
+ UNSUPPORTED_SUBQUERY,
46
+ UNSUPPORTED_UNION,
47
+ UNTERMINATED_COMMENT,
48
+ UNTERMINATED_IDENTIFIER,
49
+ UNTERMINATED_STRING,
50
+ createMessage,
51
+ } from './messages.js';
52
+ import { sqlLike } from './like.js';
53
+
54
+ /**
55
+ * @typedef {object} Loc
56
+ * @property {number} start 0-based start offset
57
+ * @property {number} end 0-based exclusive end offset
58
+ * @property {number} line 1-based start line
59
+ * @property {number} column 1-based start column
60
+ * @property {number} endLine 1-based end line
61
+ * @property {number} endColumn 1-based exclusive end column
62
+ */
63
+
64
+ /**
65
+ * @typedef {object} Value
66
+ * @property {'string'|'number'} kind literal type
67
+ * @property {string} value unescaped text, or the number exactly as written
68
+ * @property {Loc} loc location
69
+ */
70
+
71
+ /**
72
+ * @typedef {object} Expr
73
+ * @property {'and'|'or'|'compare'|'like'|'in'|'between'|'null'} type node type
74
+ * @property {Loc} loc location
75
+ */
76
+
77
+ /**
78
+ * @typedef {object} SelectAst
79
+ * @property {'select'} type node type
80
+ * @property {number|null} top TOP n, or null
81
+ * @property {'*'|{name: string, loc: Loc}[]} columns selected columns
82
+ * @property {{name: string, loc: Loc}} from data extension name
83
+ * @property {Expr|null} where filter or null
84
+ * @property {{column: string, direction: 'ASC'|'DESC', loc: Loc}[]} orderBy sort order
85
+ * @property {Loc} loc location of the whole statement
86
+ */
87
+
88
+ /**
89
+ * @typedef {object} Token
90
+ * @property {'word'|'bracket'|'string'|'number'|'symbol'|'eof'} type token type
91
+ * @property {string} value identifier / literal value (unescaped) or symbol text
92
+ * @property {string} upper upper-cased value (keyword comparison for words)
93
+ * @property {number} start 0-based start offset
94
+ * @property {number} end 0-based exclusive end offset
95
+ */
96
+
97
+ /**
98
+ Words that cannot be used as bare column / data extension names.
99
+ */
100
+ const RESERVED = new Set([
101
+ 'ALL',
102
+ 'AND',
103
+ 'ANY',
104
+ 'APPLY',
105
+ 'AS',
106
+ 'ASC',
107
+ 'BETWEEN',
108
+ 'BY',
109
+ 'CASE',
110
+ 'CROSS',
111
+ 'DESC',
112
+ 'DISTINCT',
113
+ 'ELSE',
114
+ 'END',
115
+ 'ESCAPE',
116
+ 'EXCEPT',
117
+ 'EXISTS',
118
+ 'FROM',
119
+ 'FULL',
120
+ 'GROUP',
121
+ 'HAVING',
122
+ 'IN',
123
+ 'INNER',
124
+ 'INTERSECT',
125
+ 'INTO',
126
+ 'IS',
127
+ 'JOIN',
128
+ 'LEFT',
129
+ 'LIKE',
130
+ 'NOT',
131
+ 'NULL',
132
+ 'OFFSET',
133
+ 'ON',
134
+ 'OR',
135
+ 'ORDER',
136
+ 'OUTER',
137
+ 'OVER',
138
+ 'PERCENT',
139
+ 'RIGHT',
140
+ 'SELECT',
141
+ 'SOME',
142
+ 'THEN',
143
+ 'TOP',
144
+ 'UNION',
145
+ 'WHEN',
146
+ 'WHERE',
147
+ 'WITH',
148
+ ]);
149
+
150
+ /**
151
+ * Words that must be wrapped in square brackets when used as a name (read-only view of the
152
+ * parser's reserved word list, used by the SQL printer).
153
+ */
154
+ export const RESERVED_WORDS = RESERVED;
155
+
156
+ const AGGREGATES = new Set([
157
+ 'AVG',
158
+ 'CHECKSUM_AGG',
159
+ 'COUNT',
160
+ 'COUNT_BIG',
161
+ 'GROUPING',
162
+ 'MAX',
163
+ 'MIN',
164
+ 'STDEV',
165
+ 'STDEVP',
166
+ 'STRING_AGG',
167
+ 'SUM',
168
+ 'VAR',
169
+ 'VARP',
170
+ ]);
171
+
172
+ const JOIN_WORDS = new Set(['JOIN', 'INNER', 'LEFT', 'RIGHT', 'FULL', 'CROSS', 'OUTER']);
173
+ const SET_OPERATORS = new Set(['UNION', 'EXCEPT', 'INTERSECT']);
174
+ const COMPARISON_OPERATORS = new Set(['=', '<>', '!=', '>', '>=', '<', '<=']);
175
+ const NON_SELECT_STATEMENTS = new Set([
176
+ 'ALTER',
177
+ 'CREATE',
178
+ 'DECLARE',
179
+ 'DELETE',
180
+ 'DROP',
181
+ 'EXEC',
182
+ 'EXECUTE',
183
+ 'INSERT',
184
+ 'MERGE',
185
+ 'SET',
186
+ 'TRUNCATE',
187
+ 'UPDATE',
188
+ 'WITH',
189
+ ]);
190
+ const TWO_CHAR_SYMBOLS = new Set(['<>', '<=', '>=', '!=']);
191
+ const ONE_CHAR_SYMBOLS = new Set(['(', ')', ',', '*', ';', '.', '=', '<', '>', '-', '+', '/', '%']);
192
+
193
+ // a name with U+2028 / U+2029 cannot be kept on one comment line in the generated code
194
+ const LINE_SEPARATORS = /[\u{2028}\u{2029}]/u;
195
+ const WORD_PATTERN = /[\p{L}_#][\p{L}\p{N}_#$]*/uy;
196
+ const NUMBER_PATTERN = /\d+(?:\.\d+)?/y;
197
+ const WHITESPACE_PATTERN = /\s/;
198
+ const INTEGER_PATTERN = /^\d+$/;
199
+ // functions that replace NULL by a fallback; supported in WHERE as FN(column, value) op value
200
+ const NULL_FALLBACK_FUNCTIONS = new Set(['ISNULL', 'COALESCE']);
201
+ const NUMBER_TEXT_PATTERN = /^\s*-?\d+(?:\.\d+)?\s*$/;
202
+ const ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?$/;
203
+
204
+ /**
205
+ * Internal signal that parsing stopped after an error message was recorded.
206
+ */
207
+ class ParseStop extends Error {
208
+ /**
209
+ * Creates the stop signal.
210
+ */
211
+ constructor() {
212
+ super('parse stopped');
213
+ this.name = 'ParseStop';
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Builds the offsets at which each line starts.
219
+ *
220
+ * @param {string} text source text
221
+ * @returns {number[]} start offset of every line
222
+ */
223
+ function computeLineStarts(text) {
224
+ const starts = [0];
225
+ for (let index = text.indexOf('\n'); index !== -1; index = text.indexOf('\n', index + 1)) {
226
+ starts.push(index + 1);
227
+ }
228
+ return starts;
229
+ }
230
+
231
+ /**
232
+ * Converts an offset into a 1-based line / column pair.
233
+ *
234
+ * @param {number[]} lineStarts result of computeLineStarts
235
+ * @param {number} offset 0-based offset
236
+ * @returns {{line: number, column: number}} position
237
+ */
238
+ function positionAt(lineStarts, offset) {
239
+ let low = 0;
240
+ let high = lineStarts.length - 1;
241
+ while (low < high) {
242
+ const middle = Math.ceil((low + high) / 2);
243
+ if (lineStarts[middle] <= offset) {
244
+ low = middle;
245
+ } else {
246
+ high = middle - 1;
247
+ }
248
+ }
249
+ return { line: low + 1, column: offset - lineStarts[low] + 1 };
250
+ }
251
+
252
+ /**
253
+ * Creates the parse context shared by the lexer and the parser.
254
+ *
255
+ * @param {string} text source text
256
+ * @returns {{text: string, lineStarts: number[], messages: object[], tokens: Token[], pos: number}} context
257
+ */
258
+ function createContext(text) {
259
+ return { text, lineStarts: computeLineStarts(text), messages: [], tokens: [], pos: 0 };
260
+ }
261
+
262
+ /**
263
+ * Builds a location object for an offset range.
264
+ *
265
+ * @param {object} context parse context
266
+ * @param {number} start 0-based start offset
267
+ * @param {number} end 0-based exclusive end offset
268
+ * @returns {Loc} location
269
+ */
270
+ function makeLoc(context, start, end) {
271
+ const from = positionAt(context.lineStarts, start);
272
+ const to = positionAt(context.lineStarts, end);
273
+ return {
274
+ start,
275
+ end,
276
+ line: from.line,
277
+ column: from.column,
278
+ endLine: to.line,
279
+ endColumn: to.column,
280
+ };
281
+ }
282
+
283
+ /**
284
+ * Records a message.
285
+ *
286
+ * @param {object} context parse context
287
+ * @param {'error'|'warning'|'info'} severity severity
288
+ * @param {string} code message code
289
+ * @param {string} message plain-language text
290
+ * @param {number} start 0-based start offset
291
+ * @param {number} end 0-based exclusive end offset
292
+ */
293
+ function report(context, severity, code, message, start, end) {
294
+ context.messages.push(createMessage(severity, code, message, makeLoc(context, start, end)));
295
+ }
296
+
297
+ /**
298
+ * Records an error and stops parsing.
299
+ *
300
+ * @param {object} context parse context
301
+ * @param {string} code message code
302
+ * @param {string} message plain-language text
303
+ * @param {number} start 0-based start offset
304
+ * @param {number} end 0-based exclusive end offset
305
+ * @returns {never} always throws ParseStop
306
+ */
307
+ function fail(context, code, message, start, end) {
308
+ report(context, 'error', code, message, start, end);
309
+ throw new ParseStop();
310
+ }
311
+
312
+ // ------------------------------------------------------------------------------------------
313
+ // Lexer
314
+ // ------------------------------------------------------------------------------------------
315
+
316
+ /**
317
+ * Reads a single-quoted string literal starting at the opening quote.
318
+ *
319
+ * @param {object} context parse context
320
+ * @param {number} start offset of the token (the N prefix or the quote)
321
+ * @param {number} quote offset of the opening quote
322
+ * @returns {Token} string token
323
+ */
324
+ function readString(context, start, quote) {
325
+ const { text } = context;
326
+ let value = '';
327
+ let index = quote + 1;
328
+ for (;;) {
329
+ const close = text.indexOf("'", index);
330
+ if (close === -1) {
331
+ fail(
332
+ context,
333
+ UNTERMINATED_STRING,
334
+ "This text value is never closed. Add a closing single quote (') at the end of the value.",
335
+ start,
336
+ text.length,
337
+ );
338
+ }
339
+ value += text.slice(index, close);
340
+ if (text[close + 1] === "'") {
341
+ value += "'";
342
+ index = close + 2;
343
+ } else {
344
+ return { type: 'string', value, upper: value, start, end: close + 1 };
345
+ }
346
+ }
347
+ }
348
+
349
+ /**
350
+ * Reads a [bracketed] identifier starting at the opening bracket.
351
+ *
352
+ * @param {object} context parse context
353
+ * @param {number} start offset of the opening bracket
354
+ * @returns {Token} bracket token
355
+ */
356
+ function readBracket(context, start) {
357
+ const { text } = context;
358
+ let value = '';
359
+ let index = start + 1;
360
+ for (;;) {
361
+ const close = text.indexOf(']', index);
362
+ if (close === -1) {
363
+ fail(
364
+ context,
365
+ UNTERMINATED_IDENTIFIER,
366
+ 'This [name] is never closed. Add a closing square bracket (]) after the name.',
367
+ start,
368
+ text.length,
369
+ );
370
+ }
371
+ value += text.slice(index, close);
372
+ if (text[close + 1] === ']') {
373
+ value += ']';
374
+ index = close + 2;
375
+ } else {
376
+ if (value.trim() === '') {
377
+ fail(
378
+ context,
379
+ EMPTY_IDENTIFIER,
380
+ 'The square brackets are empty. Put the column or data extension name between [ and ].',
381
+ start,
382
+ close + 1,
383
+ );
384
+ }
385
+ const separator = text.slice(start, close).search(LINE_SEPARATORS);
386
+ if (separator !== -1) {
387
+ fail(
388
+ context,
389
+ UNSUPPORTED_LINE_SEPARATOR,
390
+ 'This name contains a line separator character (U+2028 or U+2029). Remove it from the name.',
391
+ start + separator,
392
+ start + separator + 1,
393
+ );
394
+ }
395
+ return { type: 'bracket', value, upper: value.toUpperCase(), start, end: close + 1 };
396
+ }
397
+ }
398
+ }
399
+
400
+ /**
401
+ * Builds the message for a character the lexer does not understand.
402
+ *
403
+ * @param {string} character the character
404
+ * @returns {string} plain-language message
405
+ */
406
+ function unexpectedCharacterMessage(character) {
407
+ if (character === '"') {
408
+ return "Double quotes are not supported. Put text values in single quotes ('text') and wrap names with spaces in square brackets ([My Name]).";
409
+ }
410
+ if (character === '@') {
411
+ return 'Variables (@name) are not supported. Write the value directly into the query instead.';
412
+ }
413
+ return `The character "${character}" is not allowed here. Remove it or put it inside a text value in single quotes.`;
414
+ }
415
+
416
+ /**
417
+ * Splits the text into tokens, skipping whitespace and comments.
418
+ *
419
+ * @param {object} context parse context; tokens are stored on it
420
+ */
421
+ function tokenize(context) {
422
+ const { text } = context;
423
+ const tokens = context.tokens;
424
+ let index = 0;
425
+ while (index < text.length) {
426
+ const character = text[index];
427
+ const following = text[index + 1];
428
+ if (WHITESPACE_PATTERN.test(character)) {
429
+ index++;
430
+ continue;
431
+ }
432
+ if (character === '-' && following === '-') {
433
+ const newline = text.indexOf('\n', index);
434
+ index = newline === -1 ? text.length : newline + 1;
435
+ continue;
436
+ }
437
+ if (character === '/' && following === '*') {
438
+ const close = text.indexOf('*/', index + 2);
439
+ if (close === -1) {
440
+ fail(
441
+ context,
442
+ UNTERMINATED_COMMENT,
443
+ 'This comment is never closed. Add */ where the comment should end.',
444
+ index,
445
+ text.length,
446
+ );
447
+ }
448
+ index = close + 2;
449
+ continue;
450
+ }
451
+ let token;
452
+ if (character === "'") {
453
+ token = readString(context, index, index);
454
+ } else if (following === "'" && (character === 'N' || character === 'n')) {
455
+ token = readString(context, index, index + 1);
456
+ } else if (character === '[') {
457
+ token = readBracket(context, index);
458
+ } else {
459
+ token = readSimpleToken(context, index);
460
+ }
461
+ tokens.push(token);
462
+ index = token.end;
463
+ }
464
+ tokens.push({ type: 'eof', value: '', upper: '', start: text.length, end: text.length });
465
+ }
466
+
467
+ /**
468
+ * Reads a number, word or symbol token.
469
+ *
470
+ * @param {object} context parse context
471
+ * @param {number} index offset to read from
472
+ * @returns {Token} token
473
+ */
474
+ function readSimpleToken(context, index) {
475
+ const { text } = context;
476
+ NUMBER_PATTERN.lastIndex = index;
477
+ const number = NUMBER_PATTERN.exec(text);
478
+ if (number) {
479
+ return {
480
+ type: 'number',
481
+ value: number[0],
482
+ upper: number[0],
483
+ start: index,
484
+ end: index + number[0].length,
485
+ };
486
+ }
487
+ WORD_PATTERN.lastIndex = index;
488
+ const word = WORD_PATTERN.exec(text);
489
+ if (word) {
490
+ return {
491
+ type: 'word',
492
+ value: word[0],
493
+ upper: word[0].toUpperCase(),
494
+ start: index,
495
+ end: index + word[0].length,
496
+ };
497
+ }
498
+ const pair = text.slice(index, index + 2);
499
+ if (TWO_CHAR_SYMBOLS.has(pair)) {
500
+ return { type: 'symbol', value: pair, upper: pair, start: index, end: index + 2 };
501
+ }
502
+ const character = String.fromCodePoint(text.codePointAt(index));
503
+ if (ONE_CHAR_SYMBOLS.has(character)) {
504
+ return { type: 'symbol', value: character, upper: character, start: index, end: index + 1 };
505
+ }
506
+ return fail(
507
+ context,
508
+ UNEXPECTED_CHARACTER,
509
+ unexpectedCharacterMessage(character),
510
+ index,
511
+ index + character.length,
512
+ );
513
+ }
514
+
515
+ // ------------------------------------------------------------------------------------------
516
+ // Token helpers
517
+ // ------------------------------------------------------------------------------------------
518
+
519
+ /**
520
+ * Returns the token at the current position plus an offset.
521
+ *
522
+ * @param {object} context parse context
523
+ * @param {number} [ahead] how many tokens to look ahead
524
+ * @returns {Token} token (the eof token when past the end)
525
+ */
526
+ function peek(context, ahead = 0) {
527
+ const { tokens } = context;
528
+ return tokens[Math.min(context.pos + ahead, tokens.length - 1)];
529
+ }
530
+
531
+ /**
532
+ * Consumes and returns the current token.
533
+ *
534
+ * @param {object} context parse context
535
+ * @returns {Token} consumed token
536
+ */
537
+ function advance(context) {
538
+ const token = peek(context);
539
+ if (token.type !== 'eof') {
540
+ context.pos++;
541
+ }
542
+ return token;
543
+ }
544
+
545
+ /**
546
+ * Checks whether a token is the given keyword (bare word, case-insensitive).
547
+ *
548
+ * @param {Token} token token to check
549
+ * @param {string} keyword upper-case keyword
550
+ * @returns {boolean} true when it matches
551
+ */
552
+ function isKeyword(token, keyword) {
553
+ return token.type === 'word' && token.upper === keyword;
554
+ }
555
+
556
+ /**
557
+ * Checks whether a token is the given symbol.
558
+ *
559
+ * @param {Token} token token to check
560
+ * @param {string} symbol symbol text
561
+ * @returns {boolean} true when it matches
562
+ */
563
+ function isSymbol(token, symbol) {
564
+ return token.type === 'symbol' && token.value === symbol;
565
+ }
566
+
567
+ /**
568
+ * Checks whether a token can be used as a name (bracketed or non-reserved bare word).
569
+ *
570
+ * @param {Token} token token to check
571
+ * @returns {boolean} true for a usable name
572
+ */
573
+ function isName(token) {
574
+ return token.type === 'bracket' || (token.type === 'word' && !RESERVED.has(token.upper));
575
+ }
576
+
577
+ /**
578
+ * Returns the source text of a token for use in messages.
579
+ *
580
+ * @param {object} context parse context
581
+ * @param {Token} token token to describe
582
+ * @returns {string} quoted source text, or a phrase for the end of the query
583
+ */
584
+ function describe(context, token) {
585
+ if (token.type === 'eof') {
586
+ return 'the end of the query';
587
+ }
588
+ return `"${context.text.slice(token.start, token.end)}"`;
589
+ }
590
+
591
+ /**
592
+ * Finds the end offset of the parenthesis group that opens at the given token index.
593
+ *
594
+ * @param {object} context parse context
595
+ * @param {number} openIndex token index of the "("
596
+ * @returns {number} end offset of the matching ")" or of the last token when unclosed
597
+ */
598
+ function groupEnd(context, openIndex) {
599
+ const { tokens } = context;
600
+ let depth = 0;
601
+ let end = tokens[openIndex].end;
602
+ for (let index = openIndex; index < tokens.length; index++) {
603
+ const token = tokens[index];
604
+ if (token.type === 'eof') {
605
+ break;
606
+ }
607
+ end = token.end;
608
+ if (isSymbol(token, '(')) {
609
+ depth++;
610
+ } else if (isSymbol(token, ')')) {
611
+ depth--;
612
+ if (depth === 0) {
613
+ break;
614
+ }
615
+ }
616
+ }
617
+ return end;
618
+ }
619
+
620
+ // ------------------------------------------------------------------------------------------
621
+ // Shared rejections
622
+ // ------------------------------------------------------------------------------------------
623
+
624
+ /**
625
+ * Fails with UNSUPPORTED_SUBQUERY when the current token opens a subquery "(SELECT".
626
+ *
627
+ * @param {object} context parse context
628
+ */
629
+ function rejectSubquery(context) {
630
+ if (isSymbol(peek(context), '(') && isKeyword(peek(context, 1), 'SELECT')) {
631
+ fail(
632
+ context,
633
+ UNSUPPORTED_SUBQUERY,
634
+ 'Queries inside a query (subqueries) are not supported. Run the inner query on its own and use its result values directly.',
635
+ peek(context).start,
636
+ groupEnd(context, context.pos),
637
+ );
638
+ }
639
+ }
640
+
641
+ /**
642
+ * Fails with UNSUPPORTED_FUNCTION / UNSUPPORTED_AGGREGATE when the current token starts a
643
+ * function call or a CASE expression.
644
+ *
645
+ * @param {object} context parse context
646
+ */
647
+ function rejectFunction(context) {
648
+ const token = peek(context);
649
+ if (isKeyword(token, 'CASE')) {
650
+ fail(
651
+ context,
652
+ UNSUPPORTED_FUNCTION,
653
+ 'CASE expressions are not supported. Select or compare the plain column instead and handle the different cases in your code.',
654
+ token.start,
655
+ token.end,
656
+ );
657
+ }
658
+ if (token.type !== 'word' || !isSymbol(peek(context, 1), '(')) {
659
+ return;
660
+ }
661
+ const end = groupEnd(context, context.pos + 1);
662
+ if (AGGREGATES.has(token.upper)) {
663
+ fail(
664
+ context,
665
+ UNSUPPORTED_AGGREGATE,
666
+ `${token.value}() combines several rows into one value, which is not supported. Select the plain rows and calculate the result in your code.`,
667
+ token.start,
668
+ end,
669
+ );
670
+ }
671
+ fail(
672
+ context,
673
+ UNSUPPORTED_FUNCTION,
674
+ `The function ${token.value}() is not supported. Use the plain column name or a fixed value (for dates, write the date in single quotes, e.g. '2026-01-31').`,
675
+ token.start,
676
+ end,
677
+ );
678
+ }
679
+
680
+ /**
681
+ * Reads a column or data extension name, rejecting functions and prefixed names.
682
+ *
683
+ * @param {object} context parse context
684
+ * @param {string} label what kind of name is expected ("column" or "data extension")
685
+ * @returns {{name: string, start: number, end: number}} the name and its offsets
686
+ */
687
+ function readName(context, label) {
688
+ rejectFunction(context);
689
+ const token = peek(context);
690
+ if (!isName(token)) {
691
+ let message;
692
+ if (token.type === 'eof') {
693
+ message = `The query ends where a ${label} name is expected. Add the ${label} name.`;
694
+ } else if (token.type === 'word') {
695
+ message = `${describe(context, token)} is a reserved SQL word. If it is the ${label} name, wrap it in square brackets: [${token.value}].`;
696
+ } else {
697
+ message = `Expected a ${label} name but found ${describe(context, token)}. Write the ${label} name here; use [square brackets] for names with spaces.`;
698
+ }
699
+ fail(context, EXPECTED_IDENTIFIER, message, token.start, token.end);
700
+ }
701
+ advance(context);
702
+ if (isSymbol(peek(context), '.')) {
703
+ let end = peek(context).end;
704
+ while (isSymbol(peek(context), '.')) {
705
+ advance(context);
706
+ end = advance(context).end;
707
+ }
708
+ fail(
709
+ context,
710
+ UNSUPPORTED_QUALIFIED_NAME,
711
+ `Names with a prefix (such as ENT. or a table name before the dot) are not supported. Write only the ${label} name, without the part before the dot.`,
712
+ token.start,
713
+ end,
714
+ );
715
+ }
716
+ return { name: token.value, start: token.start, end: token.end };
717
+ }
718
+
719
+ /**
720
+ * Fails with UNSUPPORTED_ALIAS when the current token starts an alias (AS x, or a bare name).
721
+ *
722
+ * @param {object} context parse context
723
+ * @param {number} nameStart start offset of the name the alias belongs to
724
+ */
725
+ function rejectAlias(context, nameStart) {
726
+ const token = peek(context);
727
+ let end;
728
+ if (isKeyword(token, 'AS')) {
729
+ const aliasToken = peek(context, 1);
730
+ end = aliasToken.type === 'eof' ? token.end : aliasToken.end;
731
+ } else if (isName(token) || token.type === 'string') {
732
+ end = token.end;
733
+ } else {
734
+ return;
735
+ }
736
+ fail(
737
+ context,
738
+ UNSUPPORTED_ALIAS,
739
+ 'Renaming with AS (aliases) is not supported. Remove the new name and use the original name.',
740
+ nameStart,
741
+ end,
742
+ );
743
+ }
744
+
745
+ /**
746
+ * Fails with a generic syntax error for an unexpected token.
747
+ *
748
+ * @param {object} context parse context
749
+ * @param {string} hint what the user should do instead
750
+ * @returns {never} always throws ParseStop
751
+ */
752
+ function unexpected(context, hint) {
753
+ const token = peek(context);
754
+ fail(
755
+ context,
756
+ SYNTAX_ERROR,
757
+ `Unexpected ${describe(context, token)}. ${hint}`,
758
+ token.start,
759
+ token.end,
760
+ );
761
+ }
762
+
763
+ // ------------------------------------------------------------------------------------------
764
+ // Values and conditions
765
+ // ------------------------------------------------------------------------------------------
766
+
767
+ /**
768
+ * Reads a literal value (text in single quotes or a number, optionally negative).
769
+ *
770
+ * @param {object} context parse context
771
+ * @param {{name: string, start: number}} column the column the value is compared with
772
+ * @returns {Value} value node
773
+ */
774
+ function parseValue(context, column) {
775
+ const token = peek(context);
776
+ if (token.type === 'string' || token.type === 'number') {
777
+ advance(context);
778
+ return {
779
+ kind: token.type,
780
+ value: token.value,
781
+ loc: makeLoc(context, token.start, token.end),
782
+ };
783
+ }
784
+ const following = peek(context, 1);
785
+ if (isSymbol(token, '-') && following.type === 'number' && following.start === token.end) {
786
+ advance(context);
787
+ advance(context);
788
+ return {
789
+ kind: 'number',
790
+ value: `-${following.value}`,
791
+ loc: makeLoc(context, token.start, following.end),
792
+ };
793
+ }
794
+ if (isKeyword(token, 'NULL')) {
795
+ fail(
796
+ context,
797
+ NULL_COMPARISON,
798
+ `NULL cannot be used as a value here. To find empty values write "${column.name} IS NULL"; for non-empty values write "${column.name} IS NOT NULL".`,
799
+ token.start,
800
+ token.end,
801
+ );
802
+ }
803
+ rejectFunction(context);
804
+ rejectSubquery(context);
805
+ if (isName(token)) {
806
+ fail(
807
+ context,
808
+ UNSUPPORTED_COLUMN_COMPARISON,
809
+ `Comparing two columns (${column.name} and ${token.value}) is not supported. Compare the column with a fixed value instead. If ${token.value} is meant as text, wrap it in single quotes: '${token.value}'.`,
810
+ column.start,
811
+ token.end,
812
+ );
813
+ }
814
+ return fail(
815
+ context,
816
+ EXPECTED_VALUE,
817
+ `Expected a value but found ${describe(context, token)}. Write text in single quotes ('text') or a plain number.`,
818
+ token.start,
819
+ token.end,
820
+ );
821
+ }
822
+
823
+ /**
824
+ * Reads the value list of an IN condition, starting at "(".
825
+ *
826
+ * @param {object} context parse context
827
+ * @param {{name: string, start: number}} column the column being tested
828
+ * @param {boolean} negated true for NOT IN
829
+ * @returns {Expr} in node
830
+ */
831
+ function parseIn(context, column, negated) {
832
+ const open = peek(context);
833
+ if (!isSymbol(open, '(')) {
834
+ unexpected(context, "IN needs a list of values in round brackets, e.g. IN ('a', 'b').");
835
+ }
836
+ rejectSubquery(context);
837
+ advance(context);
838
+ const values = [];
839
+ for (;;) {
840
+ values.push(parseValue(context, column));
841
+ const token = peek(context);
842
+ if (isSymbol(token, ',')) {
843
+ advance(context);
844
+ } else if (isSymbol(token, ')')) {
845
+ advance(context);
846
+ return {
847
+ type: 'in',
848
+ negated,
849
+ column: column.name,
850
+ values,
851
+ loc: makeLoc(context, column.start, token.end),
852
+ };
853
+ } else if (token.type === 'eof') {
854
+ fail(
855
+ context,
856
+ MISSING_CLOSING_PAREN,
857
+ 'This value list is never closed. Add a closing bracket ) after the last value.',
858
+ open.start,
859
+ open.end,
860
+ );
861
+ } else {
862
+ unexpected(context, 'Separate the values with commas and close the list with ).');
863
+ }
864
+ }
865
+ }
866
+
867
+ /**
868
+ * Orders two literals the way SQL would: the literal kinds stand for the column type (a number
869
+ * on either side → numbers; two ISO dates → dates; else text without case and trailing spaces).
870
+ *
871
+ * @param {Value} left fallback value
872
+ * @param {Value} right compared value
873
+ * @returns {number|null} negative / 0 / positive, or null when the types do not fit together
874
+ */
875
+ function compareLiterals(left, right) {
876
+ if (left.kind === 'number' || right.kind === 'number') {
877
+ if (!NUMBER_TEXT_PATTERN.test(left.value) || !NUMBER_TEXT_PATTERN.test(right.value)) {
878
+ return null;
879
+ }
880
+ return Number(left.value) - Number(right.value);
881
+ }
882
+ if (ISO_DATE_PATTERN.test(left.value) && ISO_DATE_PATTERN.test(right.value)) {
883
+ // Read every value as UTC: Date.parse reads a date-only text as UTC but a text with a
884
+ // time as local time, which would shift one side by the local offset.
885
+ const toTime = (text) => {
886
+ const iso = text.replace(' ', 'T');
887
+ return Date.parse(`${iso.includes('T') ? iso : `${iso}T00:00`}Z`);
888
+ };
889
+ return toTime(left.value) - toTime(right.value);
890
+ }
891
+ const a = left.value.trimEnd().toLowerCase();
892
+ const b = right.value.trimEnd().toLowerCase();
893
+ if (a === b) {
894
+ return 0;
895
+ }
896
+ return a < b ? -1 : 1;
897
+ }
898
+
899
+ /**
900
+ * Evaluates `fallback op value` at conversion time.
901
+ *
902
+ * @param {Value} fallback fallback literal
903
+ * @param {string} op comparison operator or 'LIKE'
904
+ * @param {Value} value compared literal or LIKE pattern
905
+ * @returns {boolean|null} the result, or null when the types do not fit together
906
+ */
907
+ function fallbackMatches(fallback, op, value) {
908
+ if (op === 'LIKE') {
909
+ return sqlLike(fallback.value, value.value);
910
+ }
911
+ const order = compareLiterals(fallback, value);
912
+ if (order === null || Number.isNaN(order)) {
913
+ return null;
914
+ }
915
+ const results = {
916
+ '=': order === 0,
917
+ '<>': order !== 0,
918
+ '<': order < 0,
919
+ '<=': order <= 0,
920
+ '>': order > 0,
921
+ '>=': order >= 0,
922
+ };
923
+ return results[op];
924
+ }
925
+
926
+ /**
927
+ * Reads the fallback argument of ISNULL / COALESCE: a fixed value or NULL.
928
+ *
929
+ * @param {object} context parse context
930
+ * @param {{name: string, start: number}} column the column of the call
931
+ * @param {(detail: string) => never} unsupported fails with an explanation
932
+ * @returns {Value|null} the fallback, or null for NULL
933
+ */
934
+ function parseFallbackValue(context, column, unsupported) {
935
+ const token = peek(context);
936
+ if (isKeyword(token, 'NULL')) {
937
+ advance(context);
938
+ return null;
939
+ }
940
+ if (token.type === 'word' && isSymbol(peek(context, 1), '(')) {
941
+ unsupported('Nested functions are not supported.');
942
+ }
943
+ if (isName(token)) {
944
+ unsupported('The fallback must be a fixed value, not a column.');
945
+ }
946
+ return parseValue(context, column);
947
+ }
948
+
949
+ /**
950
+ * Parses `ISNULL(column, fallback) op value` (also COALESCE with two arguments) and rewrites
951
+ * it without the function: `column op value`, plus `OR column IS NULL` when `fallback op value`
952
+ * is true. A NULL fallback adds no OR branch; comparing with NULL stays an error.
953
+ *
954
+ * @param {object} context parse context, positioned at the function name
955
+ * @returns {Expr} condition node (compare / like, or an OR with an IS NULL test)
956
+ */
957
+ function parseFallbackPredicate(context) {
958
+ const functionToken = advance(context);
959
+ const name = functionToken.upper;
960
+ const callEnd = groupEnd(context, context.pos);
961
+ const unsupported = (detail) =>
962
+ fail(
963
+ context,
964
+ UNSUPPORTED_FUNCTION,
965
+ `${name}() is only supported in WHERE as ${name}(Column, value) compared with a fixed value, e.g. "${name}(Country, 'DE') = 'DE'". ${detail}`,
966
+ functionToken.start,
967
+ callEnd,
968
+ );
969
+ advance(context);
970
+ const first = peek(context);
971
+ if (first.type === 'word' && isSymbol(peek(context, 1), '(')) {
972
+ unsupported('Nested functions are not supported.');
973
+ }
974
+ if (!isName(first)) {
975
+ unsupported('The first argument must be a column name.');
976
+ }
977
+ const columnName = readName(context, 'column');
978
+ const column = { name: columnName.name, start: functionToken.start };
979
+ if (!isSymbol(peek(context), ',')) {
980
+ unsupported('It needs exactly two arguments: the column and the fallback value.');
981
+ }
982
+ advance(context);
983
+ const fallback = parseFallbackValue(context, column, unsupported);
984
+ if (isSymbol(peek(context), ',')) {
985
+ unsupported('More than two arguments are not supported.');
986
+ }
987
+ const close = peek(context);
988
+ if (!isSymbol(close, ')')) {
989
+ if (close.type === 'eof') {
990
+ fail(
991
+ context,
992
+ MISSING_CLOSING_PAREN,
993
+ `This ${name}( is never closed. Add a closing bracket ) after the fallback value.`,
994
+ functionToken.start,
995
+ close.start,
996
+ );
997
+ }
998
+ unexpected(context, `Close ${name}( with ) after the fallback value.`);
999
+ }
1000
+ advance(context);
1001
+ const operator = peek(context);
1002
+ let op;
1003
+ if (operator.type === 'symbol' && COMPARISON_OPERATORS.has(operator.value)) {
1004
+ op = operator.value === '!=' ? '<>' : operator.value;
1005
+ } else if (isKeyword(operator, 'LIKE')) {
1006
+ op = 'LIKE';
1007
+ } else if (isKeyword(operator, 'NOT') && isKeyword(peek(context, 1), 'LIKE')) {
1008
+ fail(
1009
+ context,
1010
+ UNSUPPORTED_NOT_LIKE,
1011
+ 'NOT LIKE is not supported. Use LIKE with the opposite pattern, or filter the unwanted rows out in your code.',
1012
+ operator.start,
1013
+ peek(context, 1).end,
1014
+ );
1015
+ } else {
1016
+ unsupported('Only =, <>, <, <=, >, >= and LIKE can follow it.');
1017
+ }
1018
+ advance(context);
1019
+ const value = parseValue(context, { name: columnName.name, start: functionToken.start });
1020
+ if (op === 'LIKE' && value.kind !== 'string') {
1021
+ fail(
1022
+ context,
1023
+ EXPECTED_STRING,
1024
+ `LIKE needs a text pattern in single quotes, e.g. LIKE '%${value.value}%'.`,
1025
+ value.loc.start,
1026
+ value.loc.end,
1027
+ );
1028
+ }
1029
+ const loc = makeLoc(context, functionToken.start, value.loc.end);
1030
+ const base =
1031
+ op === 'LIKE'
1032
+ ? { type: 'like', column: columnName.name, pattern: value, loc }
1033
+ : { type: 'compare', op, column: columnName.name, value, loc };
1034
+ const isOrNull = fallback ? fallbackMatches(fallback, op, value) : false;
1035
+ if (isOrNull === null) {
1036
+ unsupported(
1037
+ `The fallback ${context.text.slice(fallback.loc.start, fallback.loc.end)} and the value ${context.text.slice(value.loc.start, value.loc.end)} have different types; use values of the column's type.`,
1038
+ );
1039
+ }
1040
+ const source = context.text.slice(functionToken.start, value.loc.end);
1041
+ const plain = `${columnName.name} ${op} ${context.text.slice(value.loc.start, value.loc.end)}`;
1042
+ const reason = fallback
1043
+ ? `the fallback ${context.text.slice(fallback.loc.start, fallback.loc.end)} ${isOrNull ? 'matches' : 'does not match'} the condition`
1044
+ : 'the fallback is NULL';
1045
+ report(
1046
+ context,
1047
+ 'info',
1048
+ NULL_FALLBACK_REWRITTEN,
1049
+ `"${source}" is converted as "${plain}${isOrNull ? ` OR ${columnName.name} IS NULL` : ''}", because ${reason}. This assumes the fallback value fits the type of ${columnName.name}.`,
1050
+ functionToken.start,
1051
+ value.loc.end,
1052
+ );
1053
+ if (!isOrNull) {
1054
+ return base;
1055
+ }
1056
+ const nullTest = {
1057
+ type: 'null',
1058
+ negated: false,
1059
+ column: columnName.name,
1060
+ loc: makeLoc(context, functionToken.start, close.end),
1061
+ };
1062
+ return { type: 'or', left: base, right: nullTest, loc };
1063
+ }
1064
+
1065
+ /**
1066
+ * Parses a single condition such as `Age > 5`, `Name LIKE 'a%'` or `Email IS NULL`.
1067
+ *
1068
+ * @param {object} context parse context
1069
+ * @returns {Expr} condition node
1070
+ */
1071
+ function parsePredicate(context) {
1072
+ const first = peek(context);
1073
+ if (
1074
+ first.type === 'word' &&
1075
+ NULL_FALLBACK_FUNCTIONS.has(first.upper) &&
1076
+ isSymbol(peek(context, 1), '(')
1077
+ ) {
1078
+ return parseFallbackPredicate(context);
1079
+ }
1080
+ if (first.type === 'string' || first.type === 'number' || isSymbol(first, '-')) {
1081
+ fail(
1082
+ context,
1083
+ LITERAL_ON_LEFT,
1084
+ `Put the column name first, then the value, e.g. "Age > 5" instead of "5 < Age".`,
1085
+ first.start,
1086
+ first.end,
1087
+ );
1088
+ }
1089
+ const name = readName(context, 'column');
1090
+ const column = { name: name.name, start: name.start };
1091
+ const operator = peek(context);
1092
+ if (operator.type === 'symbol' && COMPARISON_OPERATORS.has(operator.value)) {
1093
+ advance(context);
1094
+ const value = parseValue(context, column);
1095
+ return {
1096
+ type: 'compare',
1097
+ op: operator.value === '!=' ? '<>' : operator.value,
1098
+ column: column.name,
1099
+ value,
1100
+ loc: makeLoc(context, column.start, value.loc.end),
1101
+ };
1102
+ }
1103
+ if (isKeyword(operator, 'LIKE')) {
1104
+ advance(context);
1105
+ const pattern = parseValue(context, column);
1106
+ if (pattern.kind !== 'string') {
1107
+ fail(
1108
+ context,
1109
+ EXPECTED_STRING,
1110
+ `LIKE needs a text pattern in single quotes, e.g. LIKE '%${pattern.value}%'.`,
1111
+ pattern.loc.start,
1112
+ pattern.loc.end,
1113
+ );
1114
+ }
1115
+ return {
1116
+ type: 'like',
1117
+ column: column.name,
1118
+ pattern,
1119
+ loc: makeLoc(context, column.start, pattern.loc.end),
1120
+ };
1121
+ }
1122
+ if (isKeyword(operator, 'IN')) {
1123
+ advance(context);
1124
+ return parseIn(context, column, false);
1125
+ }
1126
+ if (isKeyword(operator, 'BETWEEN')) {
1127
+ return parseBetween(context, column);
1128
+ }
1129
+ if (isKeyword(operator, 'NOT')) {
1130
+ return parseNotOperator(context, column);
1131
+ }
1132
+ if (isKeyword(operator, 'IS')) {
1133
+ advance(context);
1134
+ let isNegated = false;
1135
+ if (isKeyword(peek(context), 'NOT')) {
1136
+ advance(context);
1137
+ isNegated = true;
1138
+ }
1139
+ const nullToken = peek(context);
1140
+ if (!isKeyword(nullToken, 'NULL')) {
1141
+ unexpected(
1142
+ context,
1143
+ `IS can only be followed by NULL or NOT NULL, e.g. "${column.name} IS NULL".`,
1144
+ );
1145
+ }
1146
+ advance(context);
1147
+ return {
1148
+ type: 'null',
1149
+ negated: isNegated,
1150
+ column: column.name,
1151
+ loc: makeLoc(context, column.start, nullToken.end),
1152
+ };
1153
+ }
1154
+ return fail(
1155
+ context,
1156
+ EXPECTED_OPERATOR,
1157
+ `Expected a comparison after ${column.name} (=, <>, <, <=, >, >=, LIKE, IN, BETWEEN or IS NULL) but found ${describe(context, operator)}.`,
1158
+ operator.start,
1159
+ operator.end,
1160
+ );
1161
+ }
1162
+
1163
+ /**
1164
+ * Parses `column BETWEEN low AND high`, starting at BETWEEN.
1165
+ *
1166
+ * @param {object} context parse context
1167
+ * @param {{name: string, start: number}} column the column being tested
1168
+ * @returns {Expr} between node
1169
+ */
1170
+ function parseBetween(context, column) {
1171
+ advance(context);
1172
+ const low = parseValue(context, column);
1173
+ if (!isKeyword(peek(context), 'AND')) {
1174
+ unexpected(
1175
+ context,
1176
+ `BETWEEN needs two values joined by AND, e.g. "${column.name} BETWEEN 1 AND 10".`,
1177
+ );
1178
+ }
1179
+ advance(context);
1180
+ const high = parseValue(context, column);
1181
+ return {
1182
+ type: 'between',
1183
+ column: column.name,
1184
+ low,
1185
+ high,
1186
+ loc: makeLoc(context, column.start, high.loc.end),
1187
+ };
1188
+ }
1189
+
1190
+ /**
1191
+ * Parses the part after `column NOT`: only NOT IN is supported.
1192
+ *
1193
+ * @param {object} context parse context
1194
+ * @param {{name: string, start: number}} column the column being tested
1195
+ * @returns {Expr} in node with negated = true
1196
+ */
1197
+ function parseNotOperator(context, column) {
1198
+ const notToken = advance(context);
1199
+ const token = peek(context);
1200
+ if (isKeyword(token, 'IN')) {
1201
+ advance(context);
1202
+ return parseIn(context, column, true);
1203
+ }
1204
+ if (isKeyword(token, 'LIKE')) {
1205
+ fail(
1206
+ context,
1207
+ UNSUPPORTED_NOT_LIKE,
1208
+ 'NOT LIKE is not supported. Use LIKE with the opposite pattern, or filter the unwanted rows out in your code.',
1209
+ notToken.start,
1210
+ token.end,
1211
+ );
1212
+ }
1213
+ if (isKeyword(token, 'BETWEEN')) {
1214
+ fail(
1215
+ context,
1216
+ UNSUPPORTED_NOT_BETWEEN,
1217
+ `NOT BETWEEN is not supported. Write it as two conditions instead: "(${column.name} < low OR ${column.name} > high)".`,
1218
+ notToken.start,
1219
+ token.end,
1220
+ );
1221
+ }
1222
+ return unexpected(context, "After NOT only IN is supported here, e.g. \"NOT IN ('a', 'b')\".");
1223
+ }
1224
+
1225
+ /**
1226
+ * Parses a bracketed group or a single condition.
1227
+ *
1228
+ * @param {object} context parse context
1229
+ * @returns {Expr} expression node
1230
+ */
1231
+ function parsePrimary(context) {
1232
+ const token = peek(context);
1233
+ if (isKeyword(token, 'NOT')) {
1234
+ const following = peek(context, 1);
1235
+ const end = isSymbol(following, '(')
1236
+ ? groupEnd(context, context.pos + 1)
1237
+ : following.type === 'eof'
1238
+ ? token.end
1239
+ : following.end;
1240
+ fail(
1241
+ context,
1242
+ UNSUPPORTED_NOT_CONDITION,
1243
+ 'NOT in front of a condition is not supported. Write the opposite condition instead, e.g. use <> instead of =, > instead of <=, or NOT IN instead of NOT (... OR ...).',
1244
+ token.start,
1245
+ end,
1246
+ );
1247
+ }
1248
+ if (isKeyword(token, 'EXISTS')) {
1249
+ fail(
1250
+ context,
1251
+ UNSUPPORTED_SUBQUERY,
1252
+ 'EXISTS needs a query inside a query (subquery), which is not supported. Run that query on its own and filter with its result values directly.',
1253
+ token.start,
1254
+ isSymbol(peek(context, 1), '(') ? groupEnd(context, context.pos + 1) : token.end,
1255
+ );
1256
+ }
1257
+ if (isSymbol(token, '(')) {
1258
+ rejectSubquery(context);
1259
+ advance(context);
1260
+ const expression = parseOr(context);
1261
+ const close = peek(context);
1262
+ if (isSymbol(close, ')')) {
1263
+ advance(context);
1264
+ return expression;
1265
+ }
1266
+ if (close.type === 'eof') {
1267
+ fail(
1268
+ context,
1269
+ MISSING_CLOSING_PAREN,
1270
+ 'This bracket is never closed. Add a closing bracket ) at the end of the group.',
1271
+ token.start,
1272
+ token.end,
1273
+ );
1274
+ }
1275
+ return unexpected(
1276
+ context,
1277
+ 'Close the bracket with ) or join the conditions with AND or OR.',
1278
+ );
1279
+ }
1280
+ return parsePredicate(context);
1281
+ }
1282
+
1283
+ /**
1284
+ * Parses conditions joined by AND (binds tighter than OR).
1285
+ *
1286
+ * @param {object} context parse context
1287
+ * @returns {Expr} expression node
1288
+ */
1289
+ function parseAnd(context) {
1290
+ let left = parsePrimary(context);
1291
+ while (isKeyword(peek(context), 'AND')) {
1292
+ advance(context);
1293
+ const right = parsePrimary(context);
1294
+ left = { type: 'and', left, right, loc: makeLoc(context, left.loc.start, right.loc.end) };
1295
+ }
1296
+ return left;
1297
+ }
1298
+
1299
+ /**
1300
+ * Parses conditions joined by OR.
1301
+ *
1302
+ * @param {object} context parse context
1303
+ * @returns {Expr} expression node
1304
+ */
1305
+ function parseOr(context) {
1306
+ let left = parseAnd(context);
1307
+ while (isKeyword(peek(context), 'OR')) {
1308
+ advance(context);
1309
+ const right = parseAnd(context);
1310
+ left = { type: 'or', left, right, loc: makeLoc(context, left.loc.start, right.loc.end) };
1311
+ }
1312
+ return left;
1313
+ }
1314
+
1315
+ // ------------------------------------------------------------------------------------------
1316
+ // Statement
1317
+ // ------------------------------------------------------------------------------------------
1318
+
1319
+ /**
1320
+ * Parses the optional TOP clause.
1321
+ *
1322
+ * @param {object} context parse context
1323
+ * @returns {number|null} the row limit or null
1324
+ */
1325
+ function parseTop(context) {
1326
+ if (!isKeyword(peek(context), 'TOP')) {
1327
+ return null;
1328
+ }
1329
+ const topToken = advance(context);
1330
+ const isParenthesized = isSymbol(peek(context), '(');
1331
+ if (isParenthesized) {
1332
+ advance(context);
1333
+ }
1334
+ const token = peek(context);
1335
+ if (token.type !== 'number' || !INTEGER_PATTERN.test(token.value)) {
1336
+ fail(
1337
+ context,
1338
+ INVALID_TOP,
1339
+ 'TOP needs a whole number of rows, e.g. "SELECT TOP 10 ...".',
1340
+ topToken.start,
1341
+ token.type === 'eof' ? topToken.end : token.end,
1342
+ );
1343
+ }
1344
+ if (Number(token.value) === 0) {
1345
+ fail(
1346
+ context,
1347
+ INVALID_TOP,
1348
+ 'TOP 0 returns no rows. Remove TOP 0, or ask for at least one row, e.g. "SELECT TOP 10 ...".',
1349
+ topToken.start,
1350
+ token.end,
1351
+ );
1352
+ }
1353
+ advance(context);
1354
+ if (isParenthesized) {
1355
+ if (!isSymbol(peek(context), ')')) {
1356
+ unexpected(context, 'Close the bracket after the number, e.g. TOP (10).');
1357
+ }
1358
+ advance(context);
1359
+ }
1360
+ const after = peek(context);
1361
+ if (isKeyword(after, 'PERCENT') || isKeyword(after, 'WITH')) {
1362
+ fail(
1363
+ context,
1364
+ INVALID_TOP,
1365
+ `TOP ... ${after.value.toUpperCase()} is not supported. Use a plain number of rows, e.g. "SELECT TOP 10 ...".`,
1366
+ topToken.start,
1367
+ isKeyword(after, 'WITH') ? peek(context, 1).end : after.end,
1368
+ );
1369
+ }
1370
+ return Number(token.value);
1371
+ }
1372
+
1373
+ /**
1374
+ * Parses the column list.
1375
+ *
1376
+ * @param {object} context parse context
1377
+ * @returns {'*'|{name: string, loc: Loc}[]} columns
1378
+ */
1379
+ function parseColumns(context) {
1380
+ const first = peek(context);
1381
+ if (isKeyword(first, 'DISTINCT')) {
1382
+ fail(
1383
+ context,
1384
+ UNSUPPORTED_DISTINCT,
1385
+ 'DISTINCT is not supported. Select the rows without DISTINCT and remove duplicates in your code.',
1386
+ first.start,
1387
+ first.end,
1388
+ );
1389
+ }
1390
+ if (isSymbol(first, '*')) {
1391
+ advance(context);
1392
+ if (isSymbol(peek(context), ',')) {
1393
+ fail(
1394
+ context,
1395
+ UNSUPPORTED_STAR_WITH_COLUMNS,
1396
+ 'Use either * (all columns) or a list of column names, not both. Remove the * or the extra columns.',
1397
+ first.start,
1398
+ peek(context, 1).type === 'eof' ? peek(context).end : peek(context, 1).end,
1399
+ );
1400
+ }
1401
+ rejectAlias(context, first.start);
1402
+ return '*';
1403
+ }
1404
+ const columns = [];
1405
+ for (;;) {
1406
+ const token = peek(context);
1407
+ if (isSymbol(token, '*')) {
1408
+ fail(
1409
+ context,
1410
+ UNSUPPORTED_STAR_WITH_COLUMNS,
1411
+ 'Use either * (all columns) or a list of column names, not both. Remove the * or the extra columns.',
1412
+ token.start,
1413
+ token.end,
1414
+ );
1415
+ }
1416
+ rejectSubquery(context);
1417
+ const name = readName(context, 'column');
1418
+ rejectAlias(context, name.start);
1419
+ columns.push({ name: name.name, loc: makeLoc(context, name.start, name.end) });
1420
+ if (!isSymbol(peek(context), ',')) {
1421
+ return columns;
1422
+ }
1423
+ advance(context);
1424
+ }
1425
+ }
1426
+
1427
+ /**
1428
+ * Parses the FROM clause including the checks for joins, aliases and table hints.
1429
+ *
1430
+ * @param {object} context parse context
1431
+ * @returns {{name: string, loc: Loc}} data extension reference
1432
+ */
1433
+ function parseFrom(context) {
1434
+ const fromToken = peek(context);
1435
+ if (!isKeyword(fromToken, 'FROM')) {
1436
+ if (fromToken.type === 'eof') {
1437
+ fail(
1438
+ context,
1439
+ EXPECTED_FROM,
1440
+ 'The query has no FROM. Add "FROM" followed by the data extension name after the column list.',
1441
+ fromToken.start,
1442
+ fromToken.end,
1443
+ );
1444
+ }
1445
+ unexpected(
1446
+ context,
1447
+ 'Separate columns with commas and continue with FROM and the data extension name.',
1448
+ );
1449
+ }
1450
+ advance(context);
1451
+ const token = peek(context);
1452
+ if (isSymbol(token, '(')) {
1453
+ fail(
1454
+ context,
1455
+ UNSUPPORTED_SUBQUERY,
1456
+ 'Reading from a query inside a query (subquery) is not supported. Put the data extension name directly after FROM.',
1457
+ token.start,
1458
+ groupEnd(context, context.pos),
1459
+ );
1460
+ }
1461
+ const name = readName(context, 'data extension');
1462
+ const from = { name: name.name, loc: makeLoc(context, name.start, name.end) };
1463
+ if (name.name.startsWith('_')) {
1464
+ report(
1465
+ context,
1466
+ 'warning',
1467
+ SYSTEM_DATA_VIEW,
1468
+ `${name.name} looks like a system data view. System data views can only be read in Automation Studio queries, not as a data extension. Copy the data into a data extension with a query activity first and read that one.`,
1469
+ name.start,
1470
+ name.end,
1471
+ );
1472
+ }
1473
+ skipTableHint(context);
1474
+ rejectAlias(context, name.start);
1475
+ rejectJoin(context);
1476
+ return from;
1477
+ }
1478
+
1479
+ /**
1480
+ * Skips `WITH (NOLOCK)` style table hints, which make no difference for data extension reads.
1481
+ *
1482
+ * @param {object} context parse context
1483
+ */
1484
+ function skipTableHint(context) {
1485
+ const withToken = peek(context);
1486
+ if (!isKeyword(withToken, 'WITH') || !isSymbol(peek(context, 1), '(')) {
1487
+ return;
1488
+ }
1489
+ advance(context);
1490
+ const open = advance(context);
1491
+ let depth = 1;
1492
+ while (depth > 0) {
1493
+ const token = advance(context);
1494
+ if (token.type === 'eof') {
1495
+ fail(
1496
+ context,
1497
+ MISSING_CLOSING_PAREN,
1498
+ 'This bracket is never closed. Add a closing bracket ) after the table hint.',
1499
+ open.start,
1500
+ open.end,
1501
+ );
1502
+ }
1503
+ if (isSymbol(token, '(')) {
1504
+ depth++;
1505
+ } else if (isSymbol(token, ')')) {
1506
+ depth--;
1507
+ }
1508
+ }
1509
+ const end = context.tokens[context.pos - 1].end;
1510
+ report(
1511
+ context,
1512
+ 'info',
1513
+ TABLE_HINT_IGNORED,
1514
+ 'Table hints such as WITH (NOLOCK) have no effect here and are ignored.',
1515
+ withToken.start,
1516
+ end,
1517
+ );
1518
+ }
1519
+
1520
+ /**
1521
+ * Fails with UNSUPPORTED_JOIN when the current token starts a join or a comma-separated table.
1522
+ *
1523
+ * @param {object} context parse context
1524
+ */
1525
+ function rejectJoin(context) {
1526
+ const token = peek(context);
1527
+ let end;
1528
+ if (isSymbol(token, ',')) {
1529
+ end = peek(context, 1).type === 'eof' ? token.end : peek(context, 1).end;
1530
+ } else if (token.type === 'word' && (JOIN_WORDS.has(token.upper) || token.upper === 'APPLY')) {
1531
+ end = token.end;
1532
+ for (let ahead = 0; ahead < context.tokens.length; ahead++) {
1533
+ const candidate = peek(context, ahead);
1534
+ if (candidate.type !== 'word' || !JOIN_WORDS.has(candidate.upper)) {
1535
+ if (isKeyword(candidate, 'APPLY')) {
1536
+ end = candidate.end;
1537
+ }
1538
+ break;
1539
+ }
1540
+ end = candidate.end;
1541
+ }
1542
+ } else {
1543
+ return;
1544
+ }
1545
+ fail(
1546
+ context,
1547
+ UNSUPPORTED_JOIN,
1548
+ 'Combining several data extensions (JOIN) is not supported. Read one data extension per query and combine the results in your code.',
1549
+ token.start,
1550
+ end,
1551
+ );
1552
+ }
1553
+
1554
+ /**
1555
+ * Fails when the current token is GROUP BY or HAVING.
1556
+ *
1557
+ * @param {object} context parse context
1558
+ */
1559
+ function rejectGrouping(context) {
1560
+ const token = peek(context);
1561
+ if (isKeyword(token, 'GROUP')) {
1562
+ const by = peek(context, 1);
1563
+ fail(
1564
+ context,
1565
+ UNSUPPORTED_GROUP_BY,
1566
+ 'GROUP BY is not supported. Select the plain rows and group them in your code.',
1567
+ token.start,
1568
+ isKeyword(by, 'BY') ? by.end : token.end,
1569
+ );
1570
+ }
1571
+ if (isKeyword(token, 'HAVING')) {
1572
+ fail(
1573
+ context,
1574
+ UNSUPPORTED_HAVING,
1575
+ 'HAVING is not supported. Filter rows with WHERE, or filter grouped results in your code.',
1576
+ token.start,
1577
+ token.end,
1578
+ );
1579
+ }
1580
+ }
1581
+
1582
+ /**
1583
+ * Fails when the current token is UNION, EXCEPT or INTERSECT.
1584
+ *
1585
+ * @param {object} context parse context
1586
+ */
1587
+ function rejectSetOperator(context) {
1588
+ const token = peek(context);
1589
+ if (token.type === 'word' && SET_OPERATORS.has(token.upper)) {
1590
+ const following = peek(context, 1);
1591
+ fail(
1592
+ context,
1593
+ UNSUPPORTED_UNION,
1594
+ `${token.upper} (combining the results of several queries) is not supported. Run each query on its own and combine the results in your code.`,
1595
+ token.start,
1596
+ isKeyword(following, 'ALL') ? following.end : token.end,
1597
+ );
1598
+ }
1599
+ }
1600
+
1601
+ /**
1602
+ * Fails with UNSUPPORTED_OFFSET_FETCH when the current token starts `OFFSET … FETCH …` paging.
1603
+ *
1604
+ * @param {object} context parse context
1605
+ */
1606
+ function rejectOffsetFetch(context) {
1607
+ const token = peek(context);
1608
+ if (!isKeyword(token, 'OFFSET') && !(token.type === 'word' && token.upper === 'FETCH')) {
1609
+ return;
1610
+ }
1611
+ let end = token.end;
1612
+ for (let ahead = 0; ; ahead++) {
1613
+ const candidate = peek(context, ahead);
1614
+ if (candidate.type === 'eof' || isSymbol(candidate, ';')) {
1615
+ break;
1616
+ }
1617
+ end = candidate.end;
1618
+ }
1619
+ fail(
1620
+ context,
1621
+ UNSUPPORTED_OFFSET_FETCH,
1622
+ 'OFFSET … FETCH (skipping rows / paging) is not supported. Use TOP to limit the number of rows instead, e.g. "SELECT TOP 10 … ORDER BY …".',
1623
+ token.start,
1624
+ end,
1625
+ );
1626
+ }
1627
+
1628
+ /**
1629
+ * Parses the ORDER BY list, starting at ORDER.
1630
+ *
1631
+ * @param {object} context parse context
1632
+ * @returns {{column: string, direction: 'ASC'|'DESC', loc: Loc}[]} sort order
1633
+ */
1634
+ function parseOrderBy(context) {
1635
+ advance(context);
1636
+ if (!isKeyword(peek(context), 'BY')) {
1637
+ unexpected(context, 'ORDER must be followed by BY, e.g. "ORDER BY LastName".');
1638
+ }
1639
+ advance(context);
1640
+ const items = [];
1641
+ for (;;) {
1642
+ const token = peek(context);
1643
+ if (token.type === 'number') {
1644
+ fail(
1645
+ context,
1646
+ EXPECTED_IDENTIFIER,
1647
+ 'Sorting by column position (ORDER BY 1) is not supported. Write the column name instead.',
1648
+ token.start,
1649
+ token.end,
1650
+ );
1651
+ }
1652
+ const name = readName(context, 'column');
1653
+ let direction = 'ASC';
1654
+ let end = name.end;
1655
+ const directionToken = peek(context);
1656
+ if (isKeyword(directionToken, 'ASC') || isKeyword(directionToken, 'DESC')) {
1657
+ advance(context);
1658
+ direction = directionToken.upper;
1659
+ end = directionToken.end;
1660
+ }
1661
+ items.push({ column: name.name, direction, loc: makeLoc(context, name.start, end) });
1662
+ if (!isSymbol(peek(context), ',')) {
1663
+ return items;
1664
+ }
1665
+ advance(context);
1666
+ }
1667
+ }
1668
+
1669
+ /**
1670
+ * Parses one SELECT statement and checks that nothing but an optional ";" follows.
1671
+ *
1672
+ * @param {object} context parse context
1673
+ * @returns {SelectAst} statement node
1674
+ */
1675
+ function parseStatement(context) {
1676
+ const selectToken = peek(context);
1677
+ if (!isKeyword(selectToken, 'SELECT')) {
1678
+ const message =
1679
+ selectToken.type === 'word' && NON_SELECT_STATEMENTS.has(selectToken.upper)
1680
+ ? `Only SELECT queries can be converted, but this query starts with ${selectToken.upper}. Rewrite it as "SELECT ... FROM ...".`
1681
+ : `A query must start with SELECT, but this one starts with ${describe(context, selectToken)}. Write it as "SELECT ... FROM ...".`;
1682
+ fail(context, EXPECTED_SELECT, message, selectToken.start, selectToken.end);
1683
+ }
1684
+ advance(context);
1685
+ const top = parseTop(context);
1686
+ const columns = parseColumns(context);
1687
+ const from = parseFrom(context);
1688
+ rejectGrouping(context);
1689
+ let where = null;
1690
+ if (isKeyword(peek(context), 'WHERE')) {
1691
+ advance(context);
1692
+ where = parseOr(context);
1693
+ }
1694
+ rejectGrouping(context);
1695
+ rejectSetOperator(context);
1696
+ const orderBy = isKeyword(peek(context), 'ORDER') ? parseOrderBy(context) : [];
1697
+ rejectSetOperator(context);
1698
+ rejectOffsetFetch(context);
1699
+ const end = context.tokens[context.pos - 1].end;
1700
+ if (isSymbol(peek(context), ';')) {
1701
+ advance(context);
1702
+ }
1703
+ const rest = peek(context);
1704
+ if (rest.type !== 'eof') {
1705
+ if (isSymbol(context.tokens[context.pos - 1], ';')) {
1706
+ fail(
1707
+ context,
1708
+ UNSUPPORTED_MULTIPLE_STATEMENTS,
1709
+ 'Only one query at a time is supported. Remove everything after the first query or convert each query separately.',
1710
+ rest.start,
1711
+ context.text.length,
1712
+ );
1713
+ }
1714
+ unexpected(
1715
+ context,
1716
+ where
1717
+ ? 'Join conditions with AND or OR, and put ORDER BY at the end of the query.'
1718
+ : 'Continue with WHERE or ORDER BY, or end the query here.',
1719
+ );
1720
+ }
1721
+ return {
1722
+ type: 'select',
1723
+ top,
1724
+ columns,
1725
+ from,
1726
+ where,
1727
+ orderBy,
1728
+ loc: makeLoc(context, selectToken.start, end),
1729
+ };
1730
+ }
1731
+
1732
+ /**
1733
+ * Parses an Automation Studio / T-SQL style SELECT query. Never throws.
1734
+ *
1735
+ * @param {string} text the SQL query
1736
+ * @returns {{ast: SelectAst|null, messages: import('./messages.js').Message[]}} the AST (null
1737
+ * when there is an error) and all messages
1738
+ */
1739
+ export function parseSql(text) {
1740
+ const source = typeof text === 'string' ? text : '';
1741
+ const context = createContext(source);
1742
+ try {
1743
+ tokenize(context);
1744
+ if (peek(context).type === 'eof') {
1745
+ fail(
1746
+ context,
1747
+ EMPTY_INPUT,
1748
+ 'The query is empty. Write a query such as "SELECT * FROM MyDataExtension".',
1749
+ 0,
1750
+ source.length,
1751
+ );
1752
+ }
1753
+ const ast = parseStatement(context);
1754
+ return { ast, messages: context.messages };
1755
+ } catch (ex) {
1756
+ if (!(ex instanceof ParseStop)) {
1757
+ const isTooDeep = ex instanceof RangeError;
1758
+ report(
1759
+ context,
1760
+ 'error',
1761
+ isTooDeep ? NESTING_TOO_DEEP : INTERNAL_ERROR,
1762
+ isTooDeep
1763
+ ? 'The query has too many nested brackets to read. Remove brackets that are not needed.'
1764
+ : 'The query could not be read because of an unexpected problem in the parser. Simplify the query and try again.',
1765
+ 0,
1766
+ source.length,
1767
+ );
1768
+ }
1769
+ return { ast: null, messages: context.messages };
1770
+ }
1771
+ }