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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jörn Berkefeld
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,178 @@
1
- # Temporary Holding Version
1
+ # sfmc-sql-converter
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Converts SQL SELECT queries to Salesforce Marketing Cloud lookup code (SSJS, AMPscript) and back.
4
+
5
+ You write the query you would run in a query activity. The package gives you the matching code for every lookup method of Marketing Cloud Engagement. It also reads lookup code and gives you the SQL it stands for.
6
+
7
+ - No dependencies. Plain JavaScript (ES modules), runs in Node.js and in the browser.
8
+ - The code you paste is only read as text. It is never run.
9
+ - The generated SSJS uses `var` only (no arrow functions, `let`, `const` or template strings), so the SSJS engine accepts it.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install sfmc-sql-converter
15
+ ```
16
+
17
+ Node.js 22 or newer.
18
+
19
+ ## Usage
20
+
21
+ ```js
22
+ import { convert } from 'sfmc-sql-converter';
23
+
24
+ const result = convert(
25
+ "SELECT TOP 5 SubscriberKey, Email FROM [Customers] WHERE Country = 'DE' ORDER BY Email",
26
+ { deKey: 'CUST-KEY' },
27
+ );
28
+ for (const output of result.outputs) {
29
+ console.log(output.label, output.code ?? output.unavailable);
30
+ }
31
+
32
+ const back = convert('var rows = Platform.Function.LookupRows("Customers", ["Country"], ["DE"]);', {
33
+ direction: 'toSql',
34
+ });
35
+ console.log(back.outputs[0].code);
36
+ // SELECT *
37
+ // FROM Customers
38
+ // WHERE Country = 'DE'
39
+ ```
40
+
41
+ ### `convert(input, options)`
42
+
43
+ `input` is SQL (direction `toCode`) or SSJS / AMPscript (direction `toSql`).
44
+
45
+ | Option | Default | Meaning |
46
+ | ------------ | ---------- | ----------------------------------------------------------------------------- |
47
+ | `platform` | `'mce'` | `'mce'` (Engagement) or `'mcn'` (Next) |
48
+ | `direction` | `'toCode'` | `'toCode'` (SQL to code) or `'toSql'` (code to SQL) |
49
+ | `dataSource` | `'CRM'` | Next only: `'CRM'` (Sales Cloud object) or `'MO'` (marketing object) |
50
+ | `deKey` | the name | External key of the data extension. WSProxy and Rows.Retrieve need the key. |
51
+ | `deName` | | `toSql` only: data extension name when the code does not carry it |
52
+ | `columns` | | The column names that `SELECT *` stands for |
53
+ | `schema` | | `{ fields: [{ name }] }`, used like `columns` when `columns` is not given |
54
+ | `output` | | WSProxy options: `rowsAsObjects` (default `true`), `paging` (default `false`) |
55
+
56
+ Unknown `platform` or `direction` values throw a `TypeError`. Everything else never throws: problems come back as messages.
57
+
58
+ ### Result
59
+
60
+ ```js
61
+ {
62
+ outputs: [
63
+ {
64
+ id: 'ssjs-wsproxy', // target id
65
+ language: 'ssjs', // 'ssjs', 'ampscript' or 'sql'
66
+ label: 'WSProxy',
67
+ code: '<script runat="server">…</script>', // or `unavailable: '<plain reason>'`
68
+ spans: [{ clauseId, start, end }], // where each clause is in `code`
69
+ messages: [], // messages for this output only
70
+ dropped: ['top'], // clause ids this output leaves out
71
+ roundTrip: { ok, sql, note }, // the code read back as SQL
72
+ },
73
+ ],
74
+ messages: [], // messages about the input
75
+ clauseMap: [], // { outputId, clauseId, sql, code, loc, dropped } per clause and output
76
+ roundTrip: { ok, sql, note }, // first available output (toCode) or the printed SQL (toSql)
77
+ }
78
+ ```
79
+
80
+ Every message has `severity` (`error`, `warning` or `info`), `code`, `message` (plain text), `line`, `column`, `endLine` and `endColumn` (1-based, end exclusive).
81
+
82
+ Clause ids: `column-N`, `top`, `from`, `where-N` (each single condition, left to right) and `order-N`.
83
+
84
+ ## Targets (Engagement)
85
+
86
+ | Id | Code | Available when |
87
+ | ----------------------------- | ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- |
88
+ | `ssjs-wsproxy` | WSProxy `retrieve` of `DataExtensionObject[Key]` | the columns are known (named in the SELECT, or given with `columns` / `schema`); no anchored LIKE inside OR |
89
+ | `ssjs-rows-retrieve` | `DataExtension.Init(Key).Rows.Retrieve(filter)` | no anchored LIKE inside OR |
90
+ | `ssjs-lookuprows` | `Platform.Function.LookupRows` | WHERE uses only `Column = 'value'` joined with AND |
91
+ | `ssjs-lookuporderedrows` | `Platform.Function.LookupOrderedRows` | as LookupRows, plus ORDER BY on columns without spaces or commas |
92
+ | `ampscript-lookuprows` | AMPscript `LookupRows` plus a FOR loop | as LookupRows; no name or value contains `%%` |
93
+ | `ampscript-lookuporderedrows` | AMPscript `LookupOrderedRows` plus a loop | as LookupOrderedRows; no name or value contains `%%` |
94
+ | `ampscript-lookup` | AMPscript `Lookup` | exactly one column, equals joined with AND; no `%%`. Returns the first match only. |
95
+
96
+ When a target can't express the query, its output has `unavailable` with a plain reason instead of `code`.
97
+
98
+ WSProxy reads one batch (up to 2,500 rows) by default and says so with `FIRST_BATCH_ONLY`. When more rows exist, the code sets `hasMoreRows = true`. With `output.paging` it reads every batch with `props.ContinueRequest = result.RequestID`.
99
+
100
+ ## Targets (Next)
101
+
102
+ Next mode returns the targets of the chosen `dataSource`. Only what live tests proved is generated (`NEXT_RULES` lists each rule with its test records); everything else is unavailable with a reason.
103
+
104
+ | Id | Data source | Code | Available when |
105
+ | ------------------------- | ----------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
106
+ | `handlebars-query` | CRM | `{{#each (query type="CRM" … where=":p1 …" params=(hash …))}}` | columns listed; `=`, `<>`, `<`, `<=`, `>`, `>=`, `LIKE '%text%'`, AND, OR, brackets; one ORDER BY |
107
+ | `handlebars-queryfirst` | CRM | `{{get (queryFirst type="CRM" …) "Field"}}` | as query, exactly one column; returns the first match (TOP 1) |
108
+ | `ampscript-rso` | CRM | AMPscript `RetrieveSalesforceObjects` plus a FOR loop | columns listed; the same operators joined with AND, each field at most once; no TOP / ORDER BY |
109
+ | `handlebars-query-mo` | MO | `{{#each (query type="MO" object="X" Field__c="v" …)}}` | `Column = value` joined with AND, each field once; TOP becomes `limit`; no ORDER BY |
110
+ | `ampscript-lookuprows-mo` | MO | AMPscript `LookupRows` plus a FOR loop | `Column = 'value'` joined with AND, each field once; no TOP / ORDER BY |
111
+
112
+ Values always go into `params` (literals in `where` fail in Next); `<>` is written as `!=`. Next matches LIKE as "contains", so only `'%text%'` converts. IN, NOT IN, NOT (…), BETWEEN and IS NULL are not supported in Next. On a marketing object, Next returned only one record in a test where the filter matched two, so both marketing object targets carry the warning `MO_ONE_MATCH`; filter on the key field when every match matters.
113
+
114
+ ## Rewrites and dropped clauses
115
+
116
+ - **ISNULL / COALESCE.** In WHERE, `ISNULL(Column, value) op value` (and COALESCE with two arguments) is converted without the function: `Column op value`, plus `OR Column IS NULL` when the fallback itself matches the condition (`NULL_FALLBACK_REWRITTEN`). This assumes the fallback has the column's type. Reading code back gives this expanded form. Other uses of the functions stay errors.
117
+ - **OFFSET … FETCH** is an error (`UNSUPPORTED_OFFSET_FETCH`); use TOP.
118
+
119
+ - **LIKE.** The WSProxy and Rows.Retrieve `like` filter always matches anywhere (it wraps the value in `%`). `'%text%'` is sent as is. Any other pattern is sent without its outer `%`, and the generated `sqlLike()` helper then checks the exact pattern on each row. This only works on a pure AND path, so such a LIKE inside OR makes these targets unavailable (`LIKE_CHECKED_IN_SCRIPT`).
120
+ - **Empty text.** The filter rejects an empty value, so `= ''` is sent as a single space `' '`. This finds the same rows, because trailing spaces are ignored when text is compared (`EMPTY_STRING_AS_SPACE`).
121
+ - **TOP and ORDER BY.** WSProxy, Rows.Retrieve and LookupRows can't sort or limit rows. They leave ORDER BY and TOP out with a warning. LookupOrderedRows uses TOP as its row count. `TOP 0` is an error. TOP above 2,000 gets a warning on the lookup functions, which return at most 2,000 rows.
122
+ - **NOT IN** becomes a chain of `notEquals` joined with AND. A `// SQL: NOT IN` comment lets the reverse parser fold it back.
123
+ - **Names in comments.** The data extension name and the column list are kept in a `// SQL:` (SSJS) or `/* SQL: */` (AMPscript) comment. These comments never hold a backslash or a double quote (a CloudPage reads `"` as the start of a string even inside a comment), and nothing that ends the comment, the script or an AMPscript block. `~` is the escape character: `~` becomes `~~`, `"` becomes `~q`, a backslash becomes `~b`, and a `~` is put into `</`, `*/`, `]%%`, `=%%`, `%%[` and `%%=` (for example `<~/`). Reading the code back undoes this exactly, so every name comes back unchanged.
124
+ - **Backslashes** in SSJS strings are written as the unicode escape of character 5C, never as an escaped backslash. A string ending in an escaped backslash makes a CloudPage fail.
125
+
126
+ ## Reading code back (`toSql`)
127
+
128
+ - Reads WSProxy `retrieve`, `DataExtension.Init(…).Rows.Retrieve(…)`, `Platform.Function.LookupRows` / `LookupOrderedRows`, AMPscript `LookupRows`, `LookupOrderedRows`, `Lookup` (also the CS variants), and bare filter objects.
129
+ - Next (`platform: 'mcn'`): Handlebars `query` / `queryFirst` (CRM and MO) and AMPscript `LookupRows` / `RetrieveSalesforceObjects`. Every `:name` in `where` must be defined once in `params`; a literal in `where` is an error. Handlebars keeps the value type: `p1="5"` reads back as `'5'`, `p1=5` as `5`. A LIKE value of plain text that is not `%text%` (e.g. `Ro%`) reads back as `'%Ro%'` with a warning; `_`, `[` or `%` inside the text is an error. These are errors too, as in the forward direction: `sortBy` with more than one field, a `get` field that is not in `fields` (Next renders it empty), and the same field in two `RetrieveSalesforceObjects` conditions.
130
+ - Engagement: when the SQL sorts without TOP, an info message (`ORDER_BY_NEEDS_TOP`) points out that a query activity in Automation Studio rejects ORDER BY without TOP.
131
+ - Variables set to fixed values are resolved. Values only known at run time are errors.
132
+ - A hand-written `like` filter without a `sqlLike()` check reads back as `LIKE '%value%'`, because the filter matches anywhere (`LIKE_MATCHES_ANYWHERE`).
133
+ - A bare filter object does not name its data extension. Pass `deName` to fill it in. Without it, the round trip is skipped (`roundTrip.skipped: true` with a note).
134
+
135
+ ## Round trip
136
+
137
+ Every output is read back with the reverse parser and compared with the query. The comparison ignores keyword case, name case, brackets, whitespace, the quotes of plain numbers, and how AND / OR are grouped. It also ignores the clauses the target left out, `IN` ↔ OR chains and `NOT IN` ↔ AND chains where the target writes them that way, and `*` ↔ the column list given in the options. The Next Handlebars targets keep the quotes of plain numbers apart, because Next compares `'5'` and `5` as different types.
138
+
139
+ ## Message codes
140
+
141
+ | Code | Meaning |
142
+ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
143
+ | `EMPTY_INPUT` | Nothing to convert |
144
+ | `UNEXPECTED_CHARACTER`, `UNTERMINATED_STRING`, `UNTERMINATED_IDENTIFIER`, `UNTERMINATED_COMMENT`, `EMPTY_IDENTIFIER` | The text can't be split into words |
145
+ | `UNSUPPORTED_LINE_SEPARATOR` | A name contains the line separator U+2028 or U+2029 |
146
+ | `SYNTAX_ERROR`, `EXPECTED_SELECT`, `EXPECTED_FROM`, `EXPECTED_IDENTIFIER`, `EXPECTED_OPERATOR`, `EXPECTED_VALUE`, `EXPECTED_STRING`, `MISSING_CLOSING_PAREN` | Something is missing or in the wrong place |
147
+ | `INVALID_TOP` | TOP is not a whole number above 0 |
148
+ | `LITERAL_ON_LEFT`, `NULL_COMPARISON` | Write `Column = value`, and `IS NULL` instead of `= NULL` |
149
+ | `NESTING_TOO_DEEP`, `INTERNAL_ERROR` | The input can't be read |
150
+ | `UNSUPPORTED_*` (JOIN, subquery, GROUP BY, HAVING, aggregate, DISTINCT, function, column comparison, alias, qualified name, NOT LIKE, NOT BETWEEN, NOT, `*` with columns, UNION, several statements) | Not possible with a lookup |
151
+ | `SYSTEM_DATA_VIEW` | System data views can't be read with a lookup |
152
+ | `TABLE_HINT_IGNORED` | Table hints such as `WITH (NOLOCK)` are ignored |
153
+ | `ORDER_BY_DROPPED`, `TOP_DROPPED` | The target leaves the clause out |
154
+ | `FIRST_BATCH_ONLY` | WSProxy without paging reads only the first batch of up to 2,500 rows |
155
+ | `ORDER_BY_NEEDS_TOP` | Code → SQL on Engagement: the SQL sorts without TOP, which a query activity rejects |
156
+ | `TOP_ABOVE_LOOKUP_LIMIT` | TOP asks for more than the 2,000 rows a lookup returns |
157
+ | `DE_KEY_ASSUMED` | No external key given; the name is used as the key |
158
+ | `SELECT_STAR_NEEDS_COLUMNS` | WSProxy needs the columns that `*` stands for |
159
+ | `LIKE_CHECKED_IN_SCRIPT` | The exact LIKE pattern is checked in the script |
160
+ | `EMPTY_STRING_AS_SPACE` | `''` is sent as a single space |
161
+ | `NO_LOOKUP_FOUND`, `MULTIPLE_LOOKUPS` | No lookup, or more than one (only the first is converted) |
162
+ | `ARGUMENT_COUNT`, `INVALID_ARGUMENT`, `INVALID_OBJECT_TYPE`, `INVALID_COUNT`, `INVALID_ORDER_BY` | A call argument can't be read |
163
+ | `INVALID_FILTER`, `INVALID_FILTER_VALUE`, `INVALID_LOGICAL_OPERATOR`, `UNKNOWN_FILTER_OPERATOR`, `UNSUPPORTED_FILTER_OPERATOR` | A filter object can't be read |
164
+ | `UNSUPPORTED_EXPRESSION`, `VARIABLE_VALUE` | A value is calculated or only known at run time |
165
+ | `FROM_UNKNOWN`, `FROM_NAME_FROM_KEY` | The data extension name is missing, or the key is used |
166
+ | `LOOKUP_FIRST_ROW_ONLY` | `Lookup` returns the first matching row only |
167
+ | `CASE_SENSITIVE_LOOKUP` | A CS lookup compares case-sensitively |
168
+ | `LIKE_MATCHES_ANYWHERE` | A `like` filter without a check reads back as `'%value%'` |
169
+
170
+ All codes are exported as constants and in `MESSAGE_CODES`.
171
+
172
+ ## Live verification
173
+
174
+ The expected rows come from real Marketing Cloud query activities on a fixture data extension (`tests/fixtures/ground-truth.json`). On 2026-11-25 the generated code of every available target ran unchanged on a CloudPage: 142 of 142 target runs (48 cases) returned the same rows as the query activity.
175
+
176
+ ## License
177
+
178
+ MIT, Joern Berkefeld
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
- "name": "sfmc-sql-converter",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "sfmc-sql-converter",
3
+ "version": "0.2.0",
4
+ "description": "Converts SQL SELECT queries to Salesforce Marketing Cloud lookup code (SSJS, AMPscript) and back",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "exports": {
8
+ ".": "./src/index.js"
9
+ },
10
+ "files": [
11
+ "src"
12
+ ],
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/JoernBerkefeld/sfmc-sql-converter.git"
16
+ },
17
+ "bugs": {
18
+ "url": "https://github.com/JoernBerkefeld/sfmc-sql-converter/issues"
19
+ },
20
+ "homepage": "https://github.com/JoernBerkefeld/sfmc-sql-converter#readme",
21
+ "author": "Joern Berkefeld <joern.berkefeld@gmail.com>",
22
+ "keywords": [
23
+ "sql",
24
+ "sfmc",
25
+ "marketing-cloud",
26
+ "ssjs",
27
+ "ampscript",
28
+ "wsproxy",
29
+ "handlebars"
30
+ ],
31
+ "license": "MIT",
32
+ "scripts": {
33
+ "test": "node --test tests/*.test.js",
34
+ "lint": "eslint .",
35
+ "lint:fix": "eslint --fix .",
36
+ "prepare": "husky || true",
37
+ "format": "prettier --write .",
38
+ "format:check": "prettier --check ."
39
+ },
40
+ "engines": {
41
+ "node": ">=22.0.0"
42
+ },
43
+ "lint-staged": {
44
+ "*.{js,mjs,cjs}": [
45
+ "eslint --fix"
46
+ ]
47
+ },
48
+ "devDependencies": {
49
+ "@eslint/js": "^10.0.1",
50
+ "eslint": "^10.15.0",
51
+ "eslint-config-prettier": "^10.1.8",
52
+ "eslint-plugin-jsdoc": "^65.5.2",
53
+ "eslint-plugin-prettier": "^5.5.7",
54
+ "eslint-plugin-unicorn": "^73.0.0",
55
+ "globals": "^17.14.0",
56
+ "husky": "^9.1.7",
57
+ "lint-staged": "^17.6.2",
58
+ "prettier": "^3.10.1"
59
+ }
60
+ }
package/src/clauses.js ADDED
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Clause bookkeeping shared by the emitters, the SQL printer and convert(): stable clause ids
3
+ * for every part of a query, and a small code writer that records where each clause ends up
4
+ * in generated text.
5
+ *
6
+ * Clause ids: `column-N` (explicit SELECT columns), `top`, `from`, `where-N` (each single
7
+ * condition, numbered left to right; AND / OR nodes and brackets get no id) and `order-N`
8
+ * (each ORDER BY item).
9
+ */
10
+
11
+ /**
12
+ * @typedef {import('./sql-parser.js').SelectAst} SelectAst
13
+ * @typedef {import('./sql-parser.js').Loc} Loc
14
+ */
15
+
16
+ /**
17
+ * @typedef {object} Clause
18
+ * @property {string} clauseId stable id, e.g. `where-0`
19
+ * @property {'column'|'top'|'from'|'condition'|'order'} kind clause kind
20
+ * @property {object|null} node the AST node (null for `top`)
21
+ * @property {Loc|null} loc where the clause is in the source text (null when unknown)
22
+ */
23
+
24
+ /**
25
+ * @typedef {object} Span
26
+ * @property {string} clauseId clause id
27
+ * @property {number} start 0-based start offset in the generated text
28
+ * @property {number} end 0-based exclusive end offset in the generated text
29
+ */
30
+
31
+ const TOP_PATTERN = /^SELECT\s+TOP\s*(?:\(\s*\d+\s*\)|\d+)/i;
32
+
33
+ /**
34
+ * Converts 0-based offsets of a text into a `Loc`.
35
+ *
36
+ * @param {string} text source text
37
+ * @param {number} start 0-based start offset
38
+ * @param {number} end 0-based exclusive end offset
39
+ * @returns {Loc} location
40
+ */
41
+ export function locFromOffsets(text, start, end) {
42
+ const position = (offset) => {
43
+ let line = 1;
44
+ let lineStart = 0;
45
+ for (let index = 0; index < offset; index++) {
46
+ if (text[index] !== '\n') {
47
+ continue;
48
+ }
49
+
50
+ line++;
51
+ lineStart = index + 1;
52
+ }
53
+ return { line, column: offset - lineStart + 1 };
54
+ };
55
+ const from = position(start);
56
+ const to = position(end);
57
+ return {
58
+ start,
59
+ end,
60
+ line: from.line,
61
+ column: from.column,
62
+ endLine: to.line,
63
+ endColumn: to.column,
64
+ };
65
+ }
66
+
67
+ /**
68
+ * Lists the condition nodes (compare / like / in / between / null) of a WHERE tree from left
69
+ * to right.
70
+ *
71
+ * @param {object|null} expr WHERE expression
72
+ * @returns {object[]} condition nodes
73
+ */
74
+ export function conditionsOf(expr) {
75
+ if (!expr) {
76
+ return [];
77
+ }
78
+ if (expr.type === 'and' || expr.type === 'or') {
79
+ return [...conditionsOf(expr.left), ...conditionsOf(expr.right)];
80
+ }
81
+ return [expr];
82
+ }
83
+
84
+ /**
85
+ * Checks whether a LIKE pattern means "contains": `%x%` where x neither starts nor ends with
86
+ * `%`. Only such patterns behave the same as the WSProxy / Rows.Retrieve `like` operator,
87
+ * which always wraps its value in `%…%`.
88
+ *
89
+ * @param {string} pattern LIKE pattern
90
+ * @returns {boolean} true for a contains pattern
91
+ */
92
+ export function isContainsPattern(pattern) {
93
+ if (pattern.length < 2 || !pattern.startsWith('%') || !pattern.endsWith('%')) {
94
+ return false;
95
+ }
96
+ const inner = pattern.slice(1, -1);
97
+ return !inner.startsWith('%') && !inner.endsWith('%');
98
+ }
99
+
100
+ /**
101
+ * Reads a Next LIKE value the way the forward emitter accepts it: the text between one leading
102
+ * and one trailing `%`. Next matches "contains" and ignores wildcards, so an inner `_`, `[` or
103
+ * `%` has no SQL equivalent.
104
+ *
105
+ * @param {string} value LIKE value from Next code
106
+ * @returns {{inner: string, isContains: boolean}|null} the inner text and whether the value
107
+ * already was `%text%`, or null when the inner text holds `_`, `[` or `%`
108
+ */
109
+ export function nextLikeInner(value) {
110
+ const inner = value.replace(/^%/, '').replace(/%$/, '');
111
+ if (/[%_[]/.test(inner)) {
112
+ return null;
113
+ }
114
+ return { inner, isContains: isContainsPattern(value) };
115
+ }
116
+
117
+ /**
118
+ * Explains why a Next LIKE value with `_`, `[` or `%` inside cannot be read back.
119
+ *
120
+ * @param {string} value LIKE value from Next code
121
+ * @returns {string} message
122
+ */
123
+ export function nextLikeWildcardMessage(value) {
124
+ return `Next matches LIKE as "contains" and ignores wildcards, so "${value}" has no SQL equivalent: the _, [ or % inside the text would mean a wildcard in SQL. Use plain text, e.g. "%text%".`;
125
+ }
126
+
127
+ /**
128
+ * Returns the filter Value used for an anchored LIKE pattern: the pattern without leading and
129
+ * trailing `%` (the `like` operator adds them again), or `%` when nothing is left, because an
130
+ * empty filter Value is rejected.
131
+ *
132
+ * @param {string} pattern LIKE pattern
133
+ * @returns {string} wider filter value
134
+ */
135
+ export function likeFilterValue(pattern) {
136
+ return pattern.replace(/^%+/, '').replace(/%+$/, '') || '%';
137
+ }
138
+
139
+ /**
140
+ * Finds the location of `TOP n` in the source text, falling back to the SELECT keyword.
141
+ *
142
+ * @param {SelectAst} ast statement
143
+ * @param {string} [text] source text the AST was parsed from
144
+ * @returns {Loc|null} location or null when no text is known
145
+ */
146
+ function findTopLoc(ast, text) {
147
+ if (typeof text !== 'string' || !ast.loc) {
148
+ return null;
149
+ }
150
+ const match = TOP_PATTERN.exec(text.slice(ast.loc.start));
151
+ const length = match ? match[0].length : Math.min(6, text.length - ast.loc.start);
152
+ return locFromOffsets(text, ast.loc.start, ast.loc.start + length);
153
+ }
154
+
155
+ /**
156
+ * Lists every clause of a query with its stable id.
157
+ *
158
+ * @param {SelectAst} ast statement
159
+ * @param {string} [text] source text (only used to locate TOP, which has no node)
160
+ * @returns {{clauses: Clause[], idOf: Map<object, string>}} the clauses in source order and
161
+ * a node → clause id lookup
162
+ */
163
+ export function collectClauses(ast, text) {
164
+ /**
165
+ @type {Clause[]}
166
+ */
167
+ const clauses = [];
168
+ const idOf = new Map();
169
+ const add = (clauseId, kind, node, loc) => {
170
+ clauses.push({ clauseId, kind, node, loc: loc ?? null });
171
+ if (node) {
172
+ idOf.set(node, clauseId);
173
+ }
174
+ };
175
+ if (ast.top !== null && ast.top !== undefined) {
176
+ add('top', 'top', null, findTopLoc(ast, text));
177
+ }
178
+ if (Array.isArray(ast.columns)) {
179
+ for (const [index, column] of ast.columns.entries()) {
180
+ add(`column-${index}`, 'column', column, column.loc);
181
+ }
182
+ }
183
+ add('from', 'from', ast.from, ast.from.loc);
184
+ for (const [index, condition] of conditionsOf(ast.where).entries()) {
185
+ add(`where-${index}`, 'condition', condition, condition.loc);
186
+ }
187
+ const orderBy = ast.orderBy ?? [];
188
+ for (const [index, item] of orderBy.entries()) {
189
+ add(`order-${index}`, 'order', item, item.loc);
190
+ }
191
+ return { clauses, idOf };
192
+ }
193
+
194
+ /**
195
+ * Accumulates generated text and records the spans of clauses inside it.
196
+ */
197
+ export class CodeWriter {
198
+ /**
199
+ generated text so far
200
+ */
201
+ code = '';
202
+
203
+ /**
204
+ @type {Span[]} clause spans in `code`
205
+ */
206
+ spans = [];
207
+
208
+ /**
209
+ * Appends text.
210
+ *
211
+ * @param {string} text text to append
212
+ * @returns {CodeWriter} this writer
213
+ */
214
+ write(text) {
215
+ this.code += text;
216
+ return this;
217
+ }
218
+
219
+ /**
220
+ * Appends text and records it as (part of) a clause.
221
+ *
222
+ * @param {string|undefined} clauseId clause id; when empty the text is written unmarked
223
+ * @param {string} text text to append
224
+ * @returns {CodeWriter} this writer
225
+ */
226
+ mark(clauseId, text) {
227
+ if (!clauseId) {
228
+ return this.write(text);
229
+ }
230
+ const start = this.code.length;
231
+ this.code += text;
232
+ this.spans.push({ clauseId, start, end: this.code.length });
233
+ return this;
234
+ }
235
+
236
+ /**
237
+ * Runs a callback and records everything it writes as one clause span.
238
+ *
239
+ * @param {string|undefined} clauseId clause id; when empty nothing is recorded
240
+ * @param {() => void} callback writes the clause text
241
+ * @returns {CodeWriter} this writer
242
+ */
243
+ region(clauseId, callback) {
244
+ const start = this.code.length;
245
+ callback();
246
+ if (clauseId) {
247
+ this.spans.push({ clauseId, start, end: this.code.length });
248
+ }
249
+ return this;
250
+ }
251
+ }