sfmc-sql-converter 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,296 @@
1
+ /**
2
+ * SQL printer (AST → canonical query text) and the normalization used to compare two ASTs in
3
+ * a round trip (SQL → code → SQL).
4
+ *
5
+ * Canonical text: keywords in upper case, one clause per line, `[Name]` brackets only when a
6
+ * name needs them, text in single quotes with `''` escaping, numbers unquoted. A text value
7
+ * that is a plain number without leading zeros (e.g. '500', '-2.5') prints unquoted, because
8
+ * the generated code carries every value as a string and the two forms compare as equal.
9
+ * Marketing Cloud Next keeps the type (`p1="5"` is text, `p1=5` a number): with `isTyped` the
10
+ * value kind alone decides, in printing and in the round-trip comparison.
11
+ */
12
+
13
+ import { CodeWriter, collectClauses } from './clauses.js';
14
+ import { RESERVED_WORDS } from './sql-parser.js';
15
+
16
+ /**
17
+ * @typedef {import('./sql-parser.js').SelectAst} SelectAst
18
+ * @typedef {import('./sql-parser.js').Value} Value
19
+ * @typedef {import('./clauses.js').Span} Span
20
+ */
21
+
22
+ const BARE_NAME_PATTERN = /^[\p{L}_][\p{L}\p{N}_]*$/u;
23
+ const PLAIN_NUMBER_PATTERN = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/;
24
+
25
+ /**
26
+ * Checks whether a text is a plain number without leading zeros, e.g. `500`, `-2`, `7.25`.
27
+ *
28
+ * @param {string} text value text
29
+ * @returns {boolean} true for a plain number
30
+ */
31
+ export function isPlainNumber(text) {
32
+ return PLAIN_NUMBER_PATTERN.test(text);
33
+ }
34
+
35
+ /**
36
+ * Formats a column or data extension name, adding `[ ]` only when needed.
37
+ *
38
+ * @param {string} name the name
39
+ * @returns {string} SQL name
40
+ */
41
+ export function formatName(name) {
42
+ if (BARE_NAME_PATTERN.test(name) && !RESERVED_WORDS.has(name.toUpperCase())) {
43
+ return name;
44
+ }
45
+ return `[${name.replaceAll(']', ']]')}]`;
46
+ }
47
+
48
+ /**
49
+ * Formats a literal value.
50
+ *
51
+ * @param {Value} value value node
52
+ * @param {boolean} [isTyped] true to quote every text value, even a plain number
53
+ * @returns {string} SQL literal
54
+ */
55
+ export function formatValue(value, isTyped = false) {
56
+ if (value.kind === 'number' || (!isTyped && isPlainNumber(value.value))) {
57
+ return value.value;
58
+ }
59
+ return `'${value.value.replaceAll("'", "''")}'`;
60
+ }
61
+
62
+ /**
63
+ * Writes a WHERE expression.
64
+ *
65
+ * @param {CodeWriter} out writer
66
+ * @param {object} expr expression node
67
+ * @param {Map<object, string>} idOf node → clause id
68
+ * @param {'and'|'or'|null} parent type of the enclosing node
69
+ * @param {boolean} isTyped true to quote every text value
70
+ */
71
+ function writeExpr(out, expr, idOf, parent, isTyped) {
72
+ if (expr.type === 'and' || expr.type === 'or') {
73
+ const isNeedsBrackets = expr.type === 'or' && parent === 'and';
74
+ out.write(isNeedsBrackets ? '(' : '');
75
+ writeExpr(out, expr.left, idOf, expr.type, isTyped);
76
+ out.write(` ${expr.type.toUpperCase()} `);
77
+ writeExpr(out, expr.right, idOf, expr.type, isTyped);
78
+ out.write(isNeedsBrackets ? ')' : '');
79
+ return;
80
+ }
81
+ out.mark(idOf.get(expr), formatCondition(expr, isTyped));
82
+ }
83
+
84
+ /**
85
+ * Formats a single condition.
86
+ *
87
+ * @param {object} expr condition node
88
+ * @param {boolean} isTyped true to quote every text value
89
+ * @returns {string} SQL text
90
+ */
91
+ function formatCondition(expr, isTyped) {
92
+ const column = formatName(expr.column);
93
+ const literal = (value) => formatValue(value, isTyped);
94
+ switch (expr.type) {
95
+ case 'compare': {
96
+ return `${column} ${expr.op} ${literal(expr.value)}`;
97
+ }
98
+ case 'like': {
99
+ return `${column} LIKE '${expr.pattern.value.replaceAll("'", "''")}'`;
100
+ }
101
+ case 'in': {
102
+ const values = expr.values.map((value) => literal(value)).join(', ');
103
+ return `${column} ${expr.negated ? 'NOT IN' : 'IN'} (${values})`;
104
+ }
105
+ case 'between': {
106
+ return `${column} BETWEEN ${literal(expr.low)} AND ${literal(expr.high)}`;
107
+ }
108
+ case 'null': {
109
+ return `${column} IS ${expr.negated ? 'NOT NULL' : 'NULL'}`;
110
+ }
111
+ default: {
112
+ throw new TypeError(`Unknown condition type: ${expr.type}`);
113
+ }
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Prints an AST as canonical SQL and records where each clause is in the text.
119
+ *
120
+ * @param {SelectAst} ast statement
121
+ * @param {{isTyped?: boolean}} [options] isTyped: quote every text value (Next keeps types)
122
+ * @returns {{sql: string, spans: Span[]}} SQL text and clause spans
123
+ */
124
+ export function printSqlWithSpans(ast, options = {}) {
125
+ const isTyped = Boolean(options.isTyped);
126
+ const { idOf } = collectClauses(ast);
127
+ const out = new CodeWriter();
128
+ out.write('SELECT ');
129
+ if (ast.top !== null && ast.top !== undefined) {
130
+ out.mark('top', `TOP ${ast.top}`).write(' ');
131
+ }
132
+ if (Array.isArray(ast.columns)) {
133
+ for (const [index, column] of ast.columns.entries()) {
134
+ out.write(index ? ', ' : '').mark(idOf.get(column), formatName(column.name));
135
+ }
136
+ } else {
137
+ out.write('*');
138
+ }
139
+ out.write('\nFROM ').mark('from', formatName(ast.from.name));
140
+ if (ast.where) {
141
+ out.write('\nWHERE ');
142
+ writeExpr(out, ast.where, idOf, null, isTyped);
143
+ }
144
+ if (ast.orderBy?.length) {
145
+ out.write('\nORDER BY ');
146
+ for (const [index, item] of ast.orderBy.entries()) {
147
+ out.write(index ? ', ' : '').mark(
148
+ idOf.get(item),
149
+ `${formatName(item.column)} ${item.direction}`,
150
+ );
151
+ }
152
+ }
153
+ out.spans.sort((a, b) => a.start - b.start);
154
+ return { sql: out.code, spans: out.spans };
155
+ }
156
+
157
+ /**
158
+ * Prints an AST as canonical SQL.
159
+ *
160
+ * @param {SelectAst} ast statement
161
+ * @param {{isTyped?: boolean}} [options] isTyped: quote every text value (Next keeps types)
162
+ * @returns {string} SQL text
163
+ */
164
+ export function printSql(ast, options = {}) {
165
+ return printSqlWithSpans(ast, options).sql;
166
+ }
167
+
168
+ // ------------------------------------------------------------------------------------------
169
+ // Normalization for round-trip comparison
170
+ // ------------------------------------------------------------------------------------------
171
+
172
+ /**
173
+ * @typedef {object} NormalizeOptions
174
+ * @property {string[]} [columns] column list that `*` stands for (compares `*` with an
175
+ * explicit list)
176
+ * @property {boolean} [expandIn] treat `IN (a, b)` like `= a OR = b`
177
+ * @property {boolean} [expandNotIn] treat `NOT IN (a, b)` like `<> a AND <> b`
178
+ * @property {boolean} [expandBetween] treat `BETWEEN a AND b` like `>= a AND <= b`
179
+ * @property {boolean} [dropTop] ignore TOP (the target dropped it)
180
+ * @property {boolean} [dropOrderBy] ignore ORDER BY (the target dropped it)
181
+ * @property {boolean} [isTyped] compare text and number values by their kind: '5' differs from
182
+ * 5 (Next keeps the type)
183
+ */
184
+
185
+ /**
186
+ * Normalizes a value: plain numbers compare by numeric value, everything else as text. With
187
+ * `isTyped` the value kind decides instead of the text.
188
+ *
189
+ * @param {Value} value value node
190
+ * @param {NormalizeOptions} options flags
191
+ * @returns {string} normalized value
192
+ */
193
+ function normalizeValue(value, options) {
194
+ if (options.isTyped ? value.kind === 'number' : isPlainNumber(value.value)) {
195
+ return `n:${Number(value.value)}`;
196
+ }
197
+ return `s:${value.value}`;
198
+ }
199
+
200
+ /**
201
+ * Builds an n-ary AND / OR node, flattening nested nodes of the same type.
202
+ *
203
+ * @param {'and'|'or'} type node type
204
+ * @param {Array} parts normalized children
205
+ * @returns {Array} normalized node (the only child when there is just one)
206
+ */
207
+ function junction(type, parts) {
208
+ const flat = parts.flatMap((part) => (part[0] === type ? part[1] : [part]));
209
+ return flat.length === 1 ? flat[0] : [type, flat];
210
+ }
211
+
212
+ /**
213
+ * Normalizes a WHERE expression into nested arrays.
214
+ *
215
+ * @param {object} expr expression node
216
+ * @param {NormalizeOptions} options flags
217
+ * @returns {Array} normalized expression
218
+ */
219
+ function normalizeExpr(expr, options) {
220
+ const column = expr.column?.toLowerCase();
221
+ switch (expr.type) {
222
+ case 'and':
223
+ case 'or': {
224
+ return junction(expr.type, [
225
+ normalizeExpr(expr.left, options),
226
+ normalizeExpr(expr.right, options),
227
+ ]);
228
+ }
229
+ case 'compare': {
230
+ return ['compare', expr.op, column, normalizeValue(expr.value, options)];
231
+ }
232
+ case 'like': {
233
+ return ['like', column, `s:${expr.pattern.value}`];
234
+ }
235
+ case 'in': {
236
+ const values = expr.values.map((value) => normalizeValue(value, options));
237
+ if (expr.negated && options.expandNotIn) {
238
+ return junction(
239
+ 'and',
240
+ values.map((value) => ['compare', '<>', column, value]),
241
+ );
242
+ }
243
+ if (!expr.negated && options.expandIn) {
244
+ return junction(
245
+ 'or',
246
+ values.map((value) => ['compare', '=', column, value]),
247
+ );
248
+ }
249
+ return ['in', expr.negated, column, values];
250
+ }
251
+ case 'between': {
252
+ const low = normalizeValue(expr.low, options);
253
+ const high = normalizeValue(expr.high, options);
254
+ if (options.expandBetween) {
255
+ return junction('and', [
256
+ ['compare', '>=', column, low],
257
+ ['compare', '<=', column, high],
258
+ ]);
259
+ }
260
+ return ['between', column, low, high];
261
+ }
262
+ case 'null': {
263
+ return ['null', expr.negated, column];
264
+ }
265
+ default: {
266
+ throw new TypeError(`Unknown expression type: ${expr.type}`);
267
+ }
268
+ }
269
+ }
270
+
271
+ /**
272
+ * Normalizes an AST for round-trip comparison. Two queries are equivalent when their
273
+ * normalized strings are equal. Ignored: keyword case, brackets, whitespace, literal quoting
274
+ * of plain numbers, AND / OR grouping of the same operator, name case. Optional (flags):
275
+ * IN ↔ OR chain, NOT IN ↔ AND chain, BETWEEN ↔ `>= AND <=`, `*` ↔ explicit list, and
276
+ * clauses the target dropped.
277
+ *
278
+ * @param {SelectAst} ast statement
279
+ * @param {NormalizeOptions} [options] flags
280
+ * @returns {string} normalized form
281
+ */
282
+ export function normalizeSql(ast, options = {}) {
283
+ let columns = ast.columns;
284
+ if (columns === '*' && options.columns?.length) {
285
+ columns = options.columns.map((name) => ({ name }));
286
+ }
287
+ return JSON.stringify({
288
+ top: options.dropTop ? null : (ast.top ?? null),
289
+ columns: columns === '*' ? '*' : columns.map((column) => column.name.toLowerCase()),
290
+ from: ast.from.name.toLowerCase(),
291
+ where: ast.where ? normalizeExpr(ast.where, options) : null,
292
+ orderBy: options.dropOrderBy
293
+ ? []
294
+ : (ast.orderBy ?? []).map((item) => [item.column.toLowerCase(), item.direction]),
295
+ });
296
+ }