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/index.js ADDED
@@ -0,0 +1,17 @@
1
+ export { parseSql } from './sql-parser.js';
2
+ export * from './messages.js';
3
+ export { convert, MCN_TARGETS } from './convert.js';
4
+ export {
5
+ MCE_TARGETS,
6
+ emitSsjsWsproxy,
7
+ emitSsjsRowsRetrieve,
8
+ emitSsjsLookupRows,
9
+ emitSsjsLookupOrderedRows,
10
+ emitAmpscriptLookupRows,
11
+ emitAmpscriptLookupOrderedRows,
12
+ emitAmpscriptLookup,
13
+ ampVariableNames,
14
+ } from './emit-mce.js';
15
+ export { printSql, printSqlWithSpans, normalizeSql } from './print-sql.js';
16
+ export { parseSsjs } from './parse-ssjs.js';
17
+ export { parseAmpscript } from './parse-ampscript.js';
package/src/like.js ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * SQL LIKE matching as observed in Marketing Cloud Engagement query activities: anchored,
3
+ * case-insensitive, `%` = any text, `_` = one character, `[…]` / `[^…]` = one character of a set
4
+ * (so `[%]` matches a literal %). Used by the parser to evaluate an ISNULL / COALESCE fallback
5
+ * at conversion time, and by the tests.
6
+ */
7
+
8
+ // one LIKE token: %, _, a character set such as [%] / [^a-c], or any single character
9
+ const LIKE_TOKEN = /%|_|\[\^?[^\]]+\]|[\s\S]/g;
10
+
11
+ /**
12
+ * Converts a LIKE pattern into a regular expression.
13
+ *
14
+ * @param {string} pattern LIKE pattern
15
+ * @returns {RegExp} case-insensitive, anchored expression
16
+ */
17
+ export function likeToRegExp(pattern) {
18
+ const source = pattern.replaceAll(LIKE_TOKEN, (token) => {
19
+ if (token === '%') {
20
+ return String.raw`[\s\S]*`;
21
+ }
22
+ if (token === '_') {
23
+ return String.raw`[\s\S]`;
24
+ }
25
+ if (token.length > 2 && token.startsWith('[')) {
26
+ const isNegated = token[1] === '^';
27
+ const body = token.slice(isNegated ? 2 : 1, -1).replaceAll(/[\\^]/g, String.raw`\$&`);
28
+ return `[${isNegated ? '^' : ''}${body}]`;
29
+ }
30
+ return token.replaceAll(/[.*+?^${}()|[\]\\/]/g, String.raw`\$&`);
31
+ });
32
+ return new RegExp(`^${source}$`, 'i');
33
+ }
34
+
35
+ /**
36
+ * Checks a value against a LIKE pattern; trailing spaces of the value are ignored, as in SQL.
37
+ *
38
+ * @param {string} value the value
39
+ * @param {string} pattern LIKE pattern
40
+ * @returns {boolean} true when the value matches
41
+ */
42
+ export function sqlLike(value, pattern) {
43
+ return likeToRegExp(pattern).test(String(value).replace(/ +$/, ''));
44
+ }
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Message codes and the message factory shared by the parser and (later) the emitters.
3
+ *
4
+ * Every message has the shape
5
+ * `{ severity: 'error'|'warning'|'info', code, message, line, column, endLine, endColumn }`.
6
+ * `line` / `column` are 1-based; `endLine` / `endColumn` point just after the last character
7
+ * (exclusive end), which matches how most editors mark a range.
8
+ */
9
+
10
+ // --- input / lexer -------------------------------------------------------------------------
11
+ export const EMPTY_INPUT = 'EMPTY_INPUT';
12
+ export const UNEXPECTED_CHARACTER = 'UNEXPECTED_CHARACTER';
13
+ export const UNTERMINATED_STRING = 'UNTERMINATED_STRING';
14
+ export const UNTERMINATED_IDENTIFIER = 'UNTERMINATED_IDENTIFIER';
15
+ export const UNTERMINATED_COMMENT = 'UNTERMINATED_COMMENT';
16
+ export const EMPTY_IDENTIFIER = 'EMPTY_IDENTIFIER';
17
+ export const UNSUPPORTED_LINE_SEPARATOR = 'UNSUPPORTED_LINE_SEPARATOR';
18
+
19
+ // --- syntax -------------------------------------------------------------------------------
20
+ export const SYNTAX_ERROR = 'SYNTAX_ERROR';
21
+ export const EXPECTED_SELECT = 'EXPECTED_SELECT';
22
+ export const EXPECTED_FROM = 'EXPECTED_FROM';
23
+ export const EXPECTED_IDENTIFIER = 'EXPECTED_IDENTIFIER';
24
+ export const EXPECTED_OPERATOR = 'EXPECTED_OPERATOR';
25
+ export const EXPECTED_VALUE = 'EXPECTED_VALUE';
26
+ export const EXPECTED_STRING = 'EXPECTED_STRING';
27
+ export const MISSING_CLOSING_PAREN = 'MISSING_CLOSING_PAREN';
28
+ export const INVALID_TOP = 'INVALID_TOP';
29
+ export const LITERAL_ON_LEFT = 'LITERAL_ON_LEFT';
30
+ export const NULL_COMPARISON = 'NULL_COMPARISON';
31
+ export const NESTING_TOO_DEEP = 'NESTING_TOO_DEEP';
32
+ export const INTERNAL_ERROR = 'INTERNAL_ERROR';
33
+
34
+ // --- unsupported constructs -----------------------------------------------------------------
35
+ export const UNSUPPORTED_JOIN = 'UNSUPPORTED_JOIN';
36
+ export const UNSUPPORTED_SUBQUERY = 'UNSUPPORTED_SUBQUERY';
37
+ export const UNSUPPORTED_GROUP_BY = 'UNSUPPORTED_GROUP_BY';
38
+ export const UNSUPPORTED_HAVING = 'UNSUPPORTED_HAVING';
39
+ export const UNSUPPORTED_AGGREGATE = 'UNSUPPORTED_AGGREGATE';
40
+ export const UNSUPPORTED_DISTINCT = 'UNSUPPORTED_DISTINCT';
41
+ export const UNSUPPORTED_FUNCTION = 'UNSUPPORTED_FUNCTION';
42
+ export const UNSUPPORTED_COLUMN_COMPARISON = 'UNSUPPORTED_COLUMN_COMPARISON';
43
+ export const UNSUPPORTED_ALIAS = 'UNSUPPORTED_ALIAS';
44
+ export const UNSUPPORTED_QUALIFIED_NAME = 'UNSUPPORTED_QUALIFIED_NAME';
45
+ export const UNSUPPORTED_NOT_LIKE = 'UNSUPPORTED_NOT_LIKE';
46
+ export const UNSUPPORTED_NOT_BETWEEN = 'UNSUPPORTED_NOT_BETWEEN';
47
+ export const UNSUPPORTED_NOT_CONDITION = 'UNSUPPORTED_NOT_CONDITION';
48
+ export const UNSUPPORTED_STAR_WITH_COLUMNS = 'UNSUPPORTED_STAR_WITH_COLUMNS';
49
+ export const UNSUPPORTED_UNION = 'UNSUPPORTED_UNION';
50
+ export const UNSUPPORTED_MULTIPLE_STATEMENTS = 'UNSUPPORTED_MULTIPLE_STATEMENTS';
51
+ export const UNSUPPORTED_OFFSET_FETCH = 'UNSUPPORTED_OFFSET_FETCH';
52
+
53
+ // --- warnings / info ------------------------------------------------------------------------
54
+ export const SYSTEM_DATA_VIEW = 'SYSTEM_DATA_VIEW';
55
+ export const TABLE_HINT_IGNORED = 'TABLE_HINT_IGNORED';
56
+ export const NULL_FALLBACK_REWRITTEN = 'NULL_FALLBACK_REWRITTEN';
57
+
58
+ // --- emitters / convert() -------------------------------------------------------------------
59
+ export const ORDER_BY_DROPPED = 'ORDER_BY_DROPPED';
60
+ export const TOP_DROPPED = 'TOP_DROPPED';
61
+ export const DE_KEY_ASSUMED = 'DE_KEY_ASSUMED';
62
+ export const SELECT_STAR_NEEDS_COLUMNS = 'SELECT_STAR_NEEDS_COLUMNS';
63
+ export const LIKE_CHECKED_IN_SCRIPT = 'LIKE_CHECKED_IN_SCRIPT';
64
+ export const EMPTY_STRING_AS_SPACE = 'EMPTY_STRING_AS_SPACE';
65
+ export const TOP_ABOVE_LOOKUP_LIMIT = 'TOP_ABOVE_LOOKUP_LIMIT';
66
+ export const FIRST_BATCH_ONLY = 'FIRST_BATCH_ONLY';
67
+
68
+ // --- reverse parsers (code to SQL) ------------------------------------------------------
69
+ export const NO_LOOKUP_FOUND = 'NO_LOOKUP_FOUND';
70
+ export const ARGUMENT_COUNT = 'ARGUMENT_COUNT';
71
+ export const INVALID_ARGUMENT = 'INVALID_ARGUMENT';
72
+ export const INVALID_OBJECT_TYPE = 'INVALID_OBJECT_TYPE';
73
+ export const INVALID_COUNT = 'INVALID_COUNT';
74
+ export const INVALID_ORDER_BY = 'INVALID_ORDER_BY';
75
+ export const INVALID_FILTER = 'INVALID_FILTER';
76
+ export const INVALID_FILTER_VALUE = 'INVALID_FILTER_VALUE';
77
+ export const INVALID_LOGICAL_OPERATOR = 'INVALID_LOGICAL_OPERATOR';
78
+ export const UNKNOWN_FILTER_OPERATOR = 'UNKNOWN_FILTER_OPERATOR';
79
+ export const UNSUPPORTED_FILTER_OPERATOR = 'UNSUPPORTED_FILTER_OPERATOR';
80
+ export const UNSUPPORTED_EXPRESSION = 'UNSUPPORTED_EXPRESSION';
81
+ export const VARIABLE_VALUE = 'VARIABLE_VALUE';
82
+ export const MULTIPLE_LOOKUPS = 'MULTIPLE_LOOKUPS';
83
+ export const FROM_UNKNOWN = 'FROM_UNKNOWN';
84
+ export const FROM_NAME_FROM_KEY = 'FROM_NAME_FROM_KEY';
85
+ export const LOOKUP_FIRST_ROW_ONLY = 'LOOKUP_FIRST_ROW_ONLY';
86
+ export const CASE_SENSITIVE_LOOKUP = 'CASE_SENSITIVE_LOOKUP';
87
+ export const LIKE_MATCHES_ANYWHERE = 'LIKE_MATCHES_ANYWHERE';
88
+
89
+ /**
90
+ * All message codes, keyed by themselves (handy for iteration and lookups).
91
+ */
92
+ export const MESSAGE_CODES = Object.freeze({
93
+ EMPTY_INPUT,
94
+ UNEXPECTED_CHARACTER,
95
+ UNTERMINATED_STRING,
96
+ UNTERMINATED_IDENTIFIER,
97
+ UNTERMINATED_COMMENT,
98
+ EMPTY_IDENTIFIER,
99
+ UNSUPPORTED_LINE_SEPARATOR,
100
+ SYNTAX_ERROR,
101
+ EXPECTED_SELECT,
102
+ EXPECTED_FROM,
103
+ EXPECTED_IDENTIFIER,
104
+ EXPECTED_OPERATOR,
105
+ EXPECTED_VALUE,
106
+ EXPECTED_STRING,
107
+ MISSING_CLOSING_PAREN,
108
+ INVALID_TOP,
109
+ LITERAL_ON_LEFT,
110
+ NULL_COMPARISON,
111
+ NESTING_TOO_DEEP,
112
+ INTERNAL_ERROR,
113
+ UNSUPPORTED_JOIN,
114
+ UNSUPPORTED_SUBQUERY,
115
+ UNSUPPORTED_GROUP_BY,
116
+ UNSUPPORTED_HAVING,
117
+ UNSUPPORTED_AGGREGATE,
118
+ UNSUPPORTED_DISTINCT,
119
+ UNSUPPORTED_FUNCTION,
120
+ UNSUPPORTED_COLUMN_COMPARISON,
121
+ UNSUPPORTED_ALIAS,
122
+ UNSUPPORTED_QUALIFIED_NAME,
123
+ UNSUPPORTED_NOT_LIKE,
124
+ UNSUPPORTED_NOT_BETWEEN,
125
+ UNSUPPORTED_NOT_CONDITION,
126
+ UNSUPPORTED_STAR_WITH_COLUMNS,
127
+ UNSUPPORTED_UNION,
128
+ UNSUPPORTED_MULTIPLE_STATEMENTS,
129
+ UNSUPPORTED_OFFSET_FETCH,
130
+ SYSTEM_DATA_VIEW,
131
+ TABLE_HINT_IGNORED,
132
+ NULL_FALLBACK_REWRITTEN,
133
+ ORDER_BY_DROPPED,
134
+ TOP_DROPPED,
135
+ DE_KEY_ASSUMED,
136
+ SELECT_STAR_NEEDS_COLUMNS,
137
+ LIKE_CHECKED_IN_SCRIPT,
138
+ EMPTY_STRING_AS_SPACE,
139
+ TOP_ABOVE_LOOKUP_LIMIT,
140
+ FIRST_BATCH_ONLY,
141
+ NO_LOOKUP_FOUND,
142
+ ARGUMENT_COUNT,
143
+ INVALID_ARGUMENT,
144
+ INVALID_OBJECT_TYPE,
145
+ INVALID_COUNT,
146
+ INVALID_ORDER_BY,
147
+ INVALID_FILTER,
148
+ INVALID_FILTER_VALUE,
149
+ INVALID_LOGICAL_OPERATOR,
150
+ UNKNOWN_FILTER_OPERATOR,
151
+ UNSUPPORTED_FILTER_OPERATOR,
152
+ UNSUPPORTED_EXPRESSION,
153
+ VARIABLE_VALUE,
154
+ MULTIPLE_LOOKUPS,
155
+ FROM_UNKNOWN,
156
+ FROM_NAME_FROM_KEY,
157
+ LOOKUP_FIRST_ROW_ONLY,
158
+ CASE_SENSITIVE_LOOKUP,
159
+ LIKE_MATCHES_ANYWHERE,
160
+ });
161
+
162
+ /**
163
+ * The message codes used only by the reverse parsers (`parseSsjs`, `parseAmpscript`), keyed by
164
+ * themselves.
165
+ */
166
+ export const REVERSE_MESSAGE_CODES = Object.freeze({
167
+ NO_LOOKUP_FOUND,
168
+ ARGUMENT_COUNT,
169
+ INVALID_ARGUMENT,
170
+ INVALID_OBJECT_TYPE,
171
+ INVALID_COUNT,
172
+ INVALID_ORDER_BY,
173
+ INVALID_FILTER,
174
+ INVALID_FILTER_VALUE,
175
+ INVALID_LOGICAL_OPERATOR,
176
+ UNKNOWN_FILTER_OPERATOR,
177
+ UNSUPPORTED_FILTER_OPERATOR,
178
+ UNSUPPORTED_EXPRESSION,
179
+ VARIABLE_VALUE,
180
+ MULTIPLE_LOOKUPS,
181
+ FROM_UNKNOWN,
182
+ FROM_NAME_FROM_KEY,
183
+ LOOKUP_FIRST_ROW_ONLY,
184
+ CASE_SENSITIVE_LOOKUP,
185
+ LIKE_MATCHES_ANYWHERE,
186
+ });
187
+
188
+ /**
189
+ * @typedef {'error'|'warning'|'info'} Severity
190
+ */
191
+
192
+ /**
193
+ * @typedef {object} Location
194
+ * @property {number} line 1-based line of the first character
195
+ * @property {number} column 1-based column of the first character
196
+ * @property {number} endLine 1-based line of the exclusive end
197
+ * @property {number} endColumn 1-based column of the exclusive end
198
+ */
199
+
200
+ /**
201
+ * @typedef {object} Message
202
+ * @property {Severity} severity how serious the finding is
203
+ * @property {string} code one of the exported code constants
204
+ * @property {string} message plain-language text: what is wrong and how to fix it
205
+ * @property {number} line 1-based start line
206
+ * @property {number} column 1-based start column
207
+ * @property {number} endLine 1-based end line
208
+ * @property {number} endColumn 1-based exclusive end column
209
+ */
210
+
211
+ /**
212
+ * Builds a message object.
213
+ *
214
+ * @param {Severity} severity 'error', 'warning' or 'info'
215
+ * @param {string} code one of the exported code constants
216
+ * @param {string} message plain-language text: what is wrong and how to fix it
217
+ * @param {Location} location where the problem is (any object with line/column/endLine/endColumn, e.g. an AST `loc`)
218
+ * @returns {Message} the message
219
+ */
220
+ export function createMessage(severity, code, message, location) {
221
+ return {
222
+ severity,
223
+ code,
224
+ message,
225
+ line: location.line,
226
+ column: location.column,
227
+ endLine: location.endLine,
228
+ endColumn: location.endColumn,
229
+ };
230
+ }
@@ -0,0 +1,372 @@
1
+ /**
2
+ * Reads Engagement AMPscript data extension lookups back into the SQL AST of `parseSql`:
3
+ * `LookupRows`, `LookupOrderedRows` and `Lookup` (plus the CS variants, with a warning).
4
+ *
5
+ * The code is read as text; it is never executed. Never throws.
6
+ */
7
+
8
+ import { SYNTAX_ERROR } from './messages.js';
9
+ import {
10
+ ARGUMENT_COUNT,
11
+ CASE_SENSITIVE_LOOKUP,
12
+ INVALID_ARGUMENT,
13
+ INVALID_COUNT,
14
+ LOOKUP_FIRST_ROW_ONLY,
15
+ MULTIPLE_LOOKUPS,
16
+ NO_LOOKUP_FOUND,
17
+ UNSUPPORTED_EXPRESSION,
18
+ VARIABLE_VALUE,
19
+ } from './messages.js';
20
+ import {
21
+ andChain,
22
+ createContext,
23
+ expressionEnd,
24
+ fail,
25
+ failUnclosedCall,
26
+ findAmpscriptRegions,
27
+ isPunct,
28
+ makeLoc,
29
+ makeValue,
30
+ parseOrderString,
31
+ readHeader,
32
+ rejectEmpty,
33
+ report,
34
+ runParser,
35
+ tokenAt,
36
+ tokenize,
37
+ } from './reverse-common.js';
38
+
39
+ /**
40
+ * @typedef {object} AmpLiteral
41
+ * @property {'string'|'number'} kind literal kind
42
+ * @property {string} value unescaped text or number text
43
+ * @property {number} start 0-based start offset
44
+ * @property {number} end 0-based exclusive end offset
45
+ */
46
+
47
+ const LOOKUP_FUNCTIONS = new Map(
48
+ Object.entries({
49
+ lookuprows: { target: 'ampscript-lookuprows', caseSensitive: false },
50
+ lookuprowscs: { target: 'ampscript-lookuprows', caseSensitive: true },
51
+ lookuporderedrows: { target: 'ampscript-lookuporderedrows', caseSensitive: false },
52
+ lookuporderedrowscs: { target: 'ampscript-lookuporderedrows', caseSensitive: true },
53
+ lookup: { target: 'ampscript-lookup', caseSensitive: false },
54
+ }),
55
+ );
56
+
57
+ /**
58
+ * Parses one argument: a string or number literal. Variables and nested calls are errors.
59
+ *
60
+ * @param {object} context parse context
61
+ * @returns {AmpLiteral} literal
62
+ */
63
+ function parseArgument(context) {
64
+ const token = tokenAt(context, context.pos);
65
+ if (token.type === 'string' || token.type === 'number') {
66
+ context.pos++;
67
+ return { kind: token.type, value: token.value, start: token.start, end: token.end };
68
+ }
69
+ if (isPunct(token, '-') && tokenAt(context, context.pos + 1).type === 'number') {
70
+ const number = tokenAt(context, context.pos + 1);
71
+ context.pos += 2;
72
+ return { kind: 'number', value: `-${number.value}`, start: token.start, end: number.end };
73
+ }
74
+ if (token.type === 'variable') {
75
+ fail(
76
+ context,
77
+ VARIABLE_VALUE,
78
+ `The variable ${token.value} can't be converted to SQL because its value is only known when the code runs. Replace it with the value itself.`,
79
+ token.start,
80
+ token.end,
81
+ );
82
+ }
83
+ if (token.type === 'ident' && isPunct(tokenAt(context, context.pos + 1), '(')) {
84
+ fail(
85
+ context,
86
+ UNSUPPORTED_EXPRESSION,
87
+ `The function call ${token.value}(…) can't be converted to SQL. Replace it with the value itself.`,
88
+ token.start,
89
+ expressionEnd(context, context.pos),
90
+ );
91
+ }
92
+ if (token.type === 'eof') {
93
+ return fail(
94
+ context,
95
+ SYNTAX_ERROR,
96
+ 'The code ends where an argument is expected.',
97
+ token.start,
98
+ token.end,
99
+ );
100
+ }
101
+ return fail(
102
+ context,
103
+ SYNTAX_ERROR,
104
+ `Expected an argument but found "${token.value}". Write text in double quotes or a number.`,
105
+ token.start,
106
+ token.end,
107
+ );
108
+ }
109
+
110
+ /**
111
+ * Parses an argument list starting at "(".
112
+ *
113
+ * @param {object} context parse context
114
+ * @returns {{args: AmpLiteral[], end: number}} arguments and the end offset of ")"
115
+ */
116
+ function parseArguments(context) {
117
+ const open = tokenAt(context, context.pos++);
118
+ const args = [];
119
+ for (;;) {
120
+ const token = tokenAt(context, context.pos);
121
+ if (isPunct(token, ')')) {
122
+ context.pos++;
123
+ return { args, end: token.end };
124
+ }
125
+ if (token.type === 'eof') {
126
+ failUnclosedCall(context, open);
127
+ }
128
+ args.push(parseArgument(context));
129
+ const separator = tokenAt(context, context.pos);
130
+ if (isPunct(separator, ',')) {
131
+ context.pos++;
132
+ } else if (separator.type === 'eof') {
133
+ failUnclosedCall(context, open);
134
+ } else if (!isPunct(separator, ')')) {
135
+ fail(
136
+ context,
137
+ UNSUPPORTED_EXPRESSION,
138
+ 'Only plain values can be converted here. Separate the arguments with commas and close the call with ).',
139
+ separator.start,
140
+ separator.end,
141
+ );
142
+ }
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Checks that an argument is non-empty text and returns it.
148
+ *
149
+ * @param {object} context parse context
150
+ * @param {AmpLiteral} literal argument
151
+ * @param {string} what what the argument is, for the message
152
+ * @returns {string} the text
153
+ */
154
+ function requireString(context, literal, what) {
155
+ if (literal.kind !== 'string' || !literal.value.trim()) {
156
+ fail(
157
+ context,
158
+ INVALID_ARGUMENT,
159
+ `${what} must be text in double quotes.`,
160
+ literal.start,
161
+ literal.end,
162
+ );
163
+ }
164
+ return literal.value;
165
+ }
166
+
167
+ /**
168
+ * Reads the column / value pairs into an AND chain of equals conditions.
169
+ *
170
+ * @param {object} context parse context
171
+ * @param {AmpLiteral[]} pairs alternating column names and values
172
+ * @returns {object} expression node
173
+ */
174
+ function readPairs(context, pairs) {
175
+ const conditions = [];
176
+ for (let index = 0; index < pairs.length; index += 2) {
177
+ const columnLiteral = pairs[index];
178
+ const valueLiteral = pairs[index + 1];
179
+ const column = requireString(context, columnLiteral, 'Each column name');
180
+ conditions.push({
181
+ type: 'compare',
182
+ op: '=',
183
+ column,
184
+ value: makeValue(
185
+ context,
186
+ valueLiteral.value,
187
+ valueLiteral.start,
188
+ valueLiteral.end,
189
+ valueLiteral.kind === 'number',
190
+ ),
191
+ loc: makeLoc(context, columnLiteral.start, valueLiteral.end),
192
+ });
193
+ }
194
+ return andChain(context, conditions);
195
+ }
196
+
197
+ /**
198
+ * Checks the argument count of a lookup function.
199
+ *
200
+ * @param {object} context parse context
201
+ * @param {string} kind lower-case function name without CS
202
+ * @param {number} count number of arguments
203
+ * @param {object} callLoc location of the call
204
+ */
205
+ function checkArgumentCount(context, kind, count, callLoc) {
206
+ const fixed = { lookuprows: 1, lookuporderedrows: 3, lookup: 2 }[kind];
207
+ if (count < fixed + 2 || (count - fixed) % 2 !== 0) {
208
+ const usage = {
209
+ lookuprows: 'LookupRows("DE name", "Column", "value"[, "Column2", "value2" …])',
210
+ lookuporderedrows:
211
+ 'LookupOrderedRows("DE name", count, "Column ASC", "Column", "value"[, …])',
212
+ lookup: 'Lookup("DE name", "ReturnColumn", "Column", "value"[, …])',
213
+ }[kind];
214
+ fail(
215
+ context,
216
+ ARGUMENT_COUNT,
217
+ `Wrong number of arguments. Write it as ${usage}: every column name needs a value.`,
218
+ callLoc.start,
219
+ callLoc.end,
220
+ );
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Reads the row count of LookupOrderedRows (0 or -1 = all rows → no TOP).
226
+ *
227
+ * @param {object} context parse context
228
+ * @param {AmpLiteral} literal count argument
229
+ * @returns {number|null} TOP value
230
+ */
231
+ function readCount(context, literal) {
232
+ const text = literal.value.trim();
233
+ if (!/^-?\d+$/.test(text)) {
234
+ fail(
235
+ context,
236
+ INVALID_COUNT,
237
+ 'The row count must be a whole number (0 or -1 for all rows).',
238
+ literal.start,
239
+ literal.end,
240
+ );
241
+ }
242
+ const count = Number(text);
243
+ return count > 0 ? count : null;
244
+ }
245
+
246
+ /**
247
+ * Finds every lookup call.
248
+ *
249
+ * @param {object} context parse context
250
+ * @returns {{index: number, name: string}[]} calls in source order
251
+ */
252
+ function findCalls(context) {
253
+ const calls = [];
254
+ for (const [index, token] of context.tokens.entries()) {
255
+ const name = token.type === 'ident' ? token.value.toLowerCase() : '';
256
+ if (LOOKUP_FUNCTIONS.has(name) && isPunct(tokenAt(context, index + 1), '(')) {
257
+ calls.push({ index, name });
258
+ }
259
+ }
260
+ return calls;
261
+ }
262
+
263
+ /**
264
+ * Parses the first lookup call and builds the AST.
265
+ *
266
+ * @param {object} context parse context
267
+ * @param {object} meta meta data (mutated)
268
+ * @returns {object} SELECT AST
269
+ */
270
+ function parseProgram(context, meta) {
271
+ const header = readHeader(context);
272
+ const calls = findCalls(context);
273
+ if (calls.length === 0) {
274
+ fail(
275
+ context,
276
+ NO_LOOKUP_FOUND,
277
+ 'No supported lookup was found. Paste a LookupRows, LookupOrderedRows or Lookup call.',
278
+ 0,
279
+ context.text.length,
280
+ );
281
+ }
282
+ const call = calls[0];
283
+ const callToken = tokenAt(context, call.index);
284
+ if (calls.length > 1) {
285
+ const second = tokenAt(context, calls[1].index);
286
+ report(
287
+ context,
288
+ 'warning',
289
+ MULTIPLE_LOOKUPS,
290
+ 'The code contains more than one lookup; only the first one is converted.',
291
+ second.start,
292
+ second.end,
293
+ );
294
+ }
295
+ context.pos = call.index + 1;
296
+ const { args, end } = parseArguments(context);
297
+ const callLoc = makeLoc(context, callToken.start, end);
298
+ const definition = LOOKUP_FUNCTIONS.get(call.name);
299
+ const kind = call.name.replace(/cs$/, '');
300
+ meta.target = definition.target;
301
+ if (definition.caseSensitive) {
302
+ report(
303
+ context,
304
+ 'warning',
305
+ CASE_SENSITIVE_LOOKUP,
306
+ `${callToken.value} compares the values case-sensitively; SQL in Marketing Cloud compares text without regard to case, so the result can contain more rows.`,
307
+ callToken.start,
308
+ callToken.end,
309
+ );
310
+ }
311
+ checkArgumentCount(context, kind, args.length, callLoc);
312
+ const name = requireString(context, args[0], 'The data extension name');
313
+ meta.deName = name;
314
+ if (header.key) {
315
+ meta.deKey = header.key;
316
+ }
317
+ let columns = header.columns ?? '*';
318
+ let top = null;
319
+ let orderBy = [];
320
+ let pairs = args.slice(1);
321
+ if (kind === 'lookuporderedrows') {
322
+ top = readCount(context, args[1]);
323
+ requireString(context, args[2], 'The sort order');
324
+ orderBy = parseOrderString(context, args[2]);
325
+ pairs = args.slice(3);
326
+ } else if (kind === 'lookup') {
327
+ const column = requireString(context, args[1], 'The column to return');
328
+ columns = [{ name: column, loc: makeLoc(context, args[1].start, args[1].end) }];
329
+ pairs = args.slice(2);
330
+ report(
331
+ context,
332
+ 'info',
333
+ LOOKUP_FIRST_ROW_ONLY,
334
+ 'Lookup returns the value of the first matching row only; the SQL query returns every matching row.',
335
+ callLoc.start,
336
+ callLoc.end,
337
+ );
338
+ }
339
+ return {
340
+ type: 'select',
341
+ top,
342
+ columns,
343
+ from: { name, loc: makeLoc(context, args[0].start, args[0].end) },
344
+ where: readPairs(context, pairs),
345
+ orderBy,
346
+ loc: callLoc,
347
+ };
348
+ }
349
+
350
+ /**
351
+ * Reads an AMPscript data extension lookup back into the SQL AST. Never throws.
352
+ *
353
+ * Accepted: `%%[ … ]%%` / `%%= … =%%` blocks or bare statements containing
354
+ * `LookupRows("Name", "Col", "v"[, …])`, `LookupOrderedRows("Name", count, "Col ASC", "Col", "v"[, …])`
355
+ * or `Lookup("Name", "ReturnCol", "Col", "v"[, …])` (also the CS variants). The first lookup is
356
+ * converted; loops and output code around it are ignored. A `/* SQL: SELECT a, b *\/` comment
357
+ * supplies the column list LookupRows cannot carry.
358
+ *
359
+ * @param {string} text AMPscript code
360
+ * @returns {{ast: object|null, messages: import('./messages.js').Message[], meta: {target: string|null, deName?: string, deKey?: string}}} AST (null on error), messages and meta data
361
+ */
362
+ export function parseAmpscript(text) {
363
+ const source = typeof text === 'string' ? text : '';
364
+ const context = createContext(source);
365
+ const meta = { target: null };
366
+ const ast = runParser(context, () => {
367
+ tokenize(context, 'ampscript', findAmpscriptRegions(source));
368
+ rejectEmpty(context);
369
+ return parseProgram(context, meta);
370
+ });
371
+ return { ast, messages: context.messages, meta };
372
+ }