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,590 @@
1
+ /**
2
+ * Reads Engagement AMPscript data extension lookups back into the SQL AST of `parseSql`:
3
+ * `LookupRows`, `LookupOrderedRows` and `Lookup` (plus the CS variants, with a warning).
4
+ *
5
+ * The code is read as text; it is never executed. Never throws.
6
+ */
7
+
8
+ import { nextLikeInner, nextLikeWildcardMessage } from './clauses.js';
9
+ import { lookupRowsRepeatedFieldMessage, rsoRepeatedFieldMessage } from './emit-mcn.js';
10
+ import { SYNTAX_ERROR } from './messages.js';
11
+ import {
12
+ ARGUMENT_COUNT,
13
+ CASE_SENSITIVE_LOOKUP,
14
+ INVALID_ARGUMENT,
15
+ INVALID_COUNT,
16
+ INVALID_FILTER,
17
+ INVALID_FILTER_VALUE,
18
+ LIKE_MATCHES_ANYWHERE,
19
+ LOOKUP_FIRST_ROW_ONLY,
20
+ MULTIPLE_LOOKUPS,
21
+ NO_LOOKUP_FOUND,
22
+ UNKNOWN_FILTER_OPERATOR,
23
+ UNSUPPORTED_EXPRESSION,
24
+ VARIABLE_VALUE,
25
+ } from './messages.js';
26
+ import {
27
+ andChain,
28
+ createContext,
29
+ expressionEnd,
30
+ fail,
31
+ failUnclosedCall,
32
+ findAmpscriptRegions,
33
+ isPunct,
34
+ makeLoc,
35
+ makeValue,
36
+ parseOrderString,
37
+ readHeader,
38
+ rejectEmpty,
39
+ report,
40
+ runParser,
41
+ tokenAt,
42
+ tokenize,
43
+ } from './reverse-common.js';
44
+
45
+ /**
46
+ * @typedef {object} AmpLiteral
47
+ * @property {'string'|'number'} kind literal kind
48
+ * @property {string} value unescaped text or number text
49
+ * @property {number} start 0-based start offset
50
+ * @property {number} end 0-based exclusive end offset
51
+ */
52
+
53
+ const LOOKUP_FUNCTIONS = new Map(
54
+ Object.entries({
55
+ lookuprows: { target: 'ampscript-lookuprows', caseSensitive: false },
56
+ lookuprowscs: { target: 'ampscript-lookuprows', caseSensitive: true },
57
+ lookuporderedrows: { target: 'ampscript-lookuporderedrows', caseSensitive: false },
58
+ lookuporderedrowscs: { target: 'ampscript-lookuporderedrows', caseSensitive: true },
59
+ lookup: { target: 'ampscript-lookup', caseSensitive: false },
60
+ }),
61
+ );
62
+
63
+ // Marketing Cloud Next: LookupRows on a marketing object and RetrieveSalesforceObjects
64
+ const NEXT_FUNCTIONS = new Map(
65
+ Object.entries({
66
+ lookuprows: { target: 'ampscript-lookuprows-mo', caseSensitive: false },
67
+ retrievesalesforceobjects: { target: 'ampscript-rso', caseSensitive: false },
68
+ }),
69
+ );
70
+
71
+ // calls that exist in AMPscript but fail or are unproven in Next
72
+ const NEXT_REJECTED = new Map(
73
+ Object.entries({
74
+ lookuporderedrows:
75
+ 'LookupOrderedRows fails in Marketing Cloud Next. Use LookupRows and sort in your code.',
76
+ lookuporderedrowscs:
77
+ 'LookupOrderedRowsCS fails in Marketing Cloud Next. Use LookupRows and sort in your code.',
78
+ lookuprowscs:
79
+ 'LookupRowsCS is not proven in Marketing Cloud Next. Use LookupRows (it ignores case).',
80
+ }),
81
+ );
82
+
83
+ const RSO_OPERATORS = {
84
+ '=': '=',
85
+ '!=': '<>',
86
+ '<>': '<>',
87
+ '<': '<',
88
+ '<=': '<=',
89
+ '>': '>',
90
+ '>=': '>=',
91
+ };
92
+
93
+ /**
94
+ * Parses one argument: a string or number literal. Variables and nested calls are errors.
95
+ *
96
+ * @param {object} context parse context
97
+ * @returns {AmpLiteral} literal
98
+ */
99
+ function parseArgument(context) {
100
+ const token = tokenAt(context, context.pos);
101
+ if (token.type === 'string' || token.type === 'number') {
102
+ context.pos++;
103
+ return { kind: token.type, value: token.value, start: token.start, end: token.end };
104
+ }
105
+ if (isPunct(token, '-') && tokenAt(context, context.pos + 1).type === 'number') {
106
+ const number = tokenAt(context, context.pos + 1);
107
+ context.pos += 2;
108
+ return { kind: 'number', value: `-${number.value}`, start: token.start, end: number.end };
109
+ }
110
+ if (token.type === 'variable') {
111
+ fail(
112
+ context,
113
+ VARIABLE_VALUE,
114
+ `The variable ${token.value} can't be converted to SQL because its value is only known when the code runs. Replace it with the value itself.`,
115
+ token.start,
116
+ token.end,
117
+ );
118
+ }
119
+ if (token.type === 'ident' && isPunct(tokenAt(context, context.pos + 1), '(')) {
120
+ fail(
121
+ context,
122
+ UNSUPPORTED_EXPRESSION,
123
+ `The function call ${token.value}(…) can't be converted to SQL. Replace it with the value itself.`,
124
+ token.start,
125
+ expressionEnd(context, context.pos),
126
+ );
127
+ }
128
+ if (token.type === 'eof') {
129
+ return fail(
130
+ context,
131
+ SYNTAX_ERROR,
132
+ 'The code ends where an argument is expected.',
133
+ token.start,
134
+ token.end,
135
+ );
136
+ }
137
+ return fail(
138
+ context,
139
+ SYNTAX_ERROR,
140
+ `Expected an argument but found "${token.value}". Write text in double quotes or a number.`,
141
+ token.start,
142
+ token.end,
143
+ );
144
+ }
145
+
146
+ /**
147
+ * Parses an argument list starting at "(".
148
+ *
149
+ * @param {object} context parse context
150
+ * @returns {{args: AmpLiteral[], end: number}} arguments and the end offset of ")"
151
+ */
152
+ function parseArguments(context) {
153
+ const open = tokenAt(context, context.pos++);
154
+ const args = [];
155
+ for (;;) {
156
+ const token = tokenAt(context, context.pos);
157
+ if (isPunct(token, ')')) {
158
+ context.pos++;
159
+ return { args, end: token.end };
160
+ }
161
+ if (token.type === 'eof') {
162
+ failUnclosedCall(context, open);
163
+ }
164
+ args.push(parseArgument(context));
165
+ const separator = tokenAt(context, context.pos);
166
+ if (isPunct(separator, ',')) {
167
+ context.pos++;
168
+ } else if (separator.type === 'eof') {
169
+ failUnclosedCall(context, open);
170
+ } else if (!isPunct(separator, ')')) {
171
+ fail(
172
+ context,
173
+ UNSUPPORTED_EXPRESSION,
174
+ 'Only plain values can be converted here. Separate the arguments with commas and close the call with ).',
175
+ separator.start,
176
+ separator.end,
177
+ );
178
+ }
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Checks that an argument is non-empty text and returns it.
184
+ *
185
+ * @param {object} context parse context
186
+ * @param {AmpLiteral} literal argument
187
+ * @param {string} what what the argument is, for the message
188
+ * @returns {string} the text
189
+ */
190
+ function requireString(context, literal, what) {
191
+ if (literal.kind !== 'string' || !literal.value.trim()) {
192
+ fail(
193
+ context,
194
+ INVALID_ARGUMENT,
195
+ `${what} must be text in double quotes.`,
196
+ literal.start,
197
+ literal.end,
198
+ );
199
+ }
200
+ return literal.value;
201
+ }
202
+
203
+ /**
204
+ * Reads the column / value pairs into an AND chain of equals conditions.
205
+ *
206
+ * @param {object} context parse context
207
+ * @param {AmpLiteral[]} pairs alternating column names and values
208
+ * @param {boolean} [isNext] true for Marketing Cloud Next (a repeated field fails)
209
+ * @returns {object} expression node
210
+ */
211
+ function readPairs(context, pairs, isNext = false) {
212
+ const conditions = [];
213
+ const seen = new Set();
214
+ for (let index = 0; index < pairs.length; index += 2) {
215
+ const columnLiteral = pairs[index];
216
+ const valueLiteral = pairs[index + 1];
217
+ const column = requireString(context, columnLiteral, 'Each column name');
218
+ if (isNext && seen.has(column.toLowerCase())) {
219
+ fail(
220
+ context,
221
+ INVALID_FILTER,
222
+ `${lookupRowsRepeatedFieldMessage()} (${column}).`,
223
+ columnLiteral.start,
224
+ columnLiteral.end,
225
+ );
226
+ }
227
+ seen.add(column.toLowerCase());
228
+ conditions.push({
229
+ type: 'compare',
230
+ op: '=',
231
+ column,
232
+ value: makeValue(
233
+ context,
234
+ valueLiteral.value,
235
+ valueLiteral.start,
236
+ valueLiteral.end,
237
+ valueLiteral.kind === 'number',
238
+ ),
239
+ loc: makeLoc(context, columnLiteral.start, valueLiteral.end),
240
+ });
241
+ }
242
+ return andChain(context, conditions);
243
+ }
244
+
245
+ /**
246
+ * Checks the argument count of a lookup function.
247
+ *
248
+ * @param {object} context parse context
249
+ * @param {string} kind lower-case function name without CS
250
+ * @param {number} count number of arguments
251
+ * @param {object} callLoc location of the call
252
+ */
253
+ function checkArgumentCount(context, kind, count, callLoc) {
254
+ const fixed = { lookuprows: 1, lookuporderedrows: 3, lookup: 2 }[kind];
255
+ if (count < fixed + 2 || (count - fixed) % 2 !== 0) {
256
+ const usage = {
257
+ lookuprows: 'LookupRows("DE name", "Column", "value"[, "Column2", "value2" …])',
258
+ lookuporderedrows:
259
+ 'LookupOrderedRows("DE name", count, "Column ASC", "Column", "value"[, …])',
260
+ lookup: 'Lookup("DE name", "ReturnColumn", "Column", "value"[, …])',
261
+ }[kind];
262
+ fail(
263
+ context,
264
+ ARGUMENT_COUNT,
265
+ `Wrong number of arguments. Write it as ${usage}: every column name needs a value.`,
266
+ callLoc.start,
267
+ callLoc.end,
268
+ );
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Reads the row count of LookupOrderedRows (0 or -1 = all rows → no TOP).
274
+ *
275
+ * @param {object} context parse context
276
+ * @param {AmpLiteral} literal count argument
277
+ * @returns {number|null} TOP value
278
+ */
279
+ function readCount(context, literal) {
280
+ const text = literal.value.trim();
281
+ if (!/^-?\d+$/.test(text)) {
282
+ fail(
283
+ context,
284
+ INVALID_COUNT,
285
+ 'The row count must be a whole number (0 or -1 for all rows).',
286
+ literal.start,
287
+ literal.end,
288
+ );
289
+ }
290
+ const count = Number(text);
291
+ return count > 0 ? count : null;
292
+ }
293
+
294
+ /**
295
+ * Finds every lookup call.
296
+ *
297
+ * @param {object} context parse context
298
+ * @param {Map<string, object>} functions lookup functions by lower-case name
299
+ * @returns {{index: number, name: string}[]} calls in source order
300
+ */
301
+ function findCalls(context, functions) {
302
+ const calls = [];
303
+ for (const [index, token] of context.tokens.entries()) {
304
+ const name = token.type === 'ident' ? token.value.toLowerCase() : '';
305
+ if (functions.has(name) && isPunct(tokenAt(context, index + 1), '(')) {
306
+ calls.push({ index, name });
307
+ }
308
+ }
309
+ return calls;
310
+ }
311
+
312
+ /**
313
+ * Fails when the code uses a call that fails or is unproven in Next.
314
+ *
315
+ * @param {object} context parse context
316
+ */
317
+ function rejectNextCalls(context) {
318
+ for (const [index, token] of context.tokens.entries()) {
319
+ const reason = token.type === 'ident' && NEXT_REJECTED.get(token.value.toLowerCase());
320
+ if (reason && isPunct(tokenAt(context, index + 1), '(')) {
321
+ fail(context, UNSUPPORTED_EXPRESSION, reason, token.start, token.end);
322
+ }
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Reads the field list of RetrieveSalesforceObjects ("A,B") into column nodes.
328
+ *
329
+ * @param {object} context parse context
330
+ * @param {AmpLiteral} literal field list argument
331
+ * @returns {{name: string, loc: object}[]} columns
332
+ */
333
+ function readRsoFields(context, literal) {
334
+ const text = requireString(context, literal, 'The field list');
335
+ const isExact = context.text.slice(literal.start + 1, literal.end - 1) === text;
336
+ const columns = [];
337
+ let offset = 0;
338
+ for (const part of text.split(',')) {
339
+ const name = part.trim();
340
+ if (!name) {
341
+ fail(
342
+ context,
343
+ INVALID_ARGUMENT,
344
+ 'The field list has an empty entry. Separate the field names with single commas.',
345
+ literal.start,
346
+ literal.end,
347
+ );
348
+ }
349
+ const start = isExact ? literal.start + 1 + offset + part.indexOf(name) : literal.start;
350
+ columns.push({
351
+ name,
352
+ loc: makeLoc(context, start, isExact ? start + name.length : literal.end),
353
+ });
354
+ offset += part.length + 1;
355
+ }
356
+ return columns;
357
+ }
358
+
359
+ /**
360
+ * Reads the field / operator / value triplets of RetrieveSalesforceObjects into an AND chain.
361
+ * Next matches LIKE as "contains", so plain text such as `Ro%` becomes `%Ro%` with a warning;
362
+ * `_`, `[` or `%` inside the text fail. A field used twice fails (no rows in Next).
363
+ *
364
+ * @param {object} context parse context
365
+ * @param {AmpLiteral[]} triplets alternating field, operator and value
366
+ * @returns {object} expression node
367
+ */
368
+ function readTriplets(context, triplets) {
369
+ const conditions = [];
370
+ const seen = new Set();
371
+ for (let index = 0; index < triplets.length; index += 3) {
372
+ const [columnLiteral, operatorLiteral, valueLiteral] = triplets.slice(index, index + 3);
373
+ const column = requireString(context, columnLiteral, 'Each field name');
374
+ if (seen.has(column.toLowerCase())) {
375
+ fail(
376
+ context,
377
+ INVALID_FILTER,
378
+ rsoRepeatedFieldMessage(column),
379
+ columnLiteral.start,
380
+ columnLiteral.end,
381
+ );
382
+ }
383
+ seen.add(column.toLowerCase());
384
+ const operator = requireString(context, operatorLiteral, 'Each operator').trim();
385
+ const value = makeValue(
386
+ context,
387
+ valueLiteral.value,
388
+ valueLiteral.start,
389
+ valueLiteral.end,
390
+ valueLiteral.kind === 'number',
391
+ );
392
+ const loc = makeLoc(context, columnLiteral.start, valueLiteral.end);
393
+ if (operator.toUpperCase() === 'LIKE') {
394
+ const parts = nextLikeInner(value.value);
395
+ if (!parts) {
396
+ fail(
397
+ context,
398
+ INVALID_FILTER_VALUE,
399
+ nextLikeWildcardMessage(value.value),
400
+ valueLiteral.start,
401
+ valueLiteral.end,
402
+ );
403
+ }
404
+ const { inner } = parts;
405
+ if (!parts.isContains) {
406
+ report(
407
+ context,
408
+ 'warning',
409
+ LIKE_MATCHES_ANYWHERE,
410
+ `Next matches LIKE as "contains" and ignores wildcards, so "${value.value}" is converted as '%${inner}%'.`,
411
+ valueLiteral.start,
412
+ valueLiteral.end,
413
+ );
414
+ }
415
+ const pattern = { ...value, kind: 'string', value: `%${inner}%` };
416
+ conditions.push({ type: 'like', column, pattern, loc });
417
+ continue;
418
+ }
419
+ const op = RSO_OPERATORS[operator];
420
+ if (!op) {
421
+ fail(
422
+ context,
423
+ UNKNOWN_FILTER_OPERATOR,
424
+ `"${operator}" is not an operator of RetrieveSalesforceObjects. Use =, !=, <, <=, >, >= or LIKE.`,
425
+ operatorLiteral.start,
426
+ operatorLiteral.end,
427
+ );
428
+ }
429
+ conditions.push({ type: 'compare', op, column, value, loc });
430
+ }
431
+ return andChain(context, conditions);
432
+ }
433
+
434
+ /**
435
+ * Builds the AST of a RetrieveSalesforceObjects call.
436
+ *
437
+ * @param {object} context parse context
438
+ * @param {AmpLiteral[]} args arguments
439
+ * @param {object} callLoc location of the call
440
+ * @returns {object} SELECT AST
441
+ */
442
+ function rsoAst(context, args, callLoc) {
443
+ if (args.length < 5 || (args.length - 2) % 3 !== 0) {
444
+ fail(
445
+ context,
446
+ ARGUMENT_COUNT,
447
+ 'Wrong number of arguments. Write it as RetrieveSalesforceObjects("Object", "Field1,Field2", "Field", "=", "value"[, …]): every condition needs a field, an operator and a value.',
448
+ callLoc.start,
449
+ callLoc.end,
450
+ );
451
+ }
452
+ const name = requireString(context, args[0], 'The object name');
453
+ return {
454
+ type: 'select',
455
+ top: null,
456
+ columns: readRsoFields(context, args[1]),
457
+ from: { name, loc: makeLoc(context, args[0].start, args[0].end) },
458
+ where: readTriplets(context, args.slice(2)),
459
+ orderBy: [],
460
+ loc: callLoc,
461
+ };
462
+ }
463
+
464
+ /**
465
+ * Parses the first lookup call and builds the AST.
466
+ *
467
+ * @param {object} context parse context
468
+ * @param {object} meta meta data (mutated)
469
+ * @param {boolean} isNext true for Marketing Cloud Next
470
+ * @returns {object} SELECT AST
471
+ */
472
+ function parseProgram(context, meta, isNext) {
473
+ const header = readHeader(context);
474
+ if (isNext) {
475
+ rejectNextCalls(context);
476
+ }
477
+ const functions = isNext ? NEXT_FUNCTIONS : LOOKUP_FUNCTIONS;
478
+ const calls = findCalls(context, functions);
479
+ if (calls.length === 0) {
480
+ fail(
481
+ context,
482
+ NO_LOOKUP_FOUND,
483
+ isNext
484
+ ? 'No supported lookup was found. Paste a LookupRows or RetrieveSalesforceObjects call.'
485
+ : 'No supported lookup was found. Paste a LookupRows, LookupOrderedRows or Lookup call.',
486
+ 0,
487
+ context.text.length,
488
+ );
489
+ }
490
+ const call = calls[0];
491
+ const callToken = tokenAt(context, call.index);
492
+ if (calls.length > 1) {
493
+ const second = tokenAt(context, calls[1].index);
494
+ report(
495
+ context,
496
+ 'warning',
497
+ MULTIPLE_LOOKUPS,
498
+ 'The code contains more than one lookup; only the first one is converted.',
499
+ second.start,
500
+ second.end,
501
+ );
502
+ }
503
+ context.pos = call.index + 1;
504
+ const { args, end } = parseArguments(context);
505
+ const callLoc = makeLoc(context, callToken.start, end);
506
+ const definition = functions.get(call.name);
507
+ const kind = call.name.replace(/cs$/, '');
508
+ meta.target = definition.target;
509
+ if (kind === 'retrievesalesforceobjects') {
510
+ const ast = rsoAst(context, args, callLoc);
511
+ meta.deName = ast.from.name;
512
+ return ast;
513
+ }
514
+ if (definition.caseSensitive) {
515
+ report(
516
+ context,
517
+ 'warning',
518
+ CASE_SENSITIVE_LOOKUP,
519
+ `${callToken.value} compares the values case-sensitively; SQL in Marketing Cloud compares text without regard to case, so the result can contain more rows.`,
520
+ callToken.start,
521
+ callToken.end,
522
+ );
523
+ }
524
+ checkArgumentCount(context, kind, args.length, callLoc);
525
+ const name = requireString(context, args[0], 'The data extension name');
526
+ meta.deName = name;
527
+ if (header.key) {
528
+ meta.deKey = header.key;
529
+ }
530
+ let columns = header.columns ?? '*';
531
+ let top = null;
532
+ let orderBy = [];
533
+ let pairs = args.slice(1);
534
+ if (kind === 'lookuporderedrows') {
535
+ top = readCount(context, args[1]);
536
+ requireString(context, args[2], 'The sort order');
537
+ orderBy = parseOrderString(context, args[2]);
538
+ pairs = args.slice(3);
539
+ } else if (kind === 'lookup') {
540
+ const column = requireString(context, args[1], 'The column to return');
541
+ columns = [{ name: column, loc: makeLoc(context, args[1].start, args[1].end) }];
542
+ pairs = args.slice(2);
543
+ report(
544
+ context,
545
+ 'info',
546
+ LOOKUP_FIRST_ROW_ONLY,
547
+ 'Lookup returns the value of the first matching row only; the SQL query returns every matching row.',
548
+ callLoc.start,
549
+ callLoc.end,
550
+ );
551
+ }
552
+ return {
553
+ type: 'select',
554
+ top,
555
+ columns,
556
+ from: { name, loc: makeLoc(context, args[0].start, args[0].end) },
557
+ where: readPairs(context, pairs, isNext),
558
+ orderBy,
559
+ loc: callLoc,
560
+ };
561
+ }
562
+
563
+ /**
564
+ * Reads an AMPscript data extension lookup back into the SQL AST. Never throws.
565
+ *
566
+ * Accepted: `%%[ … ]%%` / `%%= … =%%` blocks or bare statements containing
567
+ * `LookupRows("Name", "Col", "v"[, …])`, `LookupOrderedRows("Name", count, "Col ASC", "Col", "v"[, …])`
568
+ * or `Lookup("Name", "ReturnCol", "Col", "v"[, …])` (also the CS variants). The first lookup is
569
+ * converted; loops and output code around it are ignored. A `/* SQL: SELECT a, b *\/` comment
570
+ * supplies the column list LookupRows cannot carry.
571
+ *
572
+ * With `{ platform: 'mcn' }` the Marketing Cloud Next calls are read instead: `LookupRows` on a
573
+ * marketing object and `RetrieveSalesforceObjects("Object", "F1,F2", "Field", "op", "v"[, …])`;
574
+ * LookupOrderedRows and the CS variants are errors there.
575
+ *
576
+ * @param {string} text AMPscript code
577
+ * @param {{platform?: 'mce'|'mcn'}} [options] platform (default 'mce')
578
+ * @returns {{ast: object|null, messages: import('./messages.js').Message[], meta: {target: string|null, deName?: string, deKey?: string}}} AST (null on error), messages and meta data
579
+ */
580
+ export function parseAmpscript(text, options = {}) {
581
+ const source = typeof text === 'string' ? text : '';
582
+ const context = createContext(source);
583
+ const meta = { target: null };
584
+ const ast = runParser(context, () => {
585
+ tokenize(context, 'ampscript', findAmpscriptRegions(source));
586
+ rejectEmpty(context);
587
+ return parseProgram(context, meta, options.platform === 'mcn');
588
+ });
589
+ return { ast, messages: context.messages, meta };
590
+ }