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