sfmc-sql-converter 0.1.0 → 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,788 @@
1
+ /**
2
+ * Marketing Cloud Next emitters: turn a parsed SELECT (see `parseSql`) into Handlebars
3
+ * (`query` / `queryFirst`) or AMPscript (`RetrieveSalesforceObjects`, `LookupRows`) that reads
4
+ * the same records from a Sales Cloud object (`CRM`) or a marketing object (`MO`).
5
+ *
6
+ * Only what the live probes proved is emitted (see `NEXT_RULES`, which points at the
7
+ * verification DB rows); everything else makes the target unavailable with a plain reason.
8
+ * Emitter results have the same shape as the Engagement emitters (see emit-mce.js).
9
+ */
10
+
11
+ import { CodeWriter, collectClauses, conditionsOf, isContainsPattern } from './clauses.js';
12
+ import { ampString, emitAmpscriptLookupRows, writeAmpLoop } from './emit-mce.js';
13
+ import { LOOKUP_FIRST_ROW_ONLY, MO_ONE_MATCH, TOP_DROPPED, createMessage } from './messages.js';
14
+
15
+ /**
16
+ * @typedef {import('./sql-parser.js').SelectAst} SelectAst
17
+ * @typedef {import('./emit-mce.js').EmitResult} EmitResult
18
+ */
19
+
20
+ /**
21
+ * @typedef {object} NextEmitOptions
22
+ * @property {string} [sourceText] the SQL text the AST came from (locates TOP for messages)
23
+ */
24
+
25
+ const DB = 'entries/mcn/';
26
+ const QUERY = `${DB}mcn-handlebars-email-query.json`;
27
+ const QUERY_FIRST = `${DB}mcn-handlebars-email-queryfirst.json`;
28
+ const RSO = `${DB}mcn-ampscript-email-retrievesalesforceobjects.json`;
29
+ const LOOKUP_ROWS = `${DB}mcn-ampscript-email-lookuprows.json`;
30
+ const LOOKUP_ORDERED_ROWS = `${DB}mcn-ampscript-email-lookuporderedrows.json`;
31
+
32
+ /**
33
+ * Builds verification DB references `file#checklist[i]` (0-based, as in the JSON array).
34
+ *
35
+ * @param {string} file DB entry path
36
+ * @param {...number} indexes checklist indexes
37
+ * @returns {string[]} references
38
+ */
39
+ function rows(file, ...indexes) {
40
+ return indexes.map((index) => `${file}#checklist[${index}]`);
41
+ }
42
+
43
+ /**
44
+ * What the Next probes proved or disproved, in one place. Each rule has the `value` the
45
+ * emitters use and `db`, the verification DB rows (`.claude/skills/_verification-db/…`) it rests
46
+ * on; `db: []` marks a construct that was not probed and is therefore not emitted.
47
+ */
48
+ export const NEXT_RULES = Object.freeze({
49
+ // Handlebars query/queryFirst with named parameters saves and publishes
50
+ namedParameters: { value: true, db: [...rows(QUERY, 2), ...rows(QUERY_FIRST, 2)] },
51
+ // CRM where operators (SQL → Next); `<>` is written as `!=` (only `!=` was probed)
52
+ crmOperators: {
53
+ value: Object.freeze({ '=': '=', '<>': '!=', '<': '<', '<=': '<=', '>': '>', '>=': '>=' }),
54
+ db: rows(QUERY, 5, 6, 7, 8, 9, 10, 11, 12, 13, 64),
55
+ },
56
+ // values only as :name placeholders with params=(hash …); literals in where fail
57
+ paramsOnly: { value: true, db: rows(QUERY, 5, 6, 8, 24, 25, 26) },
58
+ // dates are compared with a "yyyy-MM-dd" string param
59
+ dateParams: { value: true, db: rows(QUERY, 21, 22, 23) },
60
+ // LIKE always matches "contains"; only `%text%` gives the SQL result
61
+ likeContainsOnly: {
62
+ value: true,
63
+ db: [...rows(QUERY, 14, 15, 16, 17, 18, 23), ...rows(RSO, 13, 14, 15)],
64
+ },
65
+ // AND, OR and parentheses in a CRM where
66
+ crmBoolean: { value: true, db: rows(QUERY, 18, 19, 20, 41) },
67
+ // a query without where/params (fields, sortBy, limit only)
68
+ crmNoWhere: { value: true, db: rows(QUERY, 42) },
69
+ // #each body: one {{Field}} per line (CRM and MO)
70
+ eachBody: { value: true, db: rows(QUERY, 41, 49) },
71
+ // Handlebars string escaping: " is written as \", ' and other backslashes stay as they are
72
+ hbEscaping: {
73
+ value: true,
74
+ db: [...rows(QUERY, 43, 44, 45), ...rows(`${DB}mcn-handlebars-email-concat.json`, 1)],
75
+ },
76
+ // number params stay unquoted, also negative and decimal
77
+ numberParams: { value: true, db: rows(QUERY, 5, 46) },
78
+ // IN, NOT IN and NOT (…) fail; BETWEEN was not probed: error with a rewrite hint
79
+ crmInBetween: { value: false, db: rows(QUERY, 69, 70, 71) },
80
+ // IS NULL / IS NOT NULL were not probed on any Next target
81
+ nullTests: { value: false, db: [] },
82
+ // fields= is required: without it every field is empty
83
+ crmFieldsRequired: { value: true, db: rows(QUERY, 30, 31) },
84
+ // sortBy="Field ASC|DESC" (one field) orders the result; queryFirst picks by it
85
+ crmSortBy: {
86
+ value: 'one field',
87
+ db: [...rows(QUERY, 27, 28, 41, 42, 66), ...rows(QUERY_FIRST, 6, 7, 20)],
88
+ },
89
+ // limit=n caps the result after sorting
90
+ crmLimit: { value: true, db: rows(QUERY, 29, 41, 42) },
91
+ // queryFirst: one value read with get; no match renders empty
92
+ queryFirstGet: { value: true, db: rows(QUERY_FIRST, 5, 8, 20) },
93
+ // MO query: inline filters Field=value on any field (key or not, number or text),
94
+ // several combine with AND; where, where + inline, and no filter fail
95
+ moInlineFilters: {
96
+ value: true,
97
+ db: [
98
+ ...rows(QUERY, 3, 4, 32, 33, 34, 49, 50, 51, 52, 53, 54, 55, 57),
99
+ ...rows(QUERY_FIRST, 3, 4, 21, 22),
100
+ ],
101
+ },
102
+ // MO query: limit=n works, sortBy fails
103
+ moLimit: { value: true, db: rows(QUERY, 60) },
104
+ moSortBy: { value: false, db: [...rows(QUERY, 61), ...rows(QUERY_FIRST, 23)] },
105
+ // MO: a filter that matches two records returned only one (Handlebars query and LookupRows)
106
+ moOneMatch: { value: true, db: [...rows(QUERY, 62), ...rows(LOOKUP_ROWS, 15)] },
107
+ // MO LookupRows: the same field in two pairs uses the second pair (no AND)
108
+ lookupRowsDistinctFields: { value: true, db: rows(LOOKUP_ROWS, 16) },
109
+ // RetrieveSalesforceObjects operators; `<>` is written as `!=`
110
+ rsoOperators: {
111
+ value: Object.freeze({
112
+ '=': '=',
113
+ '<>': '!=',
114
+ '<': '<',
115
+ '<=': '<=',
116
+ '>': '>',
117
+ '>=': '>=',
118
+ LIKE: 'LIKE',
119
+ }),
120
+ db: rows(RSO, 6, 7, 8, 11, 15, 16, 17, 18, 21, 23),
121
+ },
122
+ // operators as literal strings; Char()/Concat() fail
123
+ rsoOperatorLiteral: { value: true, db: rows(RSO, 9) },
124
+ // several triplets combine with AND (never OR)
125
+ rsoAndOnly: { value: true, db: rows(RSO, 11, 12, 25, 26) },
126
+ // the same field in two triplets returns no rows: each field at most once
127
+ rsoDistinctFields: { value: true, db: rows(RSO, 22, 24) },
128
+ // the result is tested with RowCount (Empty() gives false); Row/Field read values
129
+ rsoRowCount: { value: true, db: rows(RSO, 2, 3, 4, 21) },
130
+ // LookupRows on a marketing object: equals + AND, key or non-key field
131
+ lookupRowsMo: { value: true, db: rows(LOOKUP_ROWS, 0, 2, 3, 4, 7, 8, 9) },
132
+ // LookupOrderedRows fails in Next: no ORDER BY / TOP for AMPscript
133
+ noOrderedLookup: { value: true, db: rows(LOOKUP_ORDERED_ROWS, 2, 3, 4, 5, 6) },
134
+ });
135
+
136
+ // Salesforce API names: letters, digits and underscores, starting with a letter
137
+ const API_NAME = /^[A-Za-z]\w*$/;
138
+ const INDENT = ' '.repeat(4);
139
+ const HANDLEBARS_ALTERNATIVE = 'the Handlebars query output';
140
+
141
+ /**
142
+ * Formats text as a double-quoted Handlebars string: `"` is written as `\"`.
143
+ *
144
+ * @param {string} text the text (must not end with a backslash)
145
+ * @returns {string} string literal
146
+ */
147
+ export function hbString(text) {
148
+ return `"${String(text).replaceAll('"', String.raw`\"`)}"`;
149
+ }
150
+
151
+ /**
152
+ * Formats a value for a Handlebars hash: numbers stay numbers, text becomes a string.
153
+ *
154
+ * @param {{kind: string, value: string}} value value node
155
+ * @returns {string} Handlebars literal
156
+ */
157
+ function hbValue(value) {
158
+ return value.kind === 'number' ? value.value : hbString(value.value);
159
+ }
160
+
161
+ /**
162
+ * Lists every value of the WHERE tree.
163
+ *
164
+ * @param {SelectAst} ast statement
165
+ * @returns {{value: string}[]} value nodes
166
+ */
167
+ function valuesOf(ast) {
168
+ return conditionsOf(ast.where).flatMap((expr) =>
169
+ [expr.value, expr.pattern, expr.low, expr.high, ...(expr.values ?? [])].filter(Boolean),
170
+ );
171
+ }
172
+
173
+ /**
174
+ * Checks names (object, columns, filter and sort fields) against the Salesforce API name rule.
175
+ *
176
+ * @param {SelectAst} ast statement
177
+ * @returns {string|null} reason, or null when every name fits
178
+ */
179
+ function nameProblem(ast) {
180
+ const names = [
181
+ ast.from.name,
182
+ ...(Array.isArray(ast.columns) ? ast.columns.map((column) => column.name) : []),
183
+ ...conditionsOf(ast.where).map((expr) => expr.column),
184
+ ...(ast.orderBy ?? []).map((item) => item.column),
185
+ ];
186
+ const bad = names.find((name) => !API_NAME.test(name));
187
+ return bad === undefined
188
+ ? null
189
+ : `"${bad}" is not a Salesforce API name. Next reads objects and fields by their API name, which has only letters, digits and underscores (e.g. LastName or Score__c).`;
190
+ }
191
+
192
+ /**
193
+ * Describes the first part of a WHERE tree a Next target cannot express.
194
+ *
195
+ * @param {object} expr expression node
196
+ * @param {{label: string, or: boolean, orHint?: string, ops: Readonly<Record<string, string>>,
197
+ * like: boolean}} caps what the target supports
198
+ * @returns {string|null} reason, or null when the tree fits
199
+ */
200
+ function whereProblem(expr, caps) {
201
+ switch (expr.type) {
202
+ case 'and': {
203
+ return whereProblem(expr.left, caps) ?? whereProblem(expr.right, caps);
204
+ }
205
+ case 'or': {
206
+ if (!caps.or) {
207
+ return `${caps.label} can only combine conditions with AND, but this query uses OR.${caps.orHint ?? ''}`;
208
+ }
209
+ return whereProblem(expr.left, caps) ?? whereProblem(expr.right, caps);
210
+ }
211
+ case 'compare': {
212
+ return Object.hasOwn(caps.ops, expr.op)
213
+ ? null
214
+ : `${caps.label} can only match exact values (=) joined with AND, but this query uses ${expr.op}.`;
215
+ }
216
+ case 'like': {
217
+ if (!caps.like) {
218
+ return `${caps.label} can't use LIKE.`;
219
+ }
220
+ return likeProblem(expr.pattern.value);
221
+ }
222
+ case 'in': {
223
+ return expr.negated
224
+ ? `NOT IN is not supported in Next. Write it as conditions joined with AND: ${expr.column} <> 'a' AND ${expr.column} <> 'b'.`
225
+ : `IN is not supported in Next. Write it as conditions joined with OR: ${expr.column} = 'a' OR ${expr.column} = 'b'.`;
226
+ }
227
+ case 'between': {
228
+ return `BETWEEN is not supported in Next. Write it as two conditions: ${expr.column} >= low AND ${expr.column} <= high.`;
229
+ }
230
+ case 'null': {
231
+ return `Next has no proven way to test for empty values (${expr.column} IS ${expr.negated ? 'NOT ' : ''}NULL), so this query can't be converted.`;
232
+ }
233
+ default: {
234
+ return expr.type;
235
+ }
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Checks that a LIKE pattern means "contains" (`%text%` without `_` or `[`), the only LIKE
241
+ * Next gives the SQL result for.
242
+ *
243
+ * @param {string} pattern LIKE pattern
244
+ * @returns {string|null} reason, or null for a contains pattern
245
+ */
246
+ function likeProblem(pattern) {
247
+ const inner = pattern.slice(1, -1);
248
+ if (isContainsPattern(pattern) && !/[%_[]/.test(inner)) {
249
+ return null;
250
+ }
251
+ return `Next matches LIKE as "contains" and ignores the wildcards, so '${pattern}' would also return values that only contain the text somewhere (e.g. 'Ro%' also returns Brown). Only '%text%' patterns without _ or [ ] convert.`;
252
+ }
253
+
254
+ /**
255
+ * Checks the values for what a Handlebars string can't hold.
256
+ *
257
+ * @param {SelectAst} ast statement
258
+ * @returns {string|null} reason, or null when every value fits
259
+ */
260
+ function hbValueProblem(ast) {
261
+ const bad = valuesOf(ast).find((value) => value.value.endsWith('\\'));
262
+ return bad
263
+ ? `The value "${bad.value}" ends with a backslash, which a Handlebars string can't hold. Remove the backslash.`
264
+ : null;
265
+ }
266
+
267
+ /**
268
+ * Checks the values for "%%", which can end an AMPscript block.
269
+ *
270
+ * @param {SelectAst} ast statement
271
+ * @returns {string|null} reason, or null when every value fits
272
+ */
273
+ function ampValueProblem(ast) {
274
+ const bad = valuesOf(ast).find((value) => value.value.includes('%%'));
275
+ return bad
276
+ ? `AMPscript can't safely hold "%%" in a value ("${bad.value}"), because it can end the AMPscript block. Use ${HANDLEBARS_ALTERNATIVE} instead.`
277
+ : null;
278
+ }
279
+
280
+ /**
281
+ * Checks that the query lists its columns (Next reads only the listed fields).
282
+ *
283
+ * @param {SelectAst} ast statement
284
+ * @param {string} label target name
285
+ * @returns {string|null} reason, or null for an explicit column list
286
+ */
287
+ function starProblem(ast, label) {
288
+ return ast.columns === '*'
289
+ ? `${label} needs the field names: list the columns in the SELECT instead of *.`
290
+ : null;
291
+ }
292
+
293
+ /**
294
+ * Checks that the query neither sorts nor limits.
295
+ *
296
+ * @param {SelectAst} ast statement
297
+ * @param {string} label target name
298
+ * @returns {string|null} reason, or null without TOP and ORDER BY
299
+ */
300
+ function sortLimitProblem(ast, label) {
301
+ const parts = [
302
+ ast.top !== null && ast.top !== undefined && 'TOP',
303
+ ast.orderBy?.length && 'ORDER BY',
304
+ ].filter(Boolean);
305
+ return parts.length
306
+ ? `${label} can't sort or limit rows in Next, so ${parts.join(' and ')} can't be converted. Remove it and sort or count in your code.`
307
+ : null;
308
+ }
309
+
310
+ /**
311
+ * Returns the first problem of a list of checks.
312
+ *
313
+ * @param {...(string|null)} problems reasons or null
314
+ * @returns {{unavailable: string}|null} the first reason, or null
315
+ */
316
+ function firstProblem(...problems) {
317
+ const reason = problems.find(Boolean);
318
+ return reason ? { unavailable: reason } : null;
319
+ }
320
+
321
+ /**
322
+ * Finishes an emitter result: sorts spans by position.
323
+ *
324
+ * @param {CodeWriter} out writer
325
+ * @param {object[]} messages messages
326
+ * @param {string[]} dropped dropped clause ids
327
+ * @returns {EmitResult} result
328
+ */
329
+ function finish(out, messages = [], dropped = []) {
330
+ out.spans.sort((a, b) => a.start - b.start || a.end - b.end);
331
+ return { code: out.code, spans: out.spans, messages, dropped };
332
+ }
333
+
334
+ // ------------------------------------------------------------------------------------------
335
+ // Handlebars CRM: query / queryFirst
336
+ // ------------------------------------------------------------------------------------------
337
+
338
+ const CRM_CAPS = {
339
+ label: 'Handlebars query',
340
+ or: true,
341
+ ops: NEXT_RULES.crmOperators.value,
342
+ like: true,
343
+ };
344
+
345
+ /**
346
+ * Writes a CRM where string with :pN placeholders, brackets around OR inside AND.
347
+ *
348
+ * @param {CodeWriter} out writer
349
+ * @param {object} expr expression node
350
+ * @param {Map<object, {clauseId: string, param: string}>} paramOf condition → parameter
351
+ * @param {'and'|'or'|null} parent type of the enclosing node
352
+ */
353
+ function writeWhere(out, expr, paramOf, parent) {
354
+ if (expr.type === 'and' || expr.type === 'or') {
355
+ const isNeedsBrackets = expr.type === 'or' && parent === 'and';
356
+ out.write(isNeedsBrackets ? '(' : '');
357
+ writeWhere(out, expr.left, paramOf, expr.type);
358
+ out.write(` ${expr.type.toUpperCase()} `);
359
+ writeWhere(out, expr.right, paramOf, expr.type);
360
+ out.write(isNeedsBrackets ? ')' : '');
361
+ return;
362
+ }
363
+ const { clauseId, param } = paramOf.get(expr);
364
+ const op = expr.type === 'like' ? 'LIKE' : NEXT_RULES.crmOperators.value[expr.op];
365
+ out.mark(clauseId, `${expr.column} ${op} :${param}`);
366
+ }
367
+
368
+ /**
369
+ * Writes the named parameters of a CRM call: `type`, `object`, `fields`, `where`, `params`,
370
+ * `sortBy` and `limit`.
371
+ *
372
+ * @param {CodeWriter} out writer
373
+ * @param {SelectAst} ast statement
374
+ * @param {Map<object, string>} idOf node → clause id
375
+ * @param {{limit: boolean}} parts which optional parts to write
376
+ */
377
+ function writeCrmArguments(out, ast, idOf, parts) {
378
+ out.write('type="CRM" object=').mark('from', hbString(ast.from.name));
379
+ out.write(' fields="');
380
+ for (const [index, column] of ast.columns.entries()) {
381
+ out.write(index ? ',' : '').mark(idOf.get(column), column.name);
382
+ }
383
+ out.write('"');
384
+ if (ast.where) {
385
+ const conditions = conditionsOf(ast.where);
386
+ const paramOf = new Map(
387
+ conditions.map((node, index) => [
388
+ node,
389
+ { clauseId: idOf.get(node), param: `p${index + 1}` },
390
+ ]),
391
+ );
392
+ out.write(' where="');
393
+ writeWhere(out, ast.where, paramOf, null);
394
+ out.write('" params=(hash');
395
+ for (const node of conditions) {
396
+ const { clauseId, param } = paramOf.get(node);
397
+ out.write(' ').mark(
398
+ clauseId,
399
+ `${param}=${hbValue(node.type === 'like' ? node.pattern : node.value)}`,
400
+ );
401
+ }
402
+ out.write(')');
403
+ }
404
+ if (ast.orderBy?.length) {
405
+ const [item] = ast.orderBy;
406
+ out.write(' sortBy="').mark(idOf.get(item), `${item.column} ${item.direction}`).write('"');
407
+ }
408
+ if (parts.limit && ast.top !== null && ast.top !== undefined) {
409
+ out.write(' ').mark('top', `limit=${ast.top}`);
410
+ }
411
+ }
412
+
413
+ /**
414
+ * Shared checks of the CRM Handlebars targets.
415
+ *
416
+ * @param {SelectAst} ast statement
417
+ * @param {string} label target name
418
+ * @returns {{unavailable: string}|null} reason, or null when the query fits
419
+ */
420
+ function crmProblem(ast, label) {
421
+ return firstProblem(
422
+ starProblem(ast, label),
423
+ nameProblem(ast),
424
+ ast.where && whereProblem(ast.where, { ...CRM_CAPS, label }),
425
+ ast.orderBy?.length > 1 &&
426
+ 'Next sorts by one field only (sortBy="Field ASC"). Sort by one column, or sort the rows in your code.',
427
+ hbValueProblem(ast),
428
+ );
429
+ }
430
+
431
+ /**
432
+ * Emits `{{#each (query type="CRM" …)}}` with one `{{Field}}` line per column. Values become
433
+ * `:pN` placeholders with `params=(hash …)`, ORDER BY becomes `sortBy`, TOP `limit`.
434
+ *
435
+ * @param {SelectAst} ast statement
436
+ * @param {NextEmitOptions} [options] options
437
+ * @returns {EmitResult|{unavailable: string}} code or the reason it cannot be generated
438
+ */
439
+ export function emitHandlebarsQuery(ast, options = {}) {
440
+ const problem = crmProblem(ast, 'Handlebars query');
441
+ if (problem) {
442
+ return problem;
443
+ }
444
+ const { idOf } = collectClauses(ast, options.sourceText);
445
+ const out = new CodeWriter();
446
+ out.write('{{#each (query ');
447
+ writeCrmArguments(out, ast, idOf, { limit: true });
448
+ out.write(')}}\n');
449
+ for (const column of ast.columns) {
450
+ out.write(`${INDENT}{{${column.name}}}\n`);
451
+ }
452
+ out.write('{{/each}}');
453
+ return finish(out);
454
+ }
455
+
456
+ /**
457
+ * Emits `{{get (queryFirst type="CRM" …) "Field"}}` for a query with exactly one column. TOP
458
+ * 1 maps to queryFirst itself; another TOP is dropped.
459
+ *
460
+ * @param {SelectAst} ast statement
461
+ * @param {NextEmitOptions} [options] options
462
+ * @returns {EmitResult|{unavailable: string}} code or the reason it cannot be generated
463
+ */
464
+ export function emitHandlebarsQueryFirst(ast, options = {}) {
465
+ const problem =
466
+ crmProblem(ast, 'Handlebars queryFirst') ??
467
+ firstProblem(
468
+ ast.columns.length !== 1 &&
469
+ 'queryFirst reads the value of a single field. Select exactly one column, or use the Handlebars query output with TOP 1.',
470
+ );
471
+ if (problem) {
472
+ return problem;
473
+ }
474
+ const { clauses, idOf } = collectClauses(ast, options.sourceText);
475
+ const out = new CodeWriter();
476
+ out.write('{{get (')
477
+ .mark(ast.top === 1 ? 'top' : undefined, 'queryFirst')
478
+ .write(' ');
479
+ writeCrmArguments(out, ast, idOf, { limit: false });
480
+ const [column] = ast.columns;
481
+ out.write(') ').mark(idOf.get(column), hbString(column.name)).write('}}');
482
+ const messages = [];
483
+ const dropped = [];
484
+ if (ast.top !== null && ast.top !== undefined && ast.top !== 1) {
485
+ const topClause = clauses.find((clause) => clause.clauseId === 'top');
486
+ messages.push(
487
+ createMessage(
488
+ 'warning',
489
+ TOP_DROPPED,
490
+ `queryFirst returns one row, so TOP ${ast.top} is left out. Use the Handlebars query output to read ${ast.top} rows.`,
491
+ topClause?.loc ?? ast.loc,
492
+ ),
493
+ );
494
+ dropped.push('top');
495
+ }
496
+ messages.push(
497
+ createMessage(
498
+ 'info',
499
+ LOOKUP_FIRST_ROW_ONLY,
500
+ `queryFirst returns only the ${column.name} value of the first matching record${ast.orderBy?.length ? ' in the sortBy order' : ''}. Use the Handlebars query output to read every match.`,
501
+ column.loc,
502
+ ),
503
+ );
504
+ return finish(out, messages, dropped);
505
+ }
506
+
507
+ // ------------------------------------------------------------------------------------------
508
+ // Handlebars MO: query with inline filters
509
+ // ------------------------------------------------------------------------------------------
510
+
511
+ const MO_QUERY_CAPS = {
512
+ label: 'A Handlebars query on a marketing object',
513
+ or: false,
514
+ ops: Object.freeze({ '=': '=' }),
515
+ like: false,
516
+ };
517
+
518
+ /**
519
+ * Warns that Next returned one record when a marketing object filter matched two
520
+ * (NEXT_RULES.moOneMatch).
521
+ *
522
+ * @param {SelectAst} ast statement
523
+ * @returns {import('./messages.js').Message} warning
524
+ */
525
+ function moOneMatchMessage(ast) {
526
+ return createMessage(
527
+ 'warning',
528
+ MO_ONE_MATCH,
529
+ 'In our Next test, a marketing object filter that matched two records returned only one of them. Filter on the key field when every match matters.',
530
+ ast.where?.loc ?? ast.loc,
531
+ );
532
+ }
533
+
534
+ /**
535
+ * Checks that no field is used in two conditions of a marketing object filter.
536
+ *
537
+ * @param {SelectAst} ast statement
538
+ * @param {string} reason message for the repeated field
539
+ * @returns {string|null} reason, or null when every field appears once
540
+ */
541
+ function moRepeatedFieldProblem(ast, reason) {
542
+ const seen = new Set();
543
+ for (const { column } of conditionsOf(ast.where)) {
544
+ if (seen.has(column.toLowerCase())) {
545
+ return `${reason} (${column}).`;
546
+ }
547
+ seen.add(column.toLowerCase());
548
+ }
549
+ return null;
550
+ }
551
+
552
+ /**
553
+ * Emits `{{#each (query type="MO" object="X" Field="v" …)}}` with one `{{Field}}` line per
554
+ * column: inline filters on any fields (AND), `limit` for TOP; no sorting (NEXT_RULES.moSortBy).
555
+ *
556
+ * @param {SelectAst} ast statement
557
+ * @param {NextEmitOptions} [options] options
558
+ * @returns {EmitResult|{unavailable: string}} code or the reason it cannot be generated
559
+ */
560
+ export function emitHandlebarsQueryMo(ast, options = {}) {
561
+ const label = 'Handlebars query on a marketing object';
562
+ const problem = firstProblem(
563
+ starProblem(ast, label),
564
+ nameProblem(ast),
565
+ !ast.where &&
566
+ "A marketing object query needs at least one filter such as WHERE Field = 'value'; Next fails without one.",
567
+ ast.where && whereProblem(ast.where, MO_QUERY_CAPS),
568
+ ast.where &&
569
+ moRepeatedFieldProblem(
570
+ ast,
571
+ 'A marketing object query can name each field once, so one field cannot have two conditions',
572
+ ),
573
+ ast.orderBy?.length &&
574
+ `${label} can't sort in Next (sortBy fails), so ORDER BY can't be converted. Remove it and sort in your code.`,
575
+ hbValueProblem(ast),
576
+ );
577
+ if (problem) {
578
+ return problem;
579
+ }
580
+ const { idOf } = collectClauses(ast, options.sourceText);
581
+ const out = new CodeWriter();
582
+ out.write('{{#each (query type="MO" object=').mark('from', hbString(ast.from.name));
583
+ for (const node of conditionsOf(ast.where)) {
584
+ out.write(' ').mark(idOf.get(node), `${node.column}=${hbValue(node.value)}`);
585
+ }
586
+ if (ast.top !== null && ast.top !== undefined) {
587
+ out.write(' ').mark('top', `limit=${ast.top}`);
588
+ }
589
+ out.write(')}}\n');
590
+ for (const column of ast.columns) {
591
+ out.write(INDENT).mark(idOf.get(column), `{{${column.name}}}`).write('\n');
592
+ }
593
+ out.write('{{/each}}');
594
+ return finish(out, [moOneMatchMessage(ast)]);
595
+ }
596
+
597
+ // ------------------------------------------------------------------------------------------
598
+ // AMPscript: RetrieveSalesforceObjects (CRM), LookupRows (MO)
599
+ // ------------------------------------------------------------------------------------------
600
+
601
+ const RSO_CAPS = {
602
+ label: 'RetrieveSalesforceObjects',
603
+ or: false,
604
+ orHint: ` Use ${HANDLEBARS_ALTERNATIVE} instead.`,
605
+ ops: NEXT_RULES.rsoOperators.value,
606
+ like: true,
607
+ };
608
+
609
+ /**
610
+ * Emits AMPscript `RetrieveSalesforceObjects("Object", "F1,F2", "Field", "op", "v", …)` plus
611
+ * a FOR loop with `RowCount` / `Row` / `Field`. AND only; values and operators are strings.
612
+ *
613
+ * @param {SelectAst} ast statement
614
+ * @param {NextEmitOptions} [options] options
615
+ * @returns {EmitResult|{unavailable: string}} code or the reason it cannot be generated
616
+ */
617
+ export function emitAmpscriptRso(ast, options = {}) {
618
+ const label = 'RetrieveSalesforceObjects';
619
+ const problem = firstProblem(
620
+ starProblem(ast, label),
621
+ nameProblem(ast),
622
+ !ast.where &&
623
+ `${label} needs at least one condition such as WHERE Field = 'value'. Use ${HANDLEBARS_ALTERNATIVE} to read records without a condition.`,
624
+ ast.where && whereProblem(ast.where, RSO_CAPS),
625
+ ast.where && repeatedFieldProblem(ast),
626
+ sortLimitProblem(ast, label),
627
+ ampValueProblem(ast),
628
+ );
629
+ if (problem) {
630
+ return problem;
631
+ }
632
+ const { idOf } = collectClauses(ast, options.sourceText);
633
+ const out = new CodeWriter();
634
+ out.write('%%[\nSET @rows = RetrieveSalesforceObjects(')
635
+ .mark('from', ampString(ast.from.name))
636
+ .write(', "');
637
+ for (const [index, column] of ast.columns.entries()) {
638
+ out.write(index ? ',' : '').mark(idOf.get(column), column.name);
639
+ }
640
+ out.write('"');
641
+ for (const node of conditionsOf(ast.where)) {
642
+ const op = node.type === 'like' ? 'LIKE' : NEXT_RULES.rsoOperators.value[node.op];
643
+ const value = node.type === 'like' ? node.pattern : node.value;
644
+ out.write(', ').region(idOf.get(node), () => {
645
+ out.write(`${ampString(node.column)}, ${ampString(op)}, ${ampString(value.value)}`);
646
+ });
647
+ }
648
+ out.write(')\n');
649
+ writeAmpLoop(
650
+ out,
651
+ ast.columns.map((column) => ({ name: column.name })),
652
+ );
653
+ out.write(']%%');
654
+ return finish(out);
655
+ }
656
+
657
+ /**
658
+ * Checks that no field is used in two conditions: RetrieveSalesforceObjects returns no rows
659
+ * then (NEXT_RULES.rsoDistinctFields).
660
+ *
661
+ * @param {SelectAst} ast statement
662
+ * @returns {string|null} reason, or null when every field appears once
663
+ */
664
+ function repeatedFieldProblem(ast) {
665
+ const seen = new Set();
666
+ for (const { column } of conditionsOf(ast.where)) {
667
+ const name = column.toLowerCase();
668
+ if (seen.has(name)) {
669
+ return rsoRepeatedFieldMessage(column);
670
+ }
671
+ seen.add(name);
672
+ }
673
+ return null;
674
+ }
675
+
676
+ /**
677
+ * Explains why RetrieveSalesforceObjects can't use one field in two conditions (shared with
678
+ * the reverse parser).
679
+ *
680
+ * @param {string} column the repeated field
681
+ * @returns {string} message
682
+ */
683
+ export function rsoRepeatedFieldMessage(column) {
684
+ return `RetrieveSalesforceObjects returns no rows in Next when the same field is used in two conditions (${column}). Use ${HANDLEBARS_ALTERNATIVE} instead.`;
685
+ }
686
+
687
+ /**
688
+ * Explains why LookupRows can't use one field in two pairs in Next (shared with the reverse
689
+ * parser; NEXT_RULES.lookupRowsDistinctFields).
690
+ *
691
+ * @returns {string} message without the field and the final full stop
692
+ */
693
+ export function lookupRowsRepeatedFieldMessage() {
694
+ return 'LookupRows in Next uses only the last pair when the same field appears in two pairs, so the conditions are not combined';
695
+ }
696
+
697
+ const LOOKUP_ROWS_CAPS = {
698
+ label: 'LookupRows',
699
+ or: false,
700
+ ops: Object.freeze({ '=': '=' }),
701
+ like: false,
702
+ };
703
+
704
+ /**
705
+ * Emits AMPscript `LookupRows("Object", "Field", "v", …)` on a marketing object (same code as
706
+ * the Engagement output). Equals + AND only; no TOP / ORDER BY (LookupOrderedRows fails in
707
+ * Next).
708
+ *
709
+ * @param {SelectAst} ast statement
710
+ * @param {NextEmitOptions} [options] options
711
+ * @returns {EmitResult|{unavailable: string}} code or the reason it cannot be generated
712
+ */
713
+ export function emitAmpscriptLookupRowsMo(ast, options = {}) {
714
+ const problem = firstProblem(
715
+ nameProblem(ast),
716
+ !ast.where && "LookupRows needs at least one condition such as WHERE Field = 'value'.",
717
+ ast.where && whereProblem(ast.where, LOOKUP_ROWS_CAPS),
718
+ ast.where && moRepeatedFieldProblem(ast, lookupRowsRepeatedFieldMessage()),
719
+ sortLimitProblem(ast, 'LookupRows'),
720
+ ampValueProblem(ast),
721
+ );
722
+ if (problem) {
723
+ return problem;
724
+ }
725
+ const result = emitAmpscriptLookupRows(ast, {
726
+ deKey: ast.from.name,
727
+ sourceText: options.sourceText,
728
+ });
729
+ return { ...result, messages: [...(result.messages ?? []), moOneMatchMessage(ast)] };
730
+ }
731
+
732
+ // ------------------------------------------------------------------------------------------
733
+ // Registry
734
+ // ------------------------------------------------------------------------------------------
735
+
736
+ /**
737
+ * Marketing Cloud Next targets in display order. `dataSource` is the data source the target
738
+ * reads (`CRM` = Sales Cloud object, `MO` = marketing object); `normalize` holds the round-trip
739
+ * flags (see `normalizeSql`). Handlebars keeps the value type (`p1="5"` is text, `p1=5` a
740
+ * number), so its targets compare typed; AMPscript writes every value as a string.
741
+ *
742
+ * @type {ReadonlyArray<{id: string, language: 'handlebars'|'ampscript', label: string,
743
+ * dataSource: 'CRM'|'MO', emit: (ast: SelectAst, options?: NextEmitOptions) =>
744
+ * EmitResult|{unavailable: string}, normalize: {dropTop?: boolean, isTyped?: boolean}}>}
745
+ */
746
+ export const MCN_TARGETS = Object.freeze([
747
+ {
748
+ id: 'handlebars-query',
749
+ language: 'handlebars',
750
+ label: 'query',
751
+ dataSource: 'CRM',
752
+ emit: emitHandlebarsQuery,
753
+ normalize: { isTyped: true },
754
+ },
755
+ {
756
+ id: 'handlebars-queryfirst',
757
+ language: 'handlebars',
758
+ label: 'queryFirst',
759
+ dataSource: 'CRM',
760
+ emit: emitHandlebarsQueryFirst,
761
+ // queryFirst always returns one row: TOP 1 is implied by the call itself
762
+ normalize: { dropTop: true, isTyped: true },
763
+ },
764
+ {
765
+ id: 'ampscript-rso',
766
+ language: 'ampscript',
767
+ label: 'RetrieveSalesforceObjects',
768
+ dataSource: 'CRM',
769
+ emit: emitAmpscriptRso,
770
+ normalize: {},
771
+ },
772
+ {
773
+ id: 'handlebars-query-mo',
774
+ language: 'handlebars',
775
+ label: 'query',
776
+ dataSource: 'MO',
777
+ emit: emitHandlebarsQueryMo,
778
+ normalize: { isTyped: true },
779
+ },
780
+ {
781
+ id: 'ampscript-lookuprows-mo',
782
+ language: 'ampscript',
783
+ label: 'LookupRows',
784
+ dataSource: 'MO',
785
+ emit: emitAmpscriptLookupRowsMo,
786
+ normalize: {},
787
+ },
788
+ ]);