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.
package/src/convert.js ADDED
@@ -0,0 +1,431 @@
1
+ /**
2
+ * `convert()` — the single entry point the sfmc.guide page and the browser extension call.
3
+ *
4
+ * Direction `toCode`: SQL → one output per target (code, or the reason the target cannot
5
+ * express the query), clause spans, a clause map and a round-trip check (the code is read
6
+ * back with the reverse parser and compared with the query, minus the clauses the target
7
+ * dropped). Direction `toSql`: lookup code → canonical SQL.
8
+ *
9
+ * Platform `mce` (Marketing Cloud Engagement) reads data extensions with SSJS / AMPscript;
10
+ * `mcn` (Marketing Cloud Next) reads Sales Cloud objects (`dataSource: 'CRM'`) or marketing
11
+ * objects (`'MO'`) with Handlebars / AMPscript, limited to what the live probes proved (see
12
+ * `NEXT_RULES` in emit-mcn.js).
13
+ */
14
+
15
+ import { collectClauses, locFromOffsets } from './clauses.js';
16
+ import { MCE_TARGETS } from './emit-mce.js';
17
+ import { MCN_TARGETS } from './emit-mcn.js';
18
+ import {
19
+ DE_KEY_ASSUMED,
20
+ ORDER_BY_NEEDS_TOP,
21
+ SELECT_STAR_NEEDS_COLUMNS,
22
+ createMessage,
23
+ } from './messages.js';
24
+ import { parseAmpscript } from './parse-ampscript.js';
25
+ import { parseHandlebars } from './parse-handlebars.js';
26
+ import { parseSsjs } from './parse-ssjs.js';
27
+ import { normalizeSql, printSql, printSqlWithSpans } from './print-sql.js';
28
+ import { parseSql } from './sql-parser.js';
29
+
30
+ /**
31
+ * @typedef {import('./sql-parser.js').SelectAst} SelectAst
32
+ * @typedef {import('./messages.js').Message} Message
33
+ * @typedef {import('./clauses.js').Span} Span
34
+ */
35
+
36
+ /**
37
+ * @typedef {object} ConvertOptions
38
+ * @property {'mce'|'mcn'} [platform] target platform (default 'mce')
39
+ * @property {'toCode'|'toSql'} [direction] conversion direction (default 'toCode')
40
+ * @property {string} [deName] data extension name (toSql: used when the code does not carry it)
41
+ * @property {string} [deKey] data extension external key (default: the name)
42
+ * @property {string[]} [columns] the columns `SELECT *` stands for
43
+ * @property {'CRM'|'MO'} [dataSource] Next data source: Sales Cloud object (default) or
44
+ * marketing object
45
+ * @property {{fields: {name: string}[]}} [schema] data extension fields
46
+ * @property {{rowsAsObjects?: boolean, paging?: boolean}} [output] WSProxy output options
47
+ */
48
+
49
+ /**
50
+ * @typedef {object} Output
51
+ * @property {string} id target id, e.g. `ssjs-wsproxy`
52
+ * @property {'ssjs'|'ampscript'|'handlebars'|'sql'} language output language
53
+ * @property {string} label tab label
54
+ * @property {string} [code] generated code (absent when unavailable)
55
+ * @property {string} [unavailable] plain reason the target cannot express the input
56
+ * @property {Span[]} spans clause spans in `code`
57
+ * @property {Message[]} [messages] messages that apply to this output only
58
+ * @property {string[]} [dropped] clause ids this output leaves out
59
+ * @property {{ok: boolean, sql: string, note?: string}} [roundTrip] round trip of this output
60
+ */
61
+
62
+ /**
63
+ * @typedef {object} ClauseMapEntry
64
+ * @property {string} outputId output the entry belongs to
65
+ * @property {string} clauseId clause id
66
+ * @property {string} sql SQL text of the clause
67
+ * @property {string} code code text of the clause (span texts joined by a line break)
68
+ * @property {object|null} loc location in the input text
69
+ * @property {boolean} dropped true when the output leaves the clause out
70
+ */
71
+
72
+ /**
73
+ * @typedef {object} ConvertResult
74
+ * @property {Output[]} outputs one entry per target
75
+ * @property {Message[]} messages messages about the input
76
+ * @property {ClauseMapEntry[]} clauseMap clause ↔ code mapping for every available output
77
+ * @property {{ok: boolean, sql: string, note?: string, skipped?: boolean}} roundTrip round trip
78
+ * of the first available output (toCode) or of the printed SQL (toSql); `skipped` is true when
79
+ * there was nothing to compare (a filter without a data extension name)
80
+ */
81
+
82
+ /**
83
+ * Reads Next AMPscript back (LookupRows on a marketing object, RetrieveSalesforceObjects).
84
+ *
85
+ * @param {string} code AMPscript code
86
+ * @returns {{ast: SelectAst|null, messages: Message[], meta: object}} parse result
87
+ */
88
+ function parseNextAmpscript(code) {
89
+ return parseAmpscript(code, { platform: 'mcn' });
90
+ }
91
+
92
+ /**
93
+ * Returns the reverse parser of a target.
94
+ *
95
+ * @param {{language: string}} target target
96
+ * @param {'mce'|'mcn'} platform platform
97
+ * @returns {(code: string) => {ast: SelectAst|null, messages: Message[], meta: object}} parser
98
+ */
99
+ function reverseParserOf(target, platform) {
100
+ if (target.language === 'handlebars') {
101
+ return parseHandlebars;
102
+ }
103
+ if (target.language === 'ssjs') {
104
+ return parseSsjs;
105
+ }
106
+ return platform === 'mcn' ? parseNextAmpscript : parseAmpscript;
107
+ }
108
+
109
+ /**
110
+ * Builds the list of unavailable outputs for a target list.
111
+ *
112
+ * @param {ReadonlyArray<{id: string, language: string, label: string}>} targets targets
113
+ * @param {string} reason plain reason
114
+ * @returns {Output[]} outputs
115
+ */
116
+ function unavailableOutputs(targets, reason) {
117
+ return targets.map((target) => ({
118
+ id: target.id,
119
+ language: target.language,
120
+ label: target.label,
121
+ unavailable: reason,
122
+ spans: [],
123
+ }));
124
+ }
125
+
126
+ /**
127
+ * Returns the column list `*` stands for, if known.
128
+ *
129
+ * @param {ConvertOptions} options options
130
+ * @returns {string[]|undefined} column names
131
+ */
132
+ function starColumns(options) {
133
+ if (options.columns?.length) {
134
+ return options.columns;
135
+ }
136
+ if (options.schema?.fields?.length) {
137
+ return options.schema.fields.map((field) => field.name);
138
+ }
139
+ return;
140
+ }
141
+
142
+ /**
143
+ * Collects the code text of a clause from the spans of an output.
144
+ *
145
+ * @param {string} code generated code
146
+ * @param {Span[]} spans spans
147
+ * @param {string} clauseId clause id
148
+ * @returns {string} span texts joined by a line break
149
+ */
150
+ function spanText(code, spans, clauseId) {
151
+ return spans
152
+ .filter((span) => span.clauseId === clauseId)
153
+ .map((span) => code.slice(span.start, span.end))
154
+ .join('\n');
155
+ }
156
+
157
+ /**
158
+ * Reads generated code back and compares it with the query.
159
+ *
160
+ * @param {SelectAst} ast parsed query
161
+ * @param {object} target target from `MCE_TARGETS`
162
+ * @param {{code: string, dropped: string[]}} result emitter result
163
+ * @param {ConvertOptions} options options
164
+ * @returns {{ok: boolean, sql: string, note?: string}} round trip
165
+ */
166
+ function roundTripOf(ast, target, result, options) {
167
+ const back = reverseParserOf(target, options.platform)(result.code);
168
+ if (!back.ast) {
169
+ const reason = back.messages.find((message) => message.severity === 'error');
170
+ return {
171
+ ok: false,
172
+ sql: '',
173
+ note: `The generated ${target.label} code could not be read back${reason ? `: ${reason.message}` : '.'}`,
174
+ };
175
+ }
176
+ const dropTop = result.dropped.includes('top') || Boolean(target.normalize.dropTop);
177
+ const dropOrderBy = result.dropped.some((clauseId) => clauseId.startsWith('order-'));
178
+ const flags = { ...target.normalize, columns: starColumns(options), dropTop, dropOrderBy };
179
+ const isOk = normalizeSql(ast, flags) === normalizeSql(back.ast, flags);
180
+ const left = [result.dropped.includes('top') && 'TOP', dropOrderBy && 'ORDER BY'].filter(
181
+ Boolean,
182
+ );
183
+ let note;
184
+ if (!isOk) {
185
+ note = `Reading the ${target.label} code back gives a different query.`;
186
+ } else if (left.length) {
187
+ note = `Same query without ${left.join(' and ')}, which ${target.label} leaves out.`;
188
+ }
189
+ const sql = printSql(back.ast, { isTyped: Boolean(target.normalize.isTyped) });
190
+ return note ? { ok: isOk, sql, note } : { ok: isOk, sql };
191
+ }
192
+
193
+ /**
194
+ * SQL → code.
195
+ *
196
+ * @param {string} input SQL text
197
+ * @param {ConvertOptions} options options
198
+ * @returns {ConvertResult} result
199
+ */
200
+ function convertToCode(input, options) {
201
+ const { ast, messages } = parseSql(input);
202
+ const targets =
203
+ options.platform === 'mcn'
204
+ ? MCN_TARGETS.filter((target) => target.dataSource === options.dataSource)
205
+ : MCE_TARGETS;
206
+ if (!ast) {
207
+ return {
208
+ outputs: unavailableOutputs(targets, 'Fix the errors in the query first.'),
209
+ messages,
210
+ clauseMap: [],
211
+ roundTrip: { ok: false, sql: '', note: 'The query has errors.' },
212
+ };
213
+ }
214
+ if (options.platform === 'mcn') {
215
+ const emitOptions = { sourceText: input };
216
+ return { messages, ...emitAll(ast, input, targets, emitOptions, options) };
217
+ }
218
+ if (!options.deKey) {
219
+ messages.push(
220
+ createMessage(
221
+ 'info',
222
+ DE_KEY_ASSUMED,
223
+ `No external key was given, so the code uses the name "${ast.from.name}" as the key. Enter the data extension's external key in the settings if it differs.`,
224
+ ast.from.loc,
225
+ ),
226
+ );
227
+ }
228
+ if (ast.columns === '*' && !starColumns(options)) {
229
+ const star = input.indexOf('*', ast.loc.start);
230
+ const isFound = star !== -1 && star < ast.from.loc.start;
231
+ messages.push(
232
+ createMessage(
233
+ 'warning',
234
+ SELECT_STAR_NEEDS_COLUMNS,
235
+ 'WSProxy needs the column names that * stands for. Enter them in the settings, or list the columns in the SELECT.',
236
+ isFound ? locFromOffsets(input, star, star + 1) : ast.loc,
237
+ ),
238
+ );
239
+ }
240
+ const emitOptions = {
241
+ deKey: options.deKey,
242
+ columns: options.columns,
243
+ schema: options.schema,
244
+ output: options.output,
245
+ sourceText: input,
246
+ };
247
+ return { messages, ...emitAll(ast, input, targets, emitOptions, options) };
248
+ }
249
+
250
+ /**
251
+ * Runs every target's emitter and collects outputs, the clause map and the round trip.
252
+ *
253
+ * @param {SelectAst} ast parsed query
254
+ * @param {string} input SQL text
255
+ * @param {ReadonlyArray<object>} targets targets with `emit` and `normalize`
256
+ * @param {object} emitOptions options passed to the emitters
257
+ * @param {ConvertOptions} options convert options
258
+ * @returns {{outputs: Output[], clauseMap: ClauseMapEntry[], roundTrip: object}} result parts
259
+ */
260
+ function emitAll(ast, input, targets, emitOptions, options) {
261
+ const { clauses } = collectClauses(ast, input);
262
+ const outputs = [];
263
+ const clauseMap = [];
264
+ for (const target of targets) {
265
+ const result = target.emit(ast, emitOptions);
266
+ const base = { id: target.id, language: target.language, label: target.label };
267
+ if (result.unavailable) {
268
+ outputs.push({ ...base, unavailable: result.unavailable, spans: [] });
269
+ continue;
270
+ }
271
+ outputs.push({
272
+ ...base,
273
+ code: result.code,
274
+ spans: result.spans,
275
+ messages: result.messages,
276
+ dropped: result.dropped,
277
+ roundTrip: roundTripOf(ast, target, result, options),
278
+ });
279
+ for (const clause of clauses) {
280
+ clauseMap.push({
281
+ outputId: target.id,
282
+ clauseId: clause.clauseId,
283
+ sql: clause.loc ? input.slice(clause.loc.start, clause.loc.end) : '',
284
+ code: spanText(result.code, result.spans, clause.clauseId),
285
+ loc: clause.loc,
286
+ dropped: result.dropped.includes(clause.clauseId),
287
+ });
288
+ }
289
+ }
290
+ const first = outputs.find((output) => output.roundTrip);
291
+ return {
292
+ outputs,
293
+ clauseMap,
294
+ roundTrip: first
295
+ ? first.roundTrip
296
+ : { ok: false, sql: '', note: 'No target can express this query.' },
297
+ };
298
+ }
299
+
300
+ /**
301
+ * Reads lookup code with the matching reverse parser (AMPscript when the code looks like
302
+ * AMPscript, else SSJS; the other parser is tried when the first one fails).
303
+ *
304
+ * @param {string} input code
305
+ * @param {'mce'|'mcn'} platform platform (Next reads Handlebars and Next AMPscript)
306
+ * @returns {{ast: SelectAst|null, messages: Message[], meta: object}} parse result
307
+ */
308
+ function parseCode(input, platform) {
309
+ const isLooksLikeAmpscript = /%%\[|%%=|\bSET\s+@/i.test(input);
310
+ let parsers;
311
+ if (platform === 'mcn') {
312
+ parsers = /\{\{/.test(input)
313
+ ? [parseHandlebars, parseNextAmpscript]
314
+ : [parseNextAmpscript, parseHandlebars];
315
+ } else {
316
+ parsers = isLooksLikeAmpscript ? [parseAmpscript, parseSsjs] : [parseSsjs, parseAmpscript];
317
+ }
318
+ const primary = parsers[0](input);
319
+ if (primary.ast) {
320
+ return primary;
321
+ }
322
+ const secondary = parsers[1](input);
323
+ return secondary.ast ? secondary : primary;
324
+ }
325
+
326
+ /**
327
+ * A query activity rejects ORDER BY without TOP (live check 2026-11-26, DB
328
+ * `entries/mce/mce-sql-query-activity-where-semantics.json`): tell the reader when the printed
329
+ * SQL sorts every row.
330
+ *
331
+ * @param {SelectAst} ast statement read from the code
332
+ * @param {'mce'|'mcn'} platform platform
333
+ * @returns {Message[]} the info message, or none
334
+ */
335
+ function orderByNeedsTop(ast, platform) {
336
+ if (platform !== 'mce' || !ast.orderBy?.length || (ast.top !== null && ast.top !== undefined)) {
337
+ return [];
338
+ }
339
+ return [
340
+ createMessage(
341
+ 'info',
342
+ ORDER_BY_NEEDS_TOP,
343
+ 'The SQL sorts without TOP. A query activity in Automation Studio rejects ORDER BY without TOP, so add TOP with the number of rows you need before running it there.',
344
+ ast.orderBy[0].loc ?? ast.loc,
345
+ ),
346
+ ];
347
+ }
348
+
349
+ /**
350
+ * Code → SQL.
351
+ *
352
+ * @param {string} input lookup code
353
+ * @param {ConvertOptions} options options
354
+ * @returns {ConvertResult} result
355
+ */
356
+ function convertToSql(input, options) {
357
+ const base = { id: 'sql', language: 'sql', label: 'SQL' };
358
+ const back = parseCode(typeof input === 'string' ? input : '', options.platform);
359
+ if (!back.ast) {
360
+ return {
361
+ outputs: [{ ...base, unavailable: 'Fix the errors in the code first.', spans: [] }],
362
+ messages: back.messages,
363
+ clauseMap: [],
364
+ roundTrip: { ok: false, sql: '', note: 'The code has errors.' },
365
+ };
366
+ }
367
+ const ast = back.ast;
368
+ // a bare filter object (or a key-only WSProxy call) does not carry the name
369
+ if (options.deName && (!back.meta?.deName || !ast.from.name)) {
370
+ ast.from = { ...ast.from, name: options.deName };
371
+ }
372
+ // Handlebars keeps the value type: p1="5" is text and must not print as 5
373
+ const typed = { isTyped: back.meta?.target?.startsWith('handlebars') ?? false };
374
+ const { sql, spans } = printSqlWithSpans(ast, typed);
375
+ const clauseMap = collectClauses(ast).clauses.map((clause) => ({
376
+ outputId: 'sql',
377
+ clauseId: clause.clauseId,
378
+ sql: spanText(sql, spans, clause.clauseId),
379
+ code: clause.loc ? input.slice(clause.loc.start, clause.loc.end) : '',
380
+ loc: clause.loc,
381
+ dropped: false,
382
+ }));
383
+ if (!ast.from.name) {
384
+ // a bare filter without a FROM header and without options.deName: nothing to compare
385
+ return {
386
+ outputs: [{ ...base, code: sql, spans }],
387
+ messages: back.messages,
388
+ clauseMap,
389
+ roundTrip: {
390
+ ok: true,
391
+ skipped: true,
392
+ sql,
393
+ note: 'The round trip is skipped because the filter does not name its data extension. Enter the data extension name in the settings.',
394
+ },
395
+ };
396
+ }
397
+ const again = parseSql(sql);
398
+ const isOk = Boolean(again.ast) && normalizeSql(again.ast, typed) === normalizeSql(ast, typed);
399
+ return {
400
+ outputs: [{ ...base, code: sql, spans }],
401
+ messages: [...back.messages, ...orderByNeedsTop(ast, options.platform)],
402
+ clauseMap,
403
+ roundTrip: isOk
404
+ ? { ok: isOk, sql }
405
+ : { ok: isOk, sql, note: 'The printed SQL does not read back as the same query.' },
406
+ };
407
+ }
408
+
409
+ /**
410
+ * Converts SQL to Marketing Cloud lookup code, or lookup code back to SQL.
411
+ *
412
+ * @param {string} input SQL (toCode) or SSJS / AMPscript (toSql)
413
+ * @param {ConvertOptions} [options] options
414
+ * @returns {ConvertResult} outputs, messages, clause map and round trip
415
+ */
416
+ export function convert(input, options = {}) {
417
+ const platform = options.platform ?? 'mce';
418
+ if (platform !== 'mce' && platform !== 'mcn') {
419
+ throw new TypeError(`Unknown platform "${platform}". Use "mce" or "mcn".`);
420
+ }
421
+ const direction = options.direction ?? 'toCode';
422
+ if (direction !== 'toCode' && direction !== 'toSql') {
423
+ throw new TypeError(`Unknown direction "${direction}". Use "toCode" or "toSql".`);
424
+ }
425
+ const dataSource = options.dataSource ?? 'CRM';
426
+ if (dataSource !== 'CRM' && dataSource !== 'MO') {
427
+ throw new TypeError(`Unknown data source "${dataSource}". Use "CRM" or "MO".`);
428
+ }
429
+ const resolved = { ...options, platform, dataSource };
430
+ return direction === 'toSql' ? convertToSql(input, resolved) : convertToCode(input, resolved);
431
+ }