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