sfmc-sql-converter 0.0.0-stage → 0.1.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,1330 @@
1
+ /**
2
+ * Marketing Cloud Engagement emitters: turn a parsed SELECT (see `parseSql`) into SSJS or
3
+ * AMPscript that reads the same rows from a data extension.
4
+ *
5
+ * Every emitter returns either `{ unavailable: '<plain reason>' }` when the target cannot
6
+ * express the query, or `{ code, spans, messages, dropped }`:
7
+ * - `spans` — where each clause (see `collectClauses`) ends up in `code`;
8
+ * - `messages` — warnings / info for this target only (e.g. `ORDER_BY_DROPPED`), located in
9
+ * the SQL text;
10
+ * - `dropped` — ids of clauses the target leaves out.
11
+ *
12
+ * Emitted values are always strings. Nothing here evaluates or runs code.
13
+ */
14
+
15
+ import {
16
+ CodeWriter,
17
+ collectClauses,
18
+ conditionsOf,
19
+ isContainsPattern,
20
+ likeFilterValue,
21
+ } from './clauses.js';
22
+ import {
23
+ EMPTY_STRING_AS_SPACE,
24
+ FIRST_BATCH_ONLY,
25
+ LIKE_CHECKED_IN_SCRIPT,
26
+ LOOKUP_FIRST_ROW_ONLY,
27
+ ORDER_BY_DROPPED,
28
+ TOP_ABOVE_LOOKUP_LIMIT,
29
+ TOP_DROPPED,
30
+ createMessage,
31
+ } from './messages.js';
32
+ import { formatName } from './print-sql.js';
33
+
34
+ /**
35
+ * @typedef {import('./sql-parser.js').SelectAst} SelectAst
36
+ * @typedef {import('./clauses.js').Span} Span
37
+ * @typedef {import('./messages.js').Message} Message
38
+ */
39
+
40
+ /**
41
+ * @typedef {object} EmitOptions
42
+ * @property {string} [deKey] external key of the data extension (defaults to its name)
43
+ * @property {string[]} [columns] column names that `SELECT *` stands for
44
+ * @property {{fields: {name: string}[]}} [schema] data extension fields (used for `*` when
45
+ * `columns` is not given)
46
+ * @property {{rowsAsObjects?: boolean, paging?: boolean}} [output] WSProxy output options:
47
+ * `rowsAsObjects` (default true) adds a helper that turns each result into a plain object;
48
+ * `paging` (default false) adds a loop that reads every batch
49
+ * @property {string} [sourceText] the SQL text the AST came from (locates TOP for messages)
50
+ */
51
+
52
+ /**
53
+ * @typedef {object} EmitResult
54
+ * @property {string} code generated code
55
+ * @property {Span[]} spans clause spans in `code`
56
+ * @property {Message[]} messages target-specific messages
57
+ * @property {string[]} dropped ids of clauses the target left out
58
+ */
59
+
60
+ const SSJS_START = '<script runat="server">\nPlatform.Load("core", "1.1.1");\n';
61
+ const SSJS_END = '</script>';
62
+ const INDENT = ' '.repeat(4);
63
+ const LINE_SEPARATOR = String.fromCodePoint(0x20_28);
64
+ const PARAGRAPH_SEPARATOR = String.fromCodePoint(0x20_29);
65
+ const LINE_BREAKS = new RegExp(`[\r\n${LINE_SEPARATOR}${PARAGRAPH_SEPARATOR}]+`, 'g');
66
+
67
+ const COMMENT_ESCAPES = { '~': '~~', '"': '~q', '\\': '~b' };
68
+
69
+ const SIMPLE_OPERATORS = {
70
+ '=': 'equals',
71
+ '<>': 'notEquals',
72
+ '>': 'greaterThan',
73
+ '>=': 'greaterThanOrEqual',
74
+ '<': 'lessThan',
75
+ '<=': 'lessThanOrEqual',
76
+ };
77
+
78
+ /**
79
+ * SSJS helper (ES3-safe: `var` only, no arrow functions, no regex literals) that checks a value
80
+ * against a SQL LIKE pattern exactly: anchored, case-insensitive, `%` = any text, `_` = one
81
+ * character, `[…]` / `[^…]` = one character of a set (so `[%]` is a literal %). NULL never
82
+ * matches; trailing spaces of the value are ignored like in SQL.
83
+ */
84
+ export const SQL_LIKE_HELPER = [
85
+ 'function sqlLike(value, pattern) {',
86
+ ' if (value === null || value === undefined) {',
87
+ ' return false;',
88
+ ' }',
89
+ // Case-insensitive by lower-casing both sides: the engine ignores the flags argument of
90
+ // new RegExp(source, "i") (proven live), and the pattern is dynamic, so no regex literal.
91
+ ' var text = String(value).replace(new RegExp(" +$"), "").toLowerCase();',
92
+ ' pattern = String(pattern).toLowerCase();',
93
+ ' var source = "^";',
94
+ ' var i = 0;',
95
+ ' while (i < pattern.length) {',
96
+ ' var c = pattern.charAt(i);',
97
+ ' var close = c === "[" ? pattern.indexOf("]", i + 1) : -1;',
98
+ ' if (close > i + 1) {',
99
+ ' var body = pattern.substring(i + 1, close);',
100
+ ' var negated = body.charAt(0) === "^";',
101
+ ' if (negated) {',
102
+ ' body = body.substring(1);',
103
+ ' }',
104
+ String.raw` source += "[" + (negated ? "^" : "") + body.replace(new RegExp("[\\\\^]", "g"), "\\$&") + "]";`,
105
+ ' i = close + 1;',
106
+ ' continue;',
107
+ ' }',
108
+ ' if (c === "%") {',
109
+ String.raw` source += "[\\s\\S]*";`,
110
+ ' } else if (c === "_") {',
111
+ String.raw` source += "[\\s\\S]";`,
112
+ // Regex specials and the backslash are built from char codes: a string literal ending in an
113
+ // escaped backslash ("\\") makes the CloudPage reject the whole page (HTTP 422, proven live).
114
+ ' } else if (String.fromCharCode(92, 94, 36, 46, 42, 43, 63, 40, 41, 91, 93, 123, 125, 124, 47).indexOf(c) > -1) {',
115
+ ' source += String.fromCharCode(92) + c;',
116
+ ' } else {',
117
+ ' source += c;',
118
+ ' }',
119
+ ' i++;',
120
+ ' }',
121
+ ' return new RegExp(source + "$").test(text);',
122
+ '}',
123
+ '',
124
+ ].join('\n');
125
+
126
+ // the six characters backslash, u, 0, 0, 5, C: a backslash written as a unicode escape
127
+ export const BACKSLASH_ESCAPE = ['\\', 'u005C'].join('');
128
+ const AMPSCRIPT_LOOP_VARIABLES = new Set(['rows', 'row', 'rowcount', 'i']);
129
+ // LookupRows / LookupOrderedRows return at most this many rows
130
+ const LOOKUP_ROW_LIMIT = 2000;
131
+
132
+ // ------------------------------------------------------------------------------------------
133
+ // Literals and shared helpers
134
+ // ------------------------------------------------------------------------------------------
135
+
136
+ /**
137
+ * Formats text as a double-quoted SSJS string literal (safe inside a `<script>` block). A
138
+ * backslash is written as the unicode escape of code 5C (see BACKSLASH_ESCAPE), never as two
139
+ * backslashes: a string literal ending in an escaped backslash makes the CloudPage reject the
140
+ * whole page (HTTP 422, proven live).
141
+ *
142
+ * @param {string} text the text
143
+ * @returns {string} string literal
144
+ */
145
+ export function jsString(text) {
146
+ // JSON escapes are two-character pairs read left to right, so every double backslash found
147
+ // here is one escaped backslash, and `<` is never the second character of an escape.
148
+ return JSON.stringify(String(text))
149
+ .replaceAll(/\\\\|<\//g, (match) => (match === '</' ? String.raw`<\/` : BACKSLASH_ESCAPE))
150
+ .replaceAll(LINE_SEPARATOR, String.raw`\u2028`)
151
+ .replaceAll(PARAGRAPH_SEPARATOR, String.raw`\u2029`);
152
+ }
153
+
154
+ /**
155
+ * Makes a name safe inside a header comment. A comment must hold no backslash and no double
156
+ * quote (the CloudPage pre-reader treats `"` as a string start even inside a comment) and no
157
+ * sequence that ends the comment, the script block or an AMPscript block. `~` is the escape
158
+ * character: `~` → `~~`, `"` → `~q`, a backslash → `~b`, and a `~` is put into `</`, `*\/`,
159
+ * `]%%`, `=%%`, `%%[` and `%%=` (`<~/`, `*~/`, `]~%%`, `=~%%`, `%~%[`, `%~%=`).
160
+ * `decodeCommentText` in reverse-common.js undoes exactly this.
161
+ *
162
+ * @param {string} text name or comment text
163
+ * @returns {string} safe text on one line
164
+ */
165
+ export function commentText(text) {
166
+ return oneLine(String(text))
167
+ .replaceAll(/[~"\\]/g, (character) => COMMENT_ESCAPES[character])
168
+ .replaceAll('</', '<~/')
169
+ .replaceAll('*/', '*~/')
170
+ .replaceAll(']%%', ']~%%')
171
+ .replaceAll('=%%', '=~%%')
172
+ .replaceAll('%%[', '%~%[')
173
+ .replaceAll('%%=', '%~%=');
174
+ }
175
+
176
+ /**
177
+ * Formats text as a double-quoted AMPscript string literal (`"` doubled).
178
+ *
179
+ * @param {string} text the text
180
+ * @returns {string} string literal
181
+ */
182
+ export function ampString(text) {
183
+ return `"${String(text).replaceAll('"', '""')}"`;
184
+ }
185
+
186
+ /**
187
+ * Makes text safe for a single-line comment.
188
+ *
189
+ * @param {string} text the text
190
+ * @returns {string} text without line breaks
191
+ */
192
+ function oneLine(text) {
193
+ return text.replaceAll(LINE_BREAKS, ' ');
194
+ }
195
+
196
+ /**
197
+ * Collects what every emitter needs: clause ids, names and the column list.
198
+ *
199
+ * @param {SelectAst} ast statement
200
+ * @param {EmitOptions} options options
201
+ * @returns {{idOf: Map<object, string>, clauses: object[], deName: string, deKey: string,
202
+ * columns: {name: string, clauseId?: string}[]|null}} context; `columns` is null for `*`
203
+ * without a known column list
204
+ */
205
+ function prepare(ast, options) {
206
+ const { clauses, idOf } = collectClauses(ast, options.sourceText);
207
+ let columns = null;
208
+ if (Array.isArray(ast.columns)) {
209
+ columns = ast.columns.map((column) => ({
210
+ name: column.name,
211
+ clauseId: idOf.get(column),
212
+ }));
213
+ } else if (options.columns?.length) {
214
+ columns = options.columns.map((name) => ({ name }));
215
+ } else if (options.schema?.fields?.length) {
216
+ columns = options.schema.fields.map((field) => ({ name: field.name }));
217
+ }
218
+ return {
219
+ idOf,
220
+ clauses,
221
+ deName: ast.from.name,
222
+ deKey: options.deKey || ast.from.name,
223
+ columns,
224
+ };
225
+ }
226
+
227
+ /**
228
+ * Builds the location that covers all ORDER BY items.
229
+ *
230
+ * @param {SelectAst} ast statement
231
+ * @returns {object} location
232
+ */
233
+ function orderByLoc(ast) {
234
+ const first = ast.orderBy[0].loc;
235
+ const last = ast.orderBy.at(-1).loc;
236
+ return {
237
+ start: first.start,
238
+ end: last.end,
239
+ line: first.line,
240
+ column: first.column,
241
+ endLine: last.endLine,
242
+ endColumn: last.endColumn,
243
+ };
244
+ }
245
+
246
+ /**
247
+ * Records ORDER BY / TOP as dropped, with a warning each.
248
+ *
249
+ * @param {SelectAst} ast statement
250
+ * @param {object[]} clauses clauses from `collectClauses`
251
+ * @param {{orderBy?: boolean, top?: boolean}} drop which clauses the target leaves out
252
+ * @param {string} label target name used in the message
253
+ * @returns {{messages: Message[], dropped: string[]}} warnings and dropped clause ids
254
+ */
255
+ function dropClauses(ast, clauses, drop, label) {
256
+ const messages = [];
257
+ const dropped = [];
258
+ if (drop.top && ast.top !== null && ast.top !== undefined) {
259
+ const topClause = clauses.find((clause) => clause.clauseId === 'top');
260
+ messages.push(
261
+ createMessage(
262
+ 'warning',
263
+ TOP_DROPPED,
264
+ `${label} cannot limit the number of rows, so TOP ${ast.top} is left out. Stop after ${ast.top} rows in your code, or use LookupOrderedRows.`,
265
+ topClause?.loc ?? ast.loc,
266
+ ),
267
+ );
268
+ dropped.push('top');
269
+ }
270
+ if (drop.orderBy && ast.orderBy?.length) {
271
+ messages.push(
272
+ createMessage(
273
+ 'warning',
274
+ ORDER_BY_DROPPED,
275
+ `${label} cannot sort rows, so ORDER BY is left out. Sort the rows in your code, or use LookupOrderedRows.`,
276
+ orderByLoc(ast),
277
+ ),
278
+ );
279
+ for (const clause of clauses) {
280
+ if (clause.kind === 'order') {
281
+ dropped.push(clause.clauseId);
282
+ }
283
+ }
284
+ }
285
+ return { messages, dropped };
286
+ }
287
+
288
+ /**
289
+ * Finishes an emitter result: sorts spans by position.
290
+ *
291
+ * @param {CodeWriter} out writer
292
+ * @param {{messages: Message[], dropped: string[]}} extra messages and dropped clauses
293
+ * @returns {EmitResult} result
294
+ */
295
+ function finish(out, extra) {
296
+ out.spans.sort((a, b) => a.start - b.start || a.end - b.end);
297
+ return { code: out.code, spans: out.spans, messages: extra.messages, dropped: extra.dropped };
298
+ }
299
+
300
+ /**
301
+ * Writes `// SQL: SELECT a, b` with each column marked.
302
+ *
303
+ * @param {CodeWriter} out writer
304
+ * @param {{name: string, clauseId?: string}[]} columns selected columns
305
+ * @param {'line'|'block'} [style] `// …` (SSJS) or `/* … *\/` (AMPscript)
306
+ */
307
+ function writeSelectComment(out, columns, style = 'line') {
308
+ out.write(style === 'block' ? '/* SQL: SELECT ' : '// SQL: SELECT ');
309
+ for (const [index, column] of columns.entries()) {
310
+ const name = commentText(formatName(column.name));
311
+ out.write(index ? ', ' : '').mark(column.clauseId, name);
312
+ }
313
+ out.write(style === 'block' ? ' */\n' : '\n');
314
+ }
315
+
316
+ /**
317
+ * Writes `// SQL: NOT IN` when the query has a NOT IN condition, so the reverse parser folds
318
+ * the notEquals chain back into NOT IN.
319
+ *
320
+ * @param {CodeWriter} out writer
321
+ * @param {SelectAst} ast statement
322
+ */
323
+ function writeNotInMarker(out, ast) {
324
+ if (conditionsOf(ast.where).some((expr) => expr.type === 'in' && expr.negated)) {
325
+ out.write('// SQL: NOT IN\n');
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Writes `// SQL: FROM [Name] (external key Key)`.
331
+ *
332
+ * @param {CodeWriter} out writer
333
+ * @param {string} deName data extension name
334
+ * @param {string} deKey external key
335
+ */
336
+ function writeFromComment(out, deName, deKey) {
337
+ out.write('// SQL: FROM ').mark(
338
+ 'from',
339
+ commentText(`[${deName.replaceAll(']', ']]')}] (external key ${deKey})`),
340
+ );
341
+ out.write('\n');
342
+ }
343
+
344
+ // ------------------------------------------------------------------------------------------
345
+ // SSJS filter objects (WSProxy and Rows.Retrieve share the same shape)
346
+ // ------------------------------------------------------------------------------------------
347
+
348
+ /**
349
+ * Writes one SimpleFilterPart object literal.
350
+ *
351
+ * @param {CodeWriter} out writer
352
+ * @param {string} property column
353
+ * @param {string} operator SimpleOperator value
354
+ * @param {string|string[]} value filter value (array for IN / between)
355
+ * @param {string} indent indentation of the closing brace
356
+ */
357
+ function writeSimplePart(out, property, operator, value, indent) {
358
+ const inner = indent + INDENT;
359
+ const valueText = Array.isArray(value)
360
+ ? `[${value.map((item) => jsString(item)).join(', ')}]`
361
+ : jsString(value);
362
+ out.write(
363
+ `{\n${inner}Property: ${jsString(property)},\n${inner}SimpleOperator: ${jsString(operator)},\n${inner}Value: ${valueText}\n${indent}}`,
364
+ );
365
+ }
366
+
367
+ /**
368
+ * Writes a ComplexFilterPart joining two parts.
369
+ *
370
+ * @param {CodeWriter} out writer
371
+ * @param {string} logical "AND" or "OR"
372
+ * @param {(indent: string) => void} writeLeft writes the left operand
373
+ * @param {(indent: string) => void} writeRight writes the right operand
374
+ * @param {string} indent indentation of the closing brace
375
+ */
376
+ function writeComplexPart(out, logical, writeLeft, writeRight, indent) {
377
+ const inner = indent + INDENT;
378
+ out.write(`{\n${inner}LeftOperand: `);
379
+ writeLeft(inner);
380
+ out.write(`,\n${inner}LogicalOperator: ${jsString(logical)},\n${inner}RightOperand: `);
381
+ writeRight(inner);
382
+ out.write(`\n${indent}}`);
383
+ }
384
+
385
+ /**
386
+ * Writes `NOT IN (a, b, …)` as an AND chain of notEquals parts.
387
+ *
388
+ * @param {CodeWriter} out writer
389
+ * @param {string} column column
390
+ * @param {string[]} values values
391
+ * @param {string} indent indentation
392
+ */
393
+ function writeNotInChain(out, column, values, indent) {
394
+ if (values.length === 1) {
395
+ writeSimplePart(out, column, 'notEquals', values[0], indent);
396
+ return;
397
+ }
398
+ writeComplexPart(
399
+ out,
400
+ 'AND',
401
+ (inner) => writeNotInChain(out, column, values.slice(0, -1), inner),
402
+ (inner) => writeSimplePart(out, column, 'notEquals', values.at(-1), inner),
403
+ indent,
404
+ );
405
+ }
406
+
407
+ /**
408
+ * Turns an empty compare value into a single space: the filter rejects an empty Value, and
409
+ * `" "` finds the same rows because trailing spaces are ignored.
410
+ *
411
+ * @param {string} text compare value
412
+ * @returns {string} filter value
413
+ */
414
+ function filterText(text) {
415
+ return text === '' ? ' ' : text;
416
+ }
417
+
418
+ /**
419
+ * Writes a single condition as a filter part.
420
+ *
421
+ * @param {CodeWriter} out writer
422
+ * @param {object} expr condition node
423
+ * @param {string} indent indentation
424
+ * @param {Set.<object>} checked LIKE nodes whose pattern is checked in the script
425
+ */
426
+ function writeCondition(out, expr, indent, checked) {
427
+ switch (expr.type) {
428
+ case 'compare': {
429
+ writeSimplePart(
430
+ out,
431
+ expr.column,
432
+ SIMPLE_OPERATORS[expr.op],
433
+ filterText(expr.value.value),
434
+ indent,
435
+ );
436
+ break;
437
+ }
438
+ case 'like': {
439
+ const pattern = expr.pattern.value;
440
+ const value = checked.has(expr) ? likeFilterValue(pattern) : pattern;
441
+ writeSimplePart(out, expr.column, 'like', value, indent);
442
+ break;
443
+ }
444
+ case 'in': {
445
+ const values = expr.values.map((value) => filterText(value.value));
446
+ if (expr.negated) {
447
+ writeNotInChain(out, expr.column, values, indent);
448
+ } else {
449
+ writeSimplePart(out, expr.column, 'IN', values, indent);
450
+ }
451
+ break;
452
+ }
453
+ case 'between': {
454
+ writeSimplePart(out, expr.column, 'between', [expr.low.value, expr.high.value], indent);
455
+ break;
456
+ }
457
+ case 'null': {
458
+ writeSimplePart(out, expr.column, expr.negated ? 'isNotNull' : 'isNull', '', indent);
459
+ break;
460
+ }
461
+ default: {
462
+ throw new TypeError(`Unknown condition type: ${expr.type}`);
463
+ }
464
+ }
465
+ }
466
+
467
+ /**
468
+ * Writes a WHERE tree as nested SimpleFilterPart / ComplexFilterPart object literals.
469
+ *
470
+ * @param {CodeWriter} out writer
471
+ * @param {object} expr expression node
472
+ * @param {Map<object, string>} idOf node → clause id
473
+ * @param {string} indent indentation of the closing brace
474
+ * @param {Set.<object>} checked LIKE nodes whose pattern is checked in the script
475
+ */
476
+ function writeFilter(out, expr, idOf, indent, checked) {
477
+ if (expr.type === 'and' || expr.type === 'or') {
478
+ writeComplexPart(
479
+ out,
480
+ expr.type.toUpperCase(),
481
+ (inner) => writeFilter(out, expr.left, idOf, inner, checked),
482
+ (inner) => writeFilter(out, expr.right, idOf, inner, checked),
483
+ indent,
484
+ );
485
+ return;
486
+ }
487
+ out.region(idOf.get(expr), () => writeCondition(out, expr, indent, checked));
488
+ }
489
+
490
+ /**
491
+ * Quotes text as a SQL string literal (for messages).
492
+ *
493
+ * @param {string} text text
494
+ * @returns {string} quoted text
495
+ */
496
+ function sqlQuote(text) {
497
+ return `'${text.replaceAll("'", "''")}'`;
498
+ }
499
+
500
+ /**
501
+ * Plans the filter of WSProxy / Rows.Retrieve: finds the LIKE conditions the `like` operator
502
+ * cannot express exactly (anything but `'%x%'`), which get an exact check in the script. That
503
+ * check only works when each of them sits on a pure AND path from the WHERE root.
504
+ *
505
+ * @param {SelectAst} ast statement
506
+ * @param {string} label target name used in messages
507
+ * @returns {{unavailable: string}|{checks: object[], messages: Message[]}} reason, or the LIKE
508
+ * nodes to check plus info messages (LIKE checks, empty values sent as a space)
509
+ */
510
+ function planFilter(ast, label) {
511
+ const checks = [];
512
+ let problem = null;
513
+ const visit = (expr, isUnderOr) => {
514
+ if (expr.type === 'and' || expr.type === 'or') {
515
+ visit(expr.left, isUnderOr || expr.type === 'or');
516
+ visit(expr.right, isUnderOr || expr.type === 'or');
517
+ } else if (expr.type === 'like' && !isContainsPattern(expr.pattern.value)) {
518
+ if (isUnderOr) {
519
+ problem ??= expr;
520
+ }
521
+ checks.push(expr);
522
+ }
523
+ };
524
+ if (ast.where) {
525
+ visit(ast.where, false);
526
+ }
527
+ if (problem) {
528
+ return {
529
+ unavailable: `The ${label} like filter always matches "contains", so LIKE ${sqlQuote(problem.pattern.value)} has to be checked exactly in the script after the filter, but a LIKE inside OR can't be checked exactly after a ${label} filter. Use a pattern of the form '%text%', or move the LIKE out of the OR.`,
530
+ };
531
+ }
532
+ const messages = checks.map((expr) =>
533
+ createMessage(
534
+ 'info',
535
+ LIKE_CHECKED_IN_SCRIPT,
536
+ `The ${label} like filter always matches "contains", so the filter reads the rows containing "${likeFilterValue(expr.pattern.value)}" and the script then keeps only the rows where ${expr.column} matches LIKE ${sqlQuote(expr.pattern.value)} exactly.`,
537
+ expr.loc,
538
+ ),
539
+ );
540
+ for (const expr of conditionsOf(ast.where)) {
541
+ let values = [];
542
+ if (expr.type === 'compare') {
543
+ values = [expr.value];
544
+ } else if (expr.type === 'in') {
545
+ values = expr.values;
546
+ }
547
+ if (values.some((value) => value.value === '')) {
548
+ messages.push(
549
+ createMessage(
550
+ 'info',
551
+ EMPTY_STRING_AS_SPACE,
552
+ `The ${label} filter rejects an empty value, so '' is sent as a single space " ". This finds the same rows, because trailing spaces are ignored when text is compared.`,
553
+ expr.loc,
554
+ ),
555
+ );
556
+ }
557
+ }
558
+ return { checks, messages };
559
+ }
560
+
561
+ /**
562
+ * Writes the exact LIKE check of a row: `if (sqlLike(row["Col"], "pattern") && …) { push }`,
563
+ * with each pattern marked as part of its condition.
564
+ *
565
+ * @param {CodeWriter} out writer
566
+ * @param {object[]} checks LIKE nodes to check
567
+ * @param {Map<object, string>} idOf node → clause id
568
+ * @param {string} indent indentation of the if statement
569
+ * @param {string} push the statement that keeps the row
570
+ */
571
+ function writeRowCheck(out, checks, idOf, indent, push) {
572
+ out.write(`${indent}if (`);
573
+ for (const [index, expr] of checks.entries()) {
574
+ out.write(`${index ? ' && ' : ''}sqlLike(row[${jsString(expr.column)}], `)
575
+ .mark(idOf.get(expr), jsString(expr.pattern.value))
576
+ .write(')');
577
+ }
578
+ out.write(`) {\n${indent}${INDENT}${push}\n${indent}}\n`);
579
+ }
580
+
581
+ // ------------------------------------------------------------------------------------------
582
+ // SSJS: WSProxy and Rows.Retrieve
583
+ // ------------------------------------------------------------------------------------------
584
+
585
+ /**
586
+ * Lists the LIKE columns missing from the selected columns (case-insensitive, first spelling).
587
+ *
588
+ * @param {{name: string}[]} columns selected columns
589
+ * @param {object[]} checks LIKE nodes checked in the script
590
+ * @returns {string[]} column names to read in addition
591
+ */
592
+ function missingCheckColumns(columns, checks) {
593
+ const known = new Set(columns.map((column) => column.name.toLowerCase()));
594
+ const missing = [];
595
+ for (const expr of checks) {
596
+ const key = expr.column.toLowerCase();
597
+ if (!known.has(key)) {
598
+ known.add(key);
599
+ missing.push(expr.column);
600
+ }
601
+ }
602
+ return missing;
603
+ }
604
+
605
+ /**
606
+ * Merges the dropped clauses with the filter messages.
607
+ *
608
+ * @param {{messages: Message[], dropped: string[]}} extra messages and dropped clauses
609
+ * @param {Message[]} messages filter messages
610
+ * @returns {{messages: Message[], dropped: string[]}} merged
611
+ */
612
+ function withMessages(extra, messages) {
613
+ return { messages: [...extra.messages, ...messages], dropped: extra.dropped };
614
+ }
615
+
616
+ /**
617
+ * Emits a WSProxy retrieve of `DataExtensionObject[Key]`. ORDER BY and TOP are dropped. LIKE
618
+ * patterns other than `'%x%'` are read with the wider `like` filter and checked exactly with
619
+ * `sqlLike` in the row loop (unavailable when such a LIKE sits under OR). A failed retrieve
620
+ * leaves `rows` empty and its status in `retrieveError`.
621
+ *
622
+ * @param {SelectAst} ast statement
623
+ * @param {EmitOptions} [options] options
624
+ * @returns {EmitResult|{unavailable: string}} code or the reason it cannot be generated
625
+ */
626
+ export function emitSsjsWsproxy(ast, options = {}) {
627
+ const context = prepare(ast, options);
628
+ if (!context.columns) {
629
+ return {
630
+ unavailable:
631
+ 'WSProxy needs the list of columns to read. Name the columns in the SELECT, or enter the columns that * stands for in the settings.',
632
+ };
633
+ }
634
+ const plan = planFilter(ast, 'WSProxy');
635
+ if (plan.unavailable) {
636
+ return plan;
637
+ }
638
+ const { checks } = plan;
639
+ const rowsAsObjects = options.output?.rowsAsObjects ?? true;
640
+ const isPaging = options.output?.paging ?? false;
641
+ const missing = missingCheckColumns(context.columns, checks);
642
+ const out = new CodeWriter();
643
+ out.write(SSJS_START);
644
+ if (missing.length) {
645
+ // the cols array reads more columns than the SELECT names: keep the SELECT list here
646
+ if (Array.isArray(ast.columns)) {
647
+ writeSelectComment(out, context.columns);
648
+ } else {
649
+ out.write('// SQL: SELECT *\n');
650
+ }
651
+ }
652
+ writeFromComment(out, context.deName, context.deKey);
653
+ writeNotInMarker(out, ast);
654
+ if (checks.length) {
655
+ out.write(SQL_LIKE_HELPER);
656
+ }
657
+ if (rowsAsObjects || checks.length) {
658
+ out.write(
659
+ 'function toObject(item) {\n var obj = {};\n var props = item.Properties;\n for (var p = 0; p < props.length; p++) {\n obj[props[p].Name] = props[p].Value;\n }\n return obj;\n}\n',
660
+ );
661
+ }
662
+ out.write('var api = new Script.Util.WSProxy();\nvar objectType = ');
663
+ out.mark('from', jsString(`DataExtensionObject[${context.deKey}]`)).write(';\nvar cols = [');
664
+ for (const [index, column] of context.columns.entries()) {
665
+ out.write(index ? ', ' : '').mark(column.clauseId, jsString(column.name));
666
+ }
667
+ for (const name of missing) {
668
+ out.write(`, ${jsString(name)}`);
669
+ }
670
+ out.write('];\n');
671
+ if (ast.where) {
672
+ out.write('var filter = ');
673
+ writeFilter(out, ast.where, context.idOf, '', new Set(checks));
674
+ out.write(';\n');
675
+ }
676
+ // without WHERE the non-paging call passes a null filter, like the continuation (proven live)
677
+ let call = 'api.retrieve(objectType, cols, filter)';
678
+ if (!ast.where) {
679
+ call = isPaging ? 'api.retrieve(objectType, cols)' : 'api.retrieve(objectType, cols, null)';
680
+ }
681
+ const item = rowsAsObjects ? 'toObject(result.Results[i])' : 'result.Results[i]';
682
+ const writeBody = (indent) => {
683
+ if (checks.length) {
684
+ out.write(`${indent}var row = toObject(result.Results[i]);\n`);
685
+ writeRowCheck(
686
+ out,
687
+ checks,
688
+ context.idOf,
689
+ indent,
690
+ rowsAsObjects ? 'rows.push(row);' : 'rows.push(result.Results[i]);',
691
+ );
692
+ } else {
693
+ out.write(`${indent}rows.push(${item});\n`);
694
+ }
695
+ };
696
+ if (isPaging) {
697
+ // the next batch is read with props.ContinueRequest = RequestID (proven live)
698
+ const nextCall = `api.retrieve(objectType, cols, ${ast.where ? 'filter' : 'null'}, null, props)`;
699
+ out.write(
700
+ `var rows = [];\nvar retrieveError = "";\nvar props = {};\nvar result = ${call};\n`,
701
+ );
702
+ out.write(
703
+ 'while (result) {\n if (result.Status !== "OK" && result.Status !== "MoreDataAvailable") {\n rows = [];\n retrieveError = String(result.Status);\n break;\n }\n for (var i = 0; i < result.Results.length; i++) {\n',
704
+ );
705
+ writeBody(INDENT.repeat(2));
706
+ out.write(
707
+ ` }\n if (result.HasMoreRows) {\n props.ContinueRequest = result.RequestID;\n result = ${nextCall};\n } else {\n result = null;\n }\n}\n`,
708
+ );
709
+ } else {
710
+ out.write(
711
+ `var rows = [];\nvar retrieveError = "";\nvar hasMoreRows = false;\nvar result = ${call};\n`,
712
+ );
713
+ out.write(
714
+ 'if (result.Status === "OK" || result.Status === "MoreDataAvailable") {\n for (var i = 0; i < result.Results.length; i++) {\n',
715
+ );
716
+ writeBody(INDENT.repeat(2));
717
+ out.write(
718
+ ' }\n} else {\n retrieveError = String(result.Status);\n}\nif (result.HasMoreRows) {\n // only the first batch was read: turn on paging in the settings to read every row\n hasMoreRows = true;\n}\n',
719
+ );
720
+ }
721
+ out.write(SSJS_END);
722
+ const messages = [...plan.messages];
723
+ if (!isPaging) {
724
+ messages.push(
725
+ createMessage(
726
+ 'info',
727
+ FIRST_BATCH_ONLY,
728
+ 'Without paging only the first batch of up to 2,500 rows is read; turn on paging for more.',
729
+ ast.from.loc,
730
+ ),
731
+ );
732
+ }
733
+ return finish(
734
+ out,
735
+ withMessages(
736
+ dropClauses(ast, context.clauses, { orderBy: true, top: true }, 'WSProxy retrieve'),
737
+ messages,
738
+ ),
739
+ );
740
+ }
741
+
742
+ /**
743
+ * Emits `DataExtension.Init(key).Rows.Retrieve(filter)`. ORDER BY and TOP are dropped; all
744
+ * columns are returned, so an explicit column list is kept in a header comment. LIKE patterns
745
+ * other than `'%x%'` are read with the wider `like` filter and checked exactly with `sqlLike`
746
+ * in a loop that builds `rows` (unavailable when such a LIKE sits under OR).
747
+ *
748
+ * @param {SelectAst} ast statement
749
+ * @param {EmitOptions} [options] options
750
+ * @returns {EmitResult|{unavailable: string}} code or the reason it cannot be generated
751
+ */
752
+ export function emitSsjsRowsRetrieve(ast, options = {}) {
753
+ const plan = planFilter(ast, 'Rows.Retrieve');
754
+ if (plan.unavailable) {
755
+ return plan;
756
+ }
757
+ const { checks } = plan;
758
+ const context = prepare(ast, options);
759
+ const out = new CodeWriter();
760
+ out.write(SSJS_START);
761
+ if (Array.isArray(ast.columns)) {
762
+ writeSelectComment(out, context.columns);
763
+ }
764
+ writeFromComment(out, context.deName, context.deKey);
765
+ writeNotInMarker(out, ast);
766
+ if (checks.length) {
767
+ out.write(SQL_LIKE_HELPER);
768
+ }
769
+ out.write('var de = DataExtension.Init(').mark('from', jsString(context.deKey)).write(');\n');
770
+ if (ast.where) {
771
+ out.write('var filter = ');
772
+ writeFilter(out, ast.where, context.idOf, '', new Set(checks));
773
+ out.write(';\n');
774
+ }
775
+ if (checks.length) {
776
+ out.write(
777
+ 'var retrieved = de.Rows.Retrieve(filter);\nvar rows = [];\nfor (var i = 0; i < retrieved.length; i++) {\n var row = retrieved[i];\n',
778
+ );
779
+ writeRowCheck(out, checks, context.idOf, INDENT, 'rows.push(row);');
780
+ out.write('}\n');
781
+ } else {
782
+ out.write(
783
+ ast.where
784
+ ? 'var rows = de.Rows.Retrieve(filter);\n'
785
+ : 'var rows = de.Rows.Retrieve();\n',
786
+ );
787
+ }
788
+ out.write(SSJS_END);
789
+ return finish(
790
+ out,
791
+ withMessages(
792
+ dropClauses(ast, context.clauses, { orderBy: true, top: true }, 'Rows.Retrieve'),
793
+ plan.messages,
794
+ ),
795
+ );
796
+ }
797
+
798
+ // ------------------------------------------------------------------------------------------
799
+ // Lookup family (equals + AND only)
800
+ // ------------------------------------------------------------------------------------------
801
+
802
+ /**
803
+ * Describes the first part of a WHERE tree a lookup function cannot express.
804
+ *
805
+ * @param {object} expr expression node
806
+ * @returns {string|null} plain description, or null when the tree is equals + AND only
807
+ */
808
+ function lookupProblem(expr) {
809
+ switch (expr.type) {
810
+ case 'and': {
811
+ return lookupProblem(expr.left) ?? lookupProblem(expr.right);
812
+ }
813
+ case 'or': {
814
+ return 'OR';
815
+ }
816
+ case 'compare': {
817
+ return expr.op === '=' ? null : `the operator ${expr.op}`;
818
+ }
819
+ case 'like': {
820
+ return 'LIKE';
821
+ }
822
+ case 'in': {
823
+ return expr.negated ? 'NOT IN' : 'IN';
824
+ }
825
+ case 'between': {
826
+ return 'BETWEEN';
827
+ }
828
+ case 'null': {
829
+ return expr.negated ? 'IS NOT NULL' : 'IS NULL';
830
+ }
831
+ default: {
832
+ return expr.type;
833
+ }
834
+ }
835
+ }
836
+
837
+ /**
838
+ * Checks that a query fits a lookup function and returns its column / value pairs.
839
+ *
840
+ * @param {SelectAst} ast statement
841
+ * @param {string} functionName name used in the reason
842
+ * @param {string} alternative what to use instead
843
+ * @returns {{unavailable: string}|{pairs: object[]}} reason, or the equality conditions
844
+ */
845
+ function lookupPairs(ast, functionName, alternative) {
846
+ if (!ast.where) {
847
+ return {
848
+ unavailable: `${functionName} needs at least one condition such as WHERE Column = 'value'. Use ${alternative} to read rows without a condition.`,
849
+ };
850
+ }
851
+ const problem = lookupProblem(ast.where);
852
+ if (problem) {
853
+ return {
854
+ unavailable: `${functionName} can only match exact values joined with AND (Column = 'value' AND …), but this query uses ${problem}. Use ${alternative} instead.`,
855
+ };
856
+ }
857
+ return { pairs: conditionsOf(ast.where) };
858
+ }
859
+
860
+ /**
861
+ * Checks that LookupOrderedRows can sort by the ORDER BY columns.
862
+ *
863
+ * @param {SelectAst} ast statement
864
+ * @returns {{unavailable: string}|null} reason, or null when the sort order fits
865
+ */
866
+ function sortProblem(ast) {
867
+ if (!ast.orderBy?.length) {
868
+ return {
869
+ unavailable:
870
+ 'LookupOrderedRows needs a sort order. Add ORDER BY Column ASC (or DESC), or use the LookupRows output.',
871
+ };
872
+ }
873
+ const awkward = ast.orderBy.find((item) => /[\s,]/.test(item.column));
874
+ if (awkward) {
875
+ return {
876
+ unavailable: `LookupOrderedRows cannot sort by "${awkward.column}" because the sort text cannot hold a column name with spaces or commas. Use the LookupRows output and sort in your code.`,
877
+ };
878
+ }
879
+ return null;
880
+ }
881
+
882
+ /**
883
+ * Builds the sort text of LookupOrderedRows (`Col ASC, Col2 DESC`), each item as a piece.
884
+ *
885
+ * @param {SelectAst} ast statement
886
+ * @param {Map<object, string>} idOf node → clause id
887
+ * @returns {{clauseId: string, text: string}[]} sort items
888
+ */
889
+ function sortItems(ast, idOf) {
890
+ return ast.orderBy.map((item) => ({
891
+ clauseId: idOf.get(item),
892
+ text: `${item.column} ${item.direction}`,
893
+ }));
894
+ }
895
+
896
+ /**
897
+ * Writes a quoted sort string with each item marked.
898
+ *
899
+ * @param {CodeWriter} out writer
900
+ * @param {{clauseId: string, text: string}[]} items sort items
901
+ * @param {(text: string) => string} quote string literal formatter
902
+ */
903
+ function writeSortString(out, items, quote) {
904
+ const unquote = (text) => quote(text).slice(1, -1);
905
+ out.write('"');
906
+ for (const [index, item] of items.entries()) {
907
+ out.write(index ? ', ' : '').mark(item.clauseId, unquote(item.text));
908
+ }
909
+ out.write('"');
910
+ }
911
+
912
+ /**
913
+ * Writes the SSJS field and value arrays of a lookup call.
914
+ *
915
+ * @param {CodeWriter} out writer
916
+ * @param {object[]} pairs equality conditions
917
+ * @param {Map<object, string>} idOf node → clause id
918
+ */
919
+ function writeSsjsLookupArrays(out, pairs, idOf) {
920
+ out.write('[');
921
+ for (const [index, pair] of pairs.entries()) {
922
+ out.write(index ? ', ' : '').mark(idOf.get(pair), jsString(pair.column));
923
+ }
924
+ out.write('], [');
925
+ for (const [index, pair] of pairs.entries()) {
926
+ out.write(index ? ', ' : '').mark(idOf.get(pair), jsString(pair.value.value));
927
+ }
928
+ out.write(']');
929
+ }
930
+
931
+ const SSJS_LOOKUP_ALTERNATIVE = 'the WSProxy or Rows.Retrieve output';
932
+ const AMPSCRIPT_LOOKUP_ALTERNATIVE = 'the SSJS WSProxy output';
933
+
934
+ /**
935
+ * Emits `Platform.Function.LookupRows(name, fields, values)`. Equals + AND only; ORDER BY
936
+ * and TOP are dropped; an explicit column list is kept in a header comment.
937
+ *
938
+ * @param {SelectAst} ast statement
939
+ * @param {EmitOptions} [options] options
940
+ * @returns {EmitResult|{unavailable: string}} code or the reason it cannot be generated
941
+ */
942
+ export function emitSsjsLookupRows(ast, options = {}) {
943
+ const check = lookupPairs(ast, 'LookupRows', SSJS_LOOKUP_ALTERNATIVE);
944
+ if (check.unavailable) {
945
+ return check;
946
+ }
947
+ const context = prepare(ast, options);
948
+ const out = new CodeWriter();
949
+ out.write(SSJS_START);
950
+ if (Array.isArray(ast.columns)) {
951
+ writeSelectComment(out, context.columns);
952
+ }
953
+ out.write('var rows = Platform.Function.LookupRows(')
954
+ .mark('from', jsString(context.deName))
955
+ .write(', ');
956
+ writeSsjsLookupArrays(out, check.pairs, context.idOf);
957
+ out.write(');\nvar rowCount = rows ? rows.length : 0;\n').write(SSJS_END);
958
+ return finish(
959
+ out,
960
+ withMessages(
961
+ dropClauses(ast, context.clauses, { orderBy: true, top: true }, 'LookupRows'),
962
+ lookupLimitMessages(ast, context.clauses, 'LookupRows'),
963
+ ),
964
+ );
965
+ }
966
+
967
+ /**
968
+ * Emits `Platform.Function.LookupOrderedRows(name, count, sort, fields, values)`. Needs
969
+ * ORDER BY; count comes from TOP (0 = all rows).
970
+ *
971
+ * @param {SelectAst} ast statement
972
+ * @param {EmitOptions} [options] options
973
+ * @returns {EmitResult|{unavailable: string}} code or the reason it cannot be generated
974
+ */
975
+ export function emitSsjsLookupOrderedRows(ast, options = {}) {
976
+ const check = lookupPairs(ast, 'LookupOrderedRows', SSJS_LOOKUP_ALTERNATIVE);
977
+ if (check.unavailable) {
978
+ return check;
979
+ }
980
+ const sortCheck = sortProblem(ast);
981
+ if (sortCheck) {
982
+ return sortCheck;
983
+ }
984
+ const context = prepare(ast, options);
985
+ const out = new CodeWriter();
986
+ out.write(SSJS_START);
987
+ if (Array.isArray(ast.columns)) {
988
+ writeSelectComment(out, context.columns);
989
+ }
990
+ out.write('var rows = Platform.Function.LookupOrderedRows(')
991
+ .mark('from', jsString(context.deName))
992
+ .write(', ');
993
+ if (ast.top === null || ast.top === undefined) {
994
+ out.write('0');
995
+ } else {
996
+ out.mark('top', String(ast.top));
997
+ }
998
+ out.write(', ');
999
+ writeSortString(out, sortItems(ast, context.idOf), jsString);
1000
+ out.write(', ');
1001
+ writeSsjsLookupArrays(out, check.pairs, context.idOf);
1002
+ out.write(');\nvar rowCount = rows ? rows.length : 0;\n').write(SSJS_END);
1003
+ return finish(out, {
1004
+ messages: lookupLimitMessages(ast, context.clauses, 'LookupOrderedRows'),
1005
+ dropped: [],
1006
+ });
1007
+ }
1008
+
1009
+ // ------------------------------------------------------------------------------------------
1010
+ // AMPscript
1011
+ // ------------------------------------------------------------------------------------------
1012
+
1013
+ /**
1014
+ * Turns column names into AMPscript variable names, one per column in the same order.
1015
+ * AMPscript variable names ignore case, so names that only differ in case or in replaced
1016
+ * characters get a number (`@a_b`, `@a_b2`, …). They never clash with the loop variables
1017
+ * (`@rows`, `@row`, `@rowCount`, `@i`): such a column gets `Value` appended.
1018
+ *
1019
+ * @param {string[]} names column names
1020
+ * @returns {string[]} variable names including `@`
1021
+ */
1022
+ export function ampVariableNames(names) {
1023
+ const used = new Set(AMPSCRIPT_LOOP_VARIABLES);
1024
+ return names.map((name) => {
1025
+ let base = String(name).replaceAll(/[^A-Za-z0-9_]/g, '_');
1026
+ if (/^\d/.test(base)) {
1027
+ base = `_${base}`;
1028
+ }
1029
+ if (AMPSCRIPT_LOOP_VARIABLES.has(base.toLowerCase())) {
1030
+ base += 'Value';
1031
+ }
1032
+ let variable = base;
1033
+ for (let suffix = 2; used.has(variable.toLowerCase()); suffix++) {
1034
+ variable = `${base}${suffix}`;
1035
+ }
1036
+ used.add(variable.toLowerCase());
1037
+ return `@${variable}`;
1038
+ });
1039
+ }
1040
+
1041
+ /**
1042
+ * Checks that no name or value of the query contains `%%`. Inside an AMPscript block, `]%%`
1043
+ * ends the block; whether SFMC accepts it inside a string is not proven, so such queries get
1044
+ * no AMPscript output.
1045
+ *
1046
+ * @param {SelectAst} ast statement
1047
+ * @param {{name: string}[]|null} columns selected columns
1048
+ * @returns {{unavailable: string}|null} reason, or null when the query is safe
1049
+ */
1050
+ function ampscriptTextProblem(ast, columns) {
1051
+ const texts = [ast.from.name, ...(columns ?? []).map((column) => column.name)];
1052
+ for (const expr of conditionsOf(ast.where)) {
1053
+ const values = [expr.value, expr.pattern, expr.low, expr.high, ...(expr.values ?? [])];
1054
+ texts.push(expr.column, ...values.filter(Boolean).map((value) => value.value));
1055
+ }
1056
+ const orderBy = ast.orderBy ?? [];
1057
+ for (const item of orderBy) {
1058
+ texts.push(item.column);
1059
+ }
1060
+ const found = texts.find((text) => text.includes('%%'));
1061
+ if (found === undefined) {
1062
+ return null;
1063
+ }
1064
+ return {
1065
+ unavailable: `AMPscript can't safely hold "%%" in a name or value ("${found}"), because it can end the AMPscript block. Use the SSJS outputs instead.`,
1066
+ };
1067
+ }
1068
+
1069
+ /**
1070
+ * Warns when TOP asks for more rows than a lookup function returns (at most 2,000).
1071
+ *
1072
+ * @param {SelectAst} ast statement
1073
+ * @param {object[]} clauses clauses from `collectClauses`
1074
+ * @param {string} label function name used in the message
1075
+ * @returns {Message[]} the warning, or none
1076
+ */
1077
+ function lookupLimitMessages(ast, clauses, label) {
1078
+ if (ast.top === null || ast.top === undefined || ast.top <= LOOKUP_ROW_LIMIT) {
1079
+ return [];
1080
+ }
1081
+ const topClause = clauses.find((clause) => clause.clauseId === 'top');
1082
+ return [
1083
+ createMessage(
1084
+ 'warning',
1085
+ TOP_ABOVE_LOOKUP_LIMIT,
1086
+ `${label} returns at most 2,000 rows, so TOP ${ast.top} can't be reached. Use the SSJS WSProxy output with paging to read more rows.`,
1087
+ topClause?.loc ?? ast.loc,
1088
+ ),
1089
+ ];
1090
+ }
1091
+
1092
+ /**
1093
+ * Writes the column / value pairs of an AMPscript lookup call (`, "Col", "v", …`).
1094
+ *
1095
+ * @param {CodeWriter} out writer
1096
+ * @param {object[]} pairs equality conditions
1097
+ * @param {Map<object, string>} idOf node → clause id
1098
+ */
1099
+ function writeAmpPairs(out, pairs, idOf) {
1100
+ for (const pair of pairs) {
1101
+ out.write(', ').region(idOf.get(pair), () => {
1102
+ out.write(`${ampString(pair.column)}, ${ampString(pair.value.value)}`);
1103
+ });
1104
+ }
1105
+ }
1106
+
1107
+ /**
1108
+ * Writes the FOR loop that reads the selected columns of every row.
1109
+ *
1110
+ * @param {CodeWriter} out writer
1111
+ * @param {{name: string, clauseId?: string}[]|null} columns selected columns
1112
+ */
1113
+ function writeAmpLoop(out, columns) {
1114
+ out.write(
1115
+ 'SET @rowCount = RowCount(@rows)\nFOR @i = 1 TO @rowCount DO\n SET @row = Row(@rows, @i)\n',
1116
+ );
1117
+ if (columns) {
1118
+ const variables = ampVariableNames(columns.map((column) => column.name));
1119
+ for (const [index, column] of columns.entries()) {
1120
+ out.write(` SET ${variables[index]} = Field(@row, `)
1121
+ .mark(column.clauseId, ampString(column.name))
1122
+ .write(')\n');
1123
+ }
1124
+ } else {
1125
+ out.write(" /* add one Field(@row, 'ColumnName') per column you need */\n");
1126
+ }
1127
+ out.write('NEXT @i\n');
1128
+ }
1129
+
1130
+ /**
1131
+ * Emits AMPscript `LookupRows("Name", "Col", "v", …)` plus a FOR loop. Equals + AND only;
1132
+ * ORDER BY and TOP are dropped.
1133
+ *
1134
+ * @param {SelectAst} ast statement
1135
+ * @param {EmitOptions} [options] options
1136
+ * @returns {EmitResult|{unavailable: string}} code or the reason it cannot be generated
1137
+ */
1138
+ export function emitAmpscriptLookupRows(ast, options = {}) {
1139
+ const check = lookupPairs(ast, 'LookupRows', AMPSCRIPT_LOOKUP_ALTERNATIVE);
1140
+ if (check.unavailable) {
1141
+ return check;
1142
+ }
1143
+ const context = prepare(ast, options);
1144
+ const textProblem = ampscriptTextProblem(ast, context.columns);
1145
+ if (textProblem) {
1146
+ return textProblem;
1147
+ }
1148
+ const out = new CodeWriter();
1149
+ out.write('%%[\n');
1150
+ if (Array.isArray(ast.columns)) {
1151
+ writeSelectComment(out, context.columns, 'block');
1152
+ }
1153
+ out.write('SET @rows = LookupRows(').mark('from', ampString(context.deName));
1154
+ writeAmpPairs(out, check.pairs, context.idOf);
1155
+ out.write(')\n');
1156
+ writeAmpLoop(out, context.columns);
1157
+ out.write(']%%');
1158
+ return finish(
1159
+ out,
1160
+ withMessages(
1161
+ dropClauses(ast, context.clauses, { orderBy: true, top: true }, 'LookupRows'),
1162
+ lookupLimitMessages(ast, context.clauses, 'LookupRows'),
1163
+ ),
1164
+ );
1165
+ }
1166
+
1167
+ /**
1168
+ * Emits AMPscript `LookupOrderedRows("Name", count, "Col ASC", "Col", "v", …)` plus a FOR
1169
+ * loop. Needs ORDER BY; count comes from TOP (0 = all rows).
1170
+ *
1171
+ * @param {SelectAst} ast statement
1172
+ * @param {EmitOptions} [options] options
1173
+ * @returns {EmitResult|{unavailable: string}} code or the reason it cannot be generated
1174
+ */
1175
+ export function emitAmpscriptLookupOrderedRows(ast, options = {}) {
1176
+ const check = lookupPairs(ast, 'LookupOrderedRows', AMPSCRIPT_LOOKUP_ALTERNATIVE);
1177
+ if (check.unavailable) {
1178
+ return check;
1179
+ }
1180
+ const sortCheck = sortProblem(ast);
1181
+ if (sortCheck) {
1182
+ return sortCheck;
1183
+ }
1184
+ const context = prepare(ast, options);
1185
+ const textProblem = ampscriptTextProblem(ast, context.columns);
1186
+ if (textProblem) {
1187
+ return textProblem;
1188
+ }
1189
+ const out = new CodeWriter();
1190
+ out.write('%%[\n');
1191
+ if (Array.isArray(ast.columns)) {
1192
+ writeSelectComment(out, context.columns, 'block');
1193
+ }
1194
+ out.write('SET @rows = LookupOrderedRows(').mark('from', ampString(context.deName));
1195
+ out.write(', ');
1196
+ if (ast.top === null || ast.top === undefined) {
1197
+ out.write('0');
1198
+ } else {
1199
+ out.mark('top', String(ast.top));
1200
+ }
1201
+ out.write(', ');
1202
+ writeSortString(out, sortItems(ast, context.idOf), ampString);
1203
+ writeAmpPairs(out, check.pairs, context.idOf);
1204
+ out.write(')\n');
1205
+ writeAmpLoop(out, context.columns);
1206
+ out.write(']%%');
1207
+ return finish(out, {
1208
+ messages: lookupLimitMessages(ast, context.clauses, 'LookupOrderedRows'),
1209
+ dropped: [],
1210
+ });
1211
+ }
1212
+
1213
+ /**
1214
+ * Emits AMPscript `SET @Col = Lookup("Name", "Col", "Where", "v", …)`. Needs exactly one
1215
+ * selected column and equals + AND; returns the first match only (info message). ORDER BY is
1216
+ * dropped, and TOP unless it is 1.
1217
+ *
1218
+ * @param {SelectAst} ast statement
1219
+ * @param {EmitOptions} [options] options
1220
+ * @returns {EmitResult|{unavailable: string}} code or the reason it cannot be generated
1221
+ */
1222
+ export function emitAmpscriptLookup(ast, options = {}) {
1223
+ const context = prepare(ast, options);
1224
+ if (context.columns?.length !== 1) {
1225
+ return {
1226
+ unavailable:
1227
+ 'Lookup returns the value of a single column. Select exactly one column, or use the LookupRows output.',
1228
+ };
1229
+ }
1230
+ const check = lookupPairs(ast, 'Lookup', AMPSCRIPT_LOOKUP_ALTERNATIVE);
1231
+ if (check.unavailable) {
1232
+ return check;
1233
+ }
1234
+ const textProblem = ampscriptTextProblem(ast, context.columns);
1235
+ if (textProblem) {
1236
+ return textProblem;
1237
+ }
1238
+ const [column] = context.columns;
1239
+ const [variable] = ampVariableNames([column.name]);
1240
+ const out = new CodeWriter();
1241
+ // TOP 1 is what Lookup does anyway: it maps to the call instead of being dropped.
1242
+ out.write(`%%[\nSET ${variable} = `)
1243
+ .mark(ast.top === 1 ? 'top' : undefined, 'Lookup')
1244
+ .write('(')
1245
+ .mark('from', ampString(context.deName))
1246
+ .write(', ')
1247
+ .mark(column.clauseId, ampString(column.name));
1248
+ writeAmpPairs(out, check.pairs, context.idOf);
1249
+ out.write(')\n]%%');
1250
+ const extra = dropClauses(
1251
+ ast,
1252
+ context.clauses,
1253
+ { orderBy: true, top: ast.top !== 1 },
1254
+ 'Lookup',
1255
+ );
1256
+ const location = Array.isArray(ast.columns) ? ast.columns[0].loc : ast.loc;
1257
+ extra.messages.push(
1258
+ createMessage(
1259
+ 'info',
1260
+ LOOKUP_FIRST_ROW_ONLY,
1261
+ `Lookup returns only the ${column.name} value of the first matching row. Use the LookupRows output to read every match.`,
1262
+ location,
1263
+ ),
1264
+ );
1265
+ return finish(out, extra);
1266
+ }
1267
+
1268
+ // ------------------------------------------------------------------------------------------
1269
+ // Registry
1270
+ // ------------------------------------------------------------------------------------------
1271
+
1272
+ /**
1273
+ * Engagement targets in display order.
1274
+ *
1275
+ * @type {ReadonlyArray<{id: string, language: 'ssjs'|'ampscript', label: string,
1276
+ * emit: (ast: SelectAst, options?: EmitOptions) => EmitResult|{unavailable: string},
1277
+ * normalize: {expandNotIn?: boolean, dropTop?: boolean}}>}
1278
+ */
1279
+ export const MCE_TARGETS = Object.freeze([
1280
+ {
1281
+ id: 'ssjs-wsproxy',
1282
+ language: 'ssjs',
1283
+ label: 'WSProxy',
1284
+ emit: emitSsjsWsproxy,
1285
+ normalize: { expandNotIn: true },
1286
+ },
1287
+ {
1288
+ id: 'ssjs-rows-retrieve',
1289
+ language: 'ssjs',
1290
+ label: 'Rows.Retrieve',
1291
+ emit: emitSsjsRowsRetrieve,
1292
+ normalize: { expandNotIn: true },
1293
+ },
1294
+ {
1295
+ id: 'ssjs-lookuprows',
1296
+ language: 'ssjs',
1297
+ label: 'LookupRows',
1298
+ emit: emitSsjsLookupRows,
1299
+ normalize: {},
1300
+ },
1301
+ {
1302
+ id: 'ssjs-lookuporderedrows',
1303
+ language: 'ssjs',
1304
+ label: 'LookupOrderedRows',
1305
+ emit: emitSsjsLookupOrderedRows,
1306
+ normalize: {},
1307
+ },
1308
+ {
1309
+ id: 'ampscript-lookuprows',
1310
+ language: 'ampscript',
1311
+ label: 'LookupRows',
1312
+ emit: emitAmpscriptLookupRows,
1313
+ normalize: {},
1314
+ },
1315
+ {
1316
+ id: 'ampscript-lookuporderedrows',
1317
+ language: 'ampscript',
1318
+ label: 'LookupOrderedRows',
1319
+ emit: emitAmpscriptLookupOrderedRows,
1320
+ normalize: {},
1321
+ },
1322
+ {
1323
+ id: 'ampscript-lookup',
1324
+ language: 'ampscript',
1325
+ label: 'Lookup',
1326
+ emit: emitAmpscriptLookup,
1327
+ // Lookup always returns one row: TOP 1 is implied by the call itself
1328
+ normalize: { dropTop: true },
1329
+ },
1330
+ ]);