sfmc-sql-converter 0.1.0 → 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/README.md +57 -38
- package/package.json +17 -5
- package/src/clauses.js +27 -0
- package/src/convert.js +108 -49
- package/src/emit-mce.js +1 -1
- package/src/emit-mcn.js +788 -0
- package/src/index.js +12 -1
- package/src/messages.js +5 -0
- package/src/parse-ampscript.js +228 -10
- package/src/parse-handlebars.js +956 -0
- package/src/print-sql.js +34 -21
- package/src/sql-parser.js +6 -1
package/README.md
CHANGED
|
@@ -42,15 +42,16 @@ console.log(back.outputs[0].code);
|
|
|
42
42
|
|
|
43
43
|
`input` is SQL (direction `toCode`) or SSJS / AMPscript (direction `toSql`).
|
|
44
44
|
|
|
45
|
-
| Option
|
|
46
|
-
|
|
|
47
|
-
| `platform`
|
|
48
|
-
| `direction`
|
|
49
|
-
| `
|
|
50
|
-
| `
|
|
51
|
-
| `
|
|
52
|
-
| `
|
|
53
|
-
| `
|
|
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`) |
|
|
54
55
|
|
|
55
56
|
Unknown `platform` or `direction` values throw a `TypeError`. Everything else never throws: problems come back as messages.
|
|
56
57
|
|
|
@@ -96,10 +97,25 @@ When a target can't express the query, its output has `unavailable` with a plain
|
|
|
96
97
|
|
|
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`.
|
|
98
99
|
|
|
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.
|
|
100
113
|
|
|
101
114
|
## Rewrites and dropped clauses
|
|
102
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
|
+
|
|
103
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`).
|
|
104
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`).
|
|
105
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.
|
|
@@ -110,43 +126,46 @@ The Next targets (`handlebars-query`, `handlebars-queryfirst`, `ampscript-lookup
|
|
|
110
126
|
## Reading code back (`toSql`)
|
|
111
127
|
|
|
112
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.
|
|
113
131
|
- Variables set to fixed values are resolved. Values only known at run time are errors.
|
|
114
132
|
- A hand-written `like` filter without a `sqlLike()` check reads back as `LIKE '%value%'`, because the filter matches anywhere (`LIKE_MATCHES_ANYWHERE`).
|
|
115
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).
|
|
116
134
|
|
|
117
135
|
## Round trip
|
|
118
136
|
|
|
119
|
-
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.
|
|
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.
|
|
120
138
|
|
|
121
139
|
## Message codes
|
|
122
140
|
|
|
123
|
-
| Code | Meaning
|
|
124
|
-
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
125
|
-
| `EMPTY_INPUT` | Nothing to convert
|
|
126
|
-
| `UNEXPECTED_CHARACTER`, `UNTERMINATED_STRING`, `UNTERMINATED_IDENTIFIER`, `UNTERMINATED_COMMENT`, `EMPTY_IDENTIFIER` | The text can't be split into words
|
|
127
|
-
| `UNSUPPORTED_LINE_SEPARATOR` | A name contains the line separator U+2028 or U+2029
|
|
128
|
-
| `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
|
|
129
|
-
| `INVALID_TOP` | TOP is not a whole number above 0
|
|
130
|
-
| `LITERAL_ON_LEFT`, `NULL_COMPARISON` | Write `Column = value`, and `IS NULL` instead of `= NULL`
|
|
131
|
-
| `NESTING_TOO_DEEP`, `INTERNAL_ERROR` | The input can't be read
|
|
132
|
-
| `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
|
|
133
|
-
| `SYSTEM_DATA_VIEW` | System data views can't be read with a lookup
|
|
134
|
-
| `TABLE_HINT_IGNORED` | Table hints such as `WITH (NOLOCK)` are ignored
|
|
135
|
-
| `ORDER_BY_DROPPED`, `TOP_DROPPED` | The target leaves the clause out
|
|
136
|
-
| `FIRST_BATCH_ONLY` | WSProxy without paging reads only the first batch of up to 2,500 rows
|
|
137
|
-
| `
|
|
138
|
-
| `
|
|
139
|
-
| `
|
|
140
|
-
| `
|
|
141
|
-
| `
|
|
142
|
-
| `
|
|
143
|
-
| `
|
|
144
|
-
| `
|
|
145
|
-
| `
|
|
146
|
-
| `
|
|
147
|
-
| `
|
|
148
|
-
| `
|
|
149
|
-
| `
|
|
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%'` |
|
|
150
169
|
|
|
151
170
|
All codes are exported as constants and in `MESSAGE_CODES`.
|
|
152
171
|
|
package/package.json
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sfmc-sql-converter",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Converts SQL SELECT queries to Salesforce Marketing Cloud lookup code (SSJS, AMPscript) and back",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/index.js",
|
|
7
7
|
"exports": {
|
|
8
8
|
".": "./src/index.js"
|
|
9
9
|
},
|
|
10
|
-
"files": [
|
|
10
|
+
"files": [
|
|
11
|
+
"src"
|
|
12
|
+
],
|
|
11
13
|
"repository": {
|
|
12
14
|
"type": "git",
|
|
13
15
|
"url": "git+https://github.com/JoernBerkefeld/sfmc-sql-converter.git"
|
|
@@ -17,7 +19,15 @@
|
|
|
17
19
|
},
|
|
18
20
|
"homepage": "https://github.com/JoernBerkefeld/sfmc-sql-converter#readme",
|
|
19
21
|
"author": "Joern Berkefeld <joern.berkefeld@gmail.com>",
|
|
20
|
-
"keywords": [
|
|
22
|
+
"keywords": [
|
|
23
|
+
"sql",
|
|
24
|
+
"sfmc",
|
|
25
|
+
"marketing-cloud",
|
|
26
|
+
"ssjs",
|
|
27
|
+
"ampscript",
|
|
28
|
+
"wsproxy",
|
|
29
|
+
"handlebars"
|
|
30
|
+
],
|
|
21
31
|
"license": "MIT",
|
|
22
32
|
"scripts": {
|
|
23
33
|
"test": "node --test tests/*.test.js",
|
|
@@ -31,13 +41,15 @@
|
|
|
31
41
|
"node": ">=22.0.0"
|
|
32
42
|
},
|
|
33
43
|
"lint-staged": {
|
|
34
|
-
"*.{js,mjs,cjs}": [
|
|
44
|
+
"*.{js,mjs,cjs}": [
|
|
45
|
+
"eslint --fix"
|
|
46
|
+
]
|
|
35
47
|
},
|
|
36
48
|
"devDependencies": {
|
|
37
49
|
"@eslint/js": "^10.0.1",
|
|
38
50
|
"eslint": "^10.15.0",
|
|
39
51
|
"eslint-config-prettier": "^10.1.8",
|
|
40
|
-
"eslint-plugin-jsdoc": "^
|
|
52
|
+
"eslint-plugin-jsdoc": "^65.5.2",
|
|
41
53
|
"eslint-plugin-prettier": "^5.5.7",
|
|
42
54
|
"eslint-plugin-unicorn": "^73.0.0",
|
|
43
55
|
"globals": "^17.14.0",
|
package/src/clauses.js
CHANGED
|
@@ -97,6 +97,33 @@ export function isContainsPattern(pattern) {
|
|
|
97
97
|
return !inner.startsWith('%') && !inner.endsWith('%');
|
|
98
98
|
}
|
|
99
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
|
+
|
|
100
127
|
/**
|
|
101
128
|
* Returns the filter Value used for an anchored LIKE pattern: the pattern without leading and
|
|
102
129
|
* trailing `%` (the `like` operator adds them again), or `%` when nothing is left, because an
|
package/src/convert.js
CHANGED
|
@@ -6,14 +6,23 @@
|
|
|
6
6
|
* back with the reverse parser and compared with the query, minus the clauses the target
|
|
7
7
|
* dropped). Direction `toSql`: lookup code → canonical SQL.
|
|
8
8
|
*
|
|
9
|
-
*
|
|
10
|
-
* Cloud Next)
|
|
9
|
+
* Platform `mce` (Marketing Cloud Engagement) reads data extensions with SSJS / AMPscript;
|
|
10
|
+
* `mcn` (Marketing Cloud Next) reads Sales Cloud objects (`dataSource: 'CRM'`) or marketing
|
|
11
|
+
* objects (`'MO'`) with Handlebars / AMPscript, limited to what the live probes proved (see
|
|
12
|
+
* `NEXT_RULES` in emit-mcn.js).
|
|
11
13
|
*/
|
|
12
14
|
|
|
13
15
|
import { collectClauses, locFromOffsets } from './clauses.js';
|
|
14
16
|
import { MCE_TARGETS } from './emit-mce.js';
|
|
15
|
-
import {
|
|
17
|
+
import { MCN_TARGETS } from './emit-mcn.js';
|
|
18
|
+
import {
|
|
19
|
+
DE_KEY_ASSUMED,
|
|
20
|
+
ORDER_BY_NEEDS_TOP,
|
|
21
|
+
SELECT_STAR_NEEDS_COLUMNS,
|
|
22
|
+
createMessage,
|
|
23
|
+
} from './messages.js';
|
|
16
24
|
import { parseAmpscript } from './parse-ampscript.js';
|
|
25
|
+
import { parseHandlebars } from './parse-handlebars.js';
|
|
17
26
|
import { parseSsjs } from './parse-ssjs.js';
|
|
18
27
|
import { normalizeSql, printSql, printSqlWithSpans } from './print-sql.js';
|
|
19
28
|
import { parseSql } from './sql-parser.js';
|
|
@@ -31,7 +40,8 @@ import { parseSql } from './sql-parser.js';
|
|
|
31
40
|
* @property {string} [deName] data extension name (toSql: used when the code does not carry it)
|
|
32
41
|
* @property {string} [deKey] data extension external key (default: the name)
|
|
33
42
|
* @property {string[]} [columns] the columns `SELECT *` stands for
|
|
34
|
-
* @property {'CRM'|'MO'} [dataSource] Next data source
|
|
43
|
+
* @property {'CRM'|'MO'} [dataSource] Next data source: Sales Cloud object (default) or
|
|
44
|
+
* marketing object
|
|
35
45
|
* @property {{fields: {name: string}[]}} [schema] data extension fields
|
|
36
46
|
* @property {{rowsAsObjects?: boolean, paging?: boolean}} [output] WSProxy output options
|
|
37
47
|
*/
|
|
@@ -69,21 +79,32 @@ import { parseSql } from './sql-parser.js';
|
|
|
69
79
|
* there was nothing to compare (a filter without a data extension name)
|
|
70
80
|
*/
|
|
71
81
|
|
|
72
|
-
|
|
82
|
+
/**
|
|
83
|
+
* Reads Next AMPscript back (LookupRows on a marketing object, RetrieveSalesforceObjects).
|
|
84
|
+
*
|
|
85
|
+
* @param {string} code AMPscript code
|
|
86
|
+
* @returns {{ast: SelectAst|null, messages: Message[], meta: object}} parse result
|
|
87
|
+
*/
|
|
88
|
+
function parseNextAmpscript(code) {
|
|
89
|
+
return parseAmpscript(code, { platform: 'mcn' });
|
|
90
|
+
}
|
|
73
91
|
|
|
74
92
|
/**
|
|
75
|
-
*
|
|
93
|
+
* Returns the reverse parser of a target.
|
|
94
|
+
*
|
|
95
|
+
* @param {{language: string}} target target
|
|
96
|
+
* @param {'mce'|'mcn'} platform platform
|
|
97
|
+
* @returns {(code: string) => {ast: SelectAst|null, messages: Message[], meta: object}} parser
|
|
76
98
|
*/
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
{
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
]);
|
|
99
|
+
function reverseParserOf(target, platform) {
|
|
100
|
+
if (target.language === 'handlebars') {
|
|
101
|
+
return parseHandlebars;
|
|
102
|
+
}
|
|
103
|
+
if (target.language === 'ssjs') {
|
|
104
|
+
return parseSsjs;
|
|
105
|
+
}
|
|
106
|
+
return platform === 'mcn' ? parseNextAmpscript : parseAmpscript;
|
|
107
|
+
}
|
|
87
108
|
|
|
88
109
|
/**
|
|
89
110
|
* Builds the list of unavailable outputs for a target list.
|
|
@@ -143,8 +164,7 @@ function spanText(code, spans, clauseId) {
|
|
|
143
164
|
* @returns {{ok: boolean, sql: string, note?: string}} round trip
|
|
144
165
|
*/
|
|
145
166
|
function roundTripOf(ast, target, result, options) {
|
|
146
|
-
const
|
|
147
|
-
const back = parse(result.code);
|
|
167
|
+
const back = reverseParserOf(target, options.platform)(result.code);
|
|
148
168
|
if (!back.ast) {
|
|
149
169
|
const reason = back.messages.find((message) => message.severity === 'error');
|
|
150
170
|
return {
|
|
@@ -166,9 +186,8 @@ function roundTripOf(ast, target, result, options) {
|
|
|
166
186
|
} else if (left.length) {
|
|
167
187
|
note = `Same query without ${left.join(' and ')}, which ${target.label} leaves out.`;
|
|
168
188
|
}
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
: { ok: isOk, sql: printSql(back.ast) };
|
|
189
|
+
const sql = printSql(back.ast, { isTyped: Boolean(target.normalize.isTyped) });
|
|
190
|
+
return note ? { ok: isOk, sql, note } : { ok: isOk, sql };
|
|
172
191
|
}
|
|
173
192
|
|
|
174
193
|
/**
|
|
@@ -180,22 +199,22 @@ function roundTripOf(ast, target, result, options) {
|
|
|
180
199
|
*/
|
|
181
200
|
function convertToCode(input, options) {
|
|
182
201
|
const { ast, messages } = parseSql(input);
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
clauseMap: [],
|
|
188
|
-
roundTrip: { ok: false, sql: '', note: NEXT_PENDING },
|
|
189
|
-
};
|
|
190
|
-
}
|
|
202
|
+
const targets =
|
|
203
|
+
options.platform === 'mcn'
|
|
204
|
+
? MCN_TARGETS.filter((target) => target.dataSource === options.dataSource)
|
|
205
|
+
: MCE_TARGETS;
|
|
191
206
|
if (!ast) {
|
|
192
207
|
return {
|
|
193
|
-
outputs: unavailableOutputs(
|
|
208
|
+
outputs: unavailableOutputs(targets, 'Fix the errors in the query first.'),
|
|
194
209
|
messages,
|
|
195
210
|
clauseMap: [],
|
|
196
211
|
roundTrip: { ok: false, sql: '', note: 'The query has errors.' },
|
|
197
212
|
};
|
|
198
213
|
}
|
|
214
|
+
if (options.platform === 'mcn') {
|
|
215
|
+
const emitOptions = { sourceText: input };
|
|
216
|
+
return { messages, ...emitAll(ast, input, targets, emitOptions, options) };
|
|
217
|
+
}
|
|
199
218
|
if (!options.deKey) {
|
|
200
219
|
messages.push(
|
|
201
220
|
createMessage(
|
|
@@ -225,10 +244,24 @@ function convertToCode(input, options) {
|
|
|
225
244
|
output: options.output,
|
|
226
245
|
sourceText: input,
|
|
227
246
|
};
|
|
247
|
+
return { messages, ...emitAll(ast, input, targets, emitOptions, options) };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Runs every target's emitter and collects outputs, the clause map and the round trip.
|
|
252
|
+
*
|
|
253
|
+
* @param {SelectAst} ast parsed query
|
|
254
|
+
* @param {string} input SQL text
|
|
255
|
+
* @param {ReadonlyArray<object>} targets targets with `emit` and `normalize`
|
|
256
|
+
* @param {object} emitOptions options passed to the emitters
|
|
257
|
+
* @param {ConvertOptions} options convert options
|
|
258
|
+
* @returns {{outputs: Output[], clauseMap: ClauseMapEntry[], roundTrip: object}} result parts
|
|
259
|
+
*/
|
|
260
|
+
function emitAll(ast, input, targets, emitOptions, options) {
|
|
228
261
|
const { clauses } = collectClauses(ast, input);
|
|
229
262
|
const outputs = [];
|
|
230
263
|
const clauseMap = [];
|
|
231
|
-
for (const target of
|
|
264
|
+
for (const target of targets) {
|
|
232
265
|
const result = target.emit(ast, emitOptions);
|
|
233
266
|
const base = { id: target.id, language: target.language, label: target.label };
|
|
234
267
|
if (result.unavailable) {
|
|
@@ -257,7 +290,6 @@ function convertToCode(input, options) {
|
|
|
257
290
|
const first = outputs.find((output) => output.roundTrip);
|
|
258
291
|
return {
|
|
259
292
|
outputs,
|
|
260
|
-
messages,
|
|
261
293
|
clauseMap,
|
|
262
294
|
roundTrip: first
|
|
263
295
|
? first.roundTrip
|
|
@@ -270,13 +302,19 @@ function convertToCode(input, options) {
|
|
|
270
302
|
* AMPscript, else SSJS; the other parser is tried when the first one fails).
|
|
271
303
|
*
|
|
272
304
|
* @param {string} input code
|
|
305
|
+
* @param {'mce'|'mcn'} platform platform (Next reads Handlebars and Next AMPscript)
|
|
273
306
|
* @returns {{ast: SelectAst|null, messages: Message[], meta: object}} parse result
|
|
274
307
|
*/
|
|
275
|
-
function parseCode(input) {
|
|
308
|
+
function parseCode(input, platform) {
|
|
276
309
|
const isLooksLikeAmpscript = /%%\[|%%=|\bSET\s+@/i.test(input);
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
310
|
+
let parsers;
|
|
311
|
+
if (platform === 'mcn') {
|
|
312
|
+
parsers = /\{\{/.test(input)
|
|
313
|
+
? [parseHandlebars, parseNextAmpscript]
|
|
314
|
+
: [parseNextAmpscript, parseHandlebars];
|
|
315
|
+
} else {
|
|
316
|
+
parsers = isLooksLikeAmpscript ? [parseAmpscript, parseSsjs] : [parseSsjs, parseAmpscript];
|
|
317
|
+
}
|
|
280
318
|
const primary = parsers[0](input);
|
|
281
319
|
if (primary.ast) {
|
|
282
320
|
return primary;
|
|
@@ -285,6 +323,29 @@ function parseCode(input) {
|
|
|
285
323
|
return secondary.ast ? secondary : primary;
|
|
286
324
|
}
|
|
287
325
|
|
|
326
|
+
/**
|
|
327
|
+
* A query activity rejects ORDER BY without TOP (live check 2026-11-26, DB
|
|
328
|
+
* `entries/mce/mce-sql-query-activity-where-semantics.json`): tell the reader when the printed
|
|
329
|
+
* SQL sorts every row.
|
|
330
|
+
*
|
|
331
|
+
* @param {SelectAst} ast statement read from the code
|
|
332
|
+
* @param {'mce'|'mcn'} platform platform
|
|
333
|
+
* @returns {Message[]} the info message, or none
|
|
334
|
+
*/
|
|
335
|
+
function orderByNeedsTop(ast, platform) {
|
|
336
|
+
if (platform !== 'mce' || !ast.orderBy?.length || (ast.top !== null && ast.top !== undefined)) {
|
|
337
|
+
return [];
|
|
338
|
+
}
|
|
339
|
+
return [
|
|
340
|
+
createMessage(
|
|
341
|
+
'info',
|
|
342
|
+
ORDER_BY_NEEDS_TOP,
|
|
343
|
+
'The SQL sorts without TOP. A query activity in Automation Studio rejects ORDER BY without TOP, so add TOP with the number of rows you need before running it there.',
|
|
344
|
+
ast.orderBy[0].loc ?? ast.loc,
|
|
345
|
+
),
|
|
346
|
+
];
|
|
347
|
+
}
|
|
348
|
+
|
|
288
349
|
/**
|
|
289
350
|
* Code → SQL.
|
|
290
351
|
*
|
|
@@ -294,15 +355,7 @@ function parseCode(input) {
|
|
|
294
355
|
*/
|
|
295
356
|
function convertToSql(input, options) {
|
|
296
357
|
const base = { id: 'sql', language: 'sql', label: 'SQL' };
|
|
297
|
-
|
|
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 : '');
|
|
358
|
+
const back = parseCode(typeof input === 'string' ? input : '', options.platform);
|
|
306
359
|
if (!back.ast) {
|
|
307
360
|
return {
|
|
308
361
|
outputs: [{ ...base, unavailable: 'Fix the errors in the code first.', spans: [] }],
|
|
@@ -316,7 +369,9 @@ function convertToSql(input, options) {
|
|
|
316
369
|
if (options.deName && (!back.meta?.deName || !ast.from.name)) {
|
|
317
370
|
ast.from = { ...ast.from, name: options.deName };
|
|
318
371
|
}
|
|
319
|
-
|
|
372
|
+
// Handlebars keeps the value type: p1="5" is text and must not print as 5
|
|
373
|
+
const typed = { isTyped: back.meta?.target?.startsWith('handlebars') ?? false };
|
|
374
|
+
const { sql, spans } = printSqlWithSpans(ast, typed);
|
|
320
375
|
const clauseMap = collectClauses(ast).clauses.map((clause) => ({
|
|
321
376
|
outputId: 'sql',
|
|
322
377
|
clauseId: clause.clauseId,
|
|
@@ -340,10 +395,10 @@ function convertToSql(input, options) {
|
|
|
340
395
|
};
|
|
341
396
|
}
|
|
342
397
|
const again = parseSql(sql);
|
|
343
|
-
const isOk = Boolean(again.ast) && normalizeSql(again.ast) === normalizeSql(ast);
|
|
398
|
+
const isOk = Boolean(again.ast) && normalizeSql(again.ast, typed) === normalizeSql(ast, typed);
|
|
344
399
|
return {
|
|
345
400
|
outputs: [{ ...base, code: sql, spans }],
|
|
346
|
-
messages: back.messages,
|
|
401
|
+
messages: [...back.messages, ...orderByNeedsTop(ast, options.platform)],
|
|
347
402
|
clauseMap,
|
|
348
403
|
roundTrip: isOk
|
|
349
404
|
? { ok: isOk, sql }
|
|
@@ -367,6 +422,10 @@ export function convert(input, options = {}) {
|
|
|
367
422
|
if (direction !== 'toCode' && direction !== 'toSql') {
|
|
368
423
|
throw new TypeError(`Unknown direction "${direction}". Use "toCode" or "toSql".`);
|
|
369
424
|
}
|
|
370
|
-
const
|
|
425
|
+
const dataSource = options.dataSource ?? 'CRM';
|
|
426
|
+
if (dataSource !== 'CRM' && dataSource !== 'MO') {
|
|
427
|
+
throw new TypeError(`Unknown data source "${dataSource}". Use "CRM" or "MO".`);
|
|
428
|
+
}
|
|
429
|
+
const resolved = { ...options, platform, dataSource };
|
|
371
430
|
return direction === 'toSql' ? convertToSql(input, resolved) : convertToCode(input, resolved);
|
|
372
431
|
}
|
package/src/emit-mce.js
CHANGED
|
@@ -1110,7 +1110,7 @@ function writeAmpPairs(out, pairs, idOf) {
|
|
|
1110
1110
|
* @param {CodeWriter} out writer
|
|
1111
1111
|
* @param {{name: string, clauseId?: string}[]|null} columns selected columns
|
|
1112
1112
|
*/
|
|
1113
|
-
function writeAmpLoop(out, columns) {
|
|
1113
|
+
export function writeAmpLoop(out, columns) {
|
|
1114
1114
|
out.write(
|
|
1115
1115
|
'SET @rowCount = RowCount(@rows)\nFOR @i = 1 TO @rowCount DO\n SET @row = Row(@rows, @i)\n',
|
|
1116
1116
|
);
|