@zerodot/sql 1.0.0 → 1.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/README.md +63 -16
- package/dist/index.cjs +163 -17
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -1,30 +1,77 @@
|
|
|
1
1
|
# @zerodot/sql
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<img src="https://raw.githubusercontent.com/zerodot-io/nodes/main/packages/sql/sql.svg" alt="SQL logo" width="48" height="48">
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Run parameterized SQL queries against Postgres or MySQL databases with one node. The query runs once for each input item. The node gives the rows back as items. Connect with a SQL connection credential that has a driver, a host or connection string, and the login.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
## Install
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
- `mysql`
|
|
9
|
+
In zerodot, go to **System > Nodes** and install **SQL**.
|
|
11
10
|
|
|
12
|
-
|
|
11
|
+
Manual: install `@zerodot/sql` where the web app and the worker run, and add it to `ZERODOT_NODE_PACKAGES`.
|
|
13
12
|
|
|
14
|
-
##
|
|
13
|
+
## Nodes
|
|
15
14
|
|
|
16
15
|
### SQL (`sql.query`)
|
|
17
16
|
|
|
18
|
-
Execute
|
|
17
|
+
- **Operation**: Execute Query (`executeQuery`). This is the only operation.
|
|
19
18
|
|
|
20
|
-
|
|
21
|
-
- **Query**: SQL to run. Use driver-native placeholders (`$1`, `$2` for Postgres, `?` for MySQL).
|
|
22
|
-
- **Query Parameters**: Comma-separated values/expressions bound to placeholders.
|
|
23
|
-
- **Timeout**: Request timeout in milliseconds.
|
|
19
|
+
**Query.** Write the SQL text. Use the placeholders of your driver for values: `$1`, `$2`, and so on for Postgres, and `?` for MySQL. Example for Postgres: `SELECT id, name FROM users WHERE id = $1`.
|
|
24
20
|
|
|
25
|
-
|
|
21
|
+
**Query Parameters.** Write the values for the placeholders, in order, with commas between them. Plain text is split at each comma, spaces around a value are removed, empty entries are dropped, and each value is sent as text. For example, `42,active` gives `"42"` and `"active"`. You can also use expressions, such as `{{ $json.id }},{{ $json.status }}`. Each expression gives one value. An expression that returns an array gives one value for each element. When the field has an expression, only the values of the expressions are used, and the text outside `{{ }}` is ignored. A value from an expression keeps its type: a number, a boolean, or `null` stays as it is. A date becomes an ISO string. Other objects become JSON text.
|
|
26
22
|
|
|
27
|
-
|
|
23
|
+
**Items.** The node runs the query once for each input item. The expressions in **Query Parameters** and in **Query** see that item as `$json` and `$item`, and its position as `$index`. The rows of all items go into one output list. The rows do not say which item they came from. If the input has no items, the node gives an empty list and runs no query.
|
|
28
24
|
|
|
29
|
-
|
|
30
|
-
|
|
25
|
+
**Expressions in Query.** The **Query** field can also use `{{ }}` expressions. An expression is not written into the SQL text. Its value is bound as a parameter, in the place of the expression. So an input value cannot change the SQL. There is one exception. When the whole **Query** is one expression, such as `{{ $json.sql }}`, its value is run as SQL. Use this only for SQL that you trust.
|
|
26
|
+
|
|
27
|
+
- Postgres: the values of the expressions are numbered after the **Query Parameters**. If you give two Query Parameters, the first expression in **Query** is `$3`. You write the expression, and the node sets the number.
|
|
28
|
+
- MySQL: each expression becomes a value at its own place. The `?` marks that you write take the Query Parameters in order. The driver escapes each value and the node puts it into the statement.
|
|
29
|
+
- An array gives one placeholder for each element, for example `IN ({{ $json.ids }})`. An empty array gives `NULL`.
|
|
30
|
+
- An expression cannot be inside quotes or dollar quotes, for example `'{{ $json.name }}'`. The run fails. For a pattern, join the text in SQL, for example `name LIKE CONCAT('%', {{ $json.name }}, '%')`.
|
|
31
|
+
- An expression cannot be a table name, a column name, or a keyword such as `DESC`. It is a value. In `ORDER BY` a text value does not sort by that column.
|
|
32
|
+
- An expression cannot follow a type word, as in `INTERVAL {{ $json.span }}`. For Postgres, use a cast such as `{{ $json.span }}::interval`. Postgres can also need a cast to find the type of a value, for example `{{ $json.count }}::int`.
|
|
33
|
+
- For Postgres, a query with parameters can hold only one statement.
|
|
34
|
+
- Expressions in comments are ignored.
|
|
35
|
+
|
|
36
|
+
**Output.** Each row is one item with its columns as keys. For Postgres, a query that returns no rows gives an empty list. For MySQL, a statement that returns no rows gives one object with the result header, such as `affectedRows` and `insertId`. For Postgres, if the query returns several result sets, the rows of all sets are put into one list.
|
|
37
|
+
|
|
38
|
+
**Driver notes.**
|
|
39
|
+
- Postgres: the node sends the query with `unsafe` and the parameters. JSON and JSONB columns come back as parsed values. `date` columns are returned as text.
|
|
40
|
+
- MySQL: big numbers and dates come back as strings.
|
|
41
|
+
|
|
42
|
+
**Errors.** When a query fails, the run fails with the message of the driver. When the input has more than one item, the message ends with the item number, starting at 0, for example `(item 2)`.
|
|
43
|
+
|
|
44
|
+
**Timeout.** **Timeout (ms)** (`timeoutMs`) covers the connection and the run of the queries. The default is 30000 ms, and the maximum is 300000 ms. When the time is up, the connection is closed.
|
|
45
|
+
|
|
46
|
+
**Destructive operations.** The node runs any statement that you write, including changes and schema changes. It does not ask for a confirmation and does not check the statement. Do not use untrusted text as the whole **Query**.
|
|
47
|
+
|
|
48
|
+
**Binary data.** The node does not read or write binary data.
|
|
49
|
+
|
|
50
|
+
## Credentials
|
|
51
|
+
|
|
52
|
+
- **SQL connection** (`sql.connection`):
|
|
53
|
+
- **Driver** (`driver`): `postgres` or `mysql`. Required.
|
|
54
|
+
- **Connection String** (`connectionString`): a connection string. This field is secret. When it is set, the node uses it, and the **SSL** and **Ignore SSL Issues** fields still apply.
|
|
55
|
+
- **Host** (`host`): the host name. Required when **Connection String** is empty.
|
|
56
|
+
- **Port** (`port`): digits only. The default is 5432 for Postgres and 3306 for MySQL.
|
|
57
|
+
- **Database** (`database`): the database name. For Postgres, the default is `postgres`.
|
|
58
|
+
- **User** (`user`): the login name. For Postgres, the default is `postgres`.
|
|
59
|
+
- **Password** (`password`): the password. This field is secret.
|
|
60
|
+
- **SSL** (`ssl`): `disable` (the default) or `require`. With `require`, the node uses TLS and checks the server certificate.
|
|
61
|
+
- **Ignore SSL Issues** (`allowUnauthorizedCerts`): `true` or `false`. When it is `true`, the node uses TLS without checking the server certificate. This is used even when **SSL** is `disable`. Use it only when you trust the network.
|
|
62
|
+
|
|
63
|
+
The secret fields are **Password** and **Connection String**.
|
|
64
|
+
|
|
65
|
+
Set up the database user with the rights that your queries need. The node does not limit the statements.
|
|
66
|
+
|
|
67
|
+
Setup steps:
|
|
68
|
+
|
|
69
|
+
1. In zerodot, create a **SQL connection** credential.
|
|
70
|
+
2. Choose the **Driver**, `postgres` or `mysql`.
|
|
71
|
+
3. Either set **Connection String**, or set **Host**, **Port**, **Database**, **User**, and **Password**.
|
|
72
|
+
4. Set **SSL** if the database needs TLS.
|
|
73
|
+
5. Save the credential. zerodot runs `select 1` for Postgres, and `SELECT 1` for MySQL, to test it.
|
|
74
|
+
|
|
75
|
+
## License
|
|
76
|
+
|
|
77
|
+
AGPL-3.0-only
|
package/dist/index.cjs
CHANGED
|
@@ -69,12 +69,16 @@ function mysqlOptions(credential, options = {}) {
|
|
|
69
69
|
const { data } = credential;
|
|
70
70
|
if (sqlDriver(credential) !== "mysql") throw new Error("The credential driver is not mysql");
|
|
71
71
|
requireHostOrConnectionString(data);
|
|
72
|
+
const ssl = text(data.ssl) ?? "disable";
|
|
73
|
+
if (ssl !== "disable" && ssl !== "require") throw new Error(`Unknown SSL mode "${ssl}"`);
|
|
74
|
+
const tls = data.allowUnauthorizedCerts === "true" ? { rejectUnauthorized: false } : ssl === "require" ? { rejectUnauthorized: true } : void 0;
|
|
72
75
|
const connectionString = text(data.connectionString);
|
|
73
|
-
if (connectionString) return
|
|
76
|
+
if (connectionString) return tls ? {
|
|
77
|
+
uri: connectionString,
|
|
78
|
+
ssl: tls
|
|
79
|
+
} : connectionString;
|
|
74
80
|
const host = text(data.host);
|
|
75
81
|
if (!host) throw new Error("The credential has no \"host\"");
|
|
76
|
-
const ssl = text(data.ssl) ?? "disable";
|
|
77
|
-
if (ssl !== "disable" && ssl !== "require") throw new Error(`Unknown SSL mode "${ssl}"`);
|
|
78
82
|
const connection = {
|
|
79
83
|
host,
|
|
80
84
|
port: text(data.port) ? Number(data.port) : 3306,
|
|
@@ -89,8 +93,7 @@ function mysqlOptions(credential, options = {}) {
|
|
|
89
93
|
if (database) connection.database = database;
|
|
90
94
|
if (user) connection.user = user;
|
|
91
95
|
if (password) connection.password = password;
|
|
92
|
-
if (
|
|
93
|
-
else if (ssl === "require") connection.ssl = { rejectUnauthorized: true };
|
|
96
|
+
if (tls) connection.ssl = tls;
|
|
94
97
|
return connection;
|
|
95
98
|
}
|
|
96
99
|
/** The editor imports this package for the node catalog. Drivers load on first use. */
|
|
@@ -108,9 +111,12 @@ function toParam(value) {
|
|
|
108
111
|
return JSON.stringify(value);
|
|
109
112
|
}
|
|
110
113
|
const getResolvables = (value) => value.match(/\{\{[\s\S]*?\}\}/g) ?? [];
|
|
111
|
-
/**
|
|
114
|
+
/**
|
|
115
|
+
* Comma-separated values, unless the text contains expressions. Empty entries are dropped before
|
|
116
|
+
* the spaces are removed, so "a, , b" gives "a" and "b".
|
|
117
|
+
*/
|
|
112
118
|
function stringToArray(value) {
|
|
113
|
-
return value.split(",").
|
|
119
|
+
return value.split(",").map((entry) => entry.trim()).filter((entry) => entry !== "");
|
|
114
120
|
}
|
|
115
121
|
/**
|
|
116
122
|
* Query parameter values for one item. Each `{{ ... }}` expression gives one value. An expression
|
|
@@ -140,20 +146,159 @@ function rowsOfResult(result) {
|
|
|
140
146
|
async function runPostgresQuery(runner, { query, values }) {
|
|
141
147
|
return rowsOfResult(await runner.unsafe(query, values));
|
|
142
148
|
}
|
|
149
|
+
/** Put the escaped values at their places. The driver escapes each value. */
|
|
150
|
+
function fillPlaceholders(connection, query, values, placeholders) {
|
|
151
|
+
let sql = "";
|
|
152
|
+
let last = 0;
|
|
153
|
+
placeholders.forEach(({ at, length, identifier }, index) => {
|
|
154
|
+
const value = values[index];
|
|
155
|
+
sql += query.slice(last, at);
|
|
156
|
+
sql += identifier ? connection.escapeId(String(value)) : connection.escape(value);
|
|
157
|
+
last = at + length;
|
|
158
|
+
});
|
|
159
|
+
return sql + query.slice(last);
|
|
160
|
+
}
|
|
143
161
|
/** Run a parameterized query against MySQL. */
|
|
144
|
-
async function runMysqlQuery(connection, { query, values }) {
|
|
145
|
-
const [result] = await connection.query(query, values);
|
|
162
|
+
async function runMysqlQuery(connection, { query, values, placeholders }) {
|
|
163
|
+
const [result] = placeholders ? await connection.query(fillPlaceholders(connection, query, values, placeholders), []) : await connection.query(query, values);
|
|
146
164
|
if (Array.isArray(result)) return result;
|
|
147
165
|
if ((0, _zerodot_node_sdk.isRecord)(result)) return [{ ...result }];
|
|
148
166
|
return [{ success: true }];
|
|
149
167
|
}
|
|
150
|
-
/**
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
168
|
+
/**
|
|
169
|
+
* The parts of a query text that matter for expressions. At each position the first alternative
|
|
170
|
+
* that matches wins, so a `{{` or `?` inside a string, name or comment is part of that token.
|
|
171
|
+
* An unterminated string, name or comment runs to the end of the text.
|
|
172
|
+
*/
|
|
173
|
+
const POSTGRES_TOKEN = /(?<expression>\{\{[\s\S]*?\}\})|(?<quoted>(?<![\w$\u0080-\uffff])[eE]'(?:[^'\\]|''|\\(?:[\s\S]|$))*(?:'|$)|'(?:[^']|'')*(?:'|$)|"(?:[^"]|"")*(?:"|$))|(?<dollar>(?<![\w$\u0080-\uffff])\$(?:[A-Za-z_\u0080-\uffff][\w\u0080-\uffff]*)?\$)|(?<comment>--[^\n\r]*)|(?<block>\/\*)/g;
|
|
174
|
+
const MYSQL_TOKEN = /(?<expression>\{\{[\s\S]*?\}\})|(?<quoted>'(?:[^'\\]|''|\\(?:[\s\S]|$))*(?:'|$)|"(?:[^"\\]|""|\\(?:[\s\S]|$))*(?:"|$)|`(?:[^`]|``)*(?:`|$))|(?<comment>#[^\n]*|--(?=\s|$)[^\n]*|\/\*(?![!+])[\s\S]*?(?:\*\/|$))|(?<mark>\?+)/g;
|
|
175
|
+
/** The end of a Postgres block comment. These comments can be nested. */
|
|
176
|
+
function blockCommentEnd(query, from) {
|
|
177
|
+
const edge = /\/\*|\*\//g;
|
|
178
|
+
edge.lastIndex = from;
|
|
179
|
+
let depth = 1;
|
|
180
|
+
while (depth > 0) {
|
|
181
|
+
const match = edge.exec(query);
|
|
182
|
+
if (!match) return query.length;
|
|
183
|
+
depth += match[0] === "/*" ? 1 : -1;
|
|
184
|
+
}
|
|
185
|
+
return edge.lastIndex;
|
|
186
|
+
}
|
|
187
|
+
function queryTokens(query, driver) {
|
|
188
|
+
const pattern = new RegExp(driver === "postgres" ? POSTGRES_TOKEN : MYSQL_TOKEN);
|
|
189
|
+
const tokens = [];
|
|
190
|
+
for (let match = pattern.exec(query); match; match = pattern.exec(query)) {
|
|
191
|
+
const groups = match.groups ?? {};
|
|
192
|
+
const at = match.index;
|
|
193
|
+
let end = pattern.lastIndex;
|
|
194
|
+
let kind = "comment";
|
|
195
|
+
if (groups.expression) kind = "expression";
|
|
196
|
+
else if (groups.quoted) kind = "quoted";
|
|
197
|
+
else if (groups.mark) kind = "mark";
|
|
198
|
+
else if (groups.dollar) {
|
|
199
|
+
kind = "quoted";
|
|
200
|
+
const close = query.indexOf(groups.dollar, end);
|
|
201
|
+
end = close === -1 ? query.length : close + groups.dollar.length;
|
|
202
|
+
} else if (groups.block) end = blockCommentEnd(query, end);
|
|
203
|
+
pattern.lastIndex = end;
|
|
204
|
+
tokens.push({
|
|
205
|
+
kind,
|
|
206
|
+
at,
|
|
207
|
+
text: query.slice(at, end)
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
return tokens;
|
|
211
|
+
}
|
|
212
|
+
/** The values of one expression in the query text. An array gives one value for each element. */
|
|
213
|
+
function expressionValues(evaluated) {
|
|
214
|
+
return Array.isArray(evaluated) ? evaluated.map((element) => toParam(element)) : [toParam(evaluated)];
|
|
215
|
+
}
|
|
216
|
+
/** The whole query is one expression, so the expression gives the SQL text. */
|
|
217
|
+
const WHOLE_EXPRESSION = /^\s*(\{\{(?:(?!\}\})[\s\S])*\}\})\s*;?\s*$/;
|
|
218
|
+
/**
|
|
219
|
+
* The query text as SQL, with the values. An expression in the query text is not written into the
|
|
220
|
+
* SQL. It becomes a placeholder, and its value is bound. An array gives one placeholder for each
|
|
221
|
+
* element. An empty array gives NULL. Postgres numbers the expression values after the Query
|
|
222
|
+
* Parameters, so `$1` in the text still means the first Query Parameter. MySQL `?` marks and
|
|
223
|
+
* expressions take values in order. An expression inside quotes or a name is refused, and one
|
|
224
|
+
* inside a comment is left as it is. When the whole query is one expression, its value is the SQL.
|
|
225
|
+
*
|
|
226
|
+
* For MySQL with expressions, `placeholders` says where each value goes. The driver's own search
|
|
227
|
+
* for `?` marks reads comments and double quotes differently, so it is not used then.
|
|
228
|
+
*/
|
|
229
|
+
function bindQuery(query, parameters, evaluate, driver) {
|
|
230
|
+
const whole = WHOLE_EXPRESSION.exec(query)?.[1];
|
|
231
|
+
if (whole) {
|
|
232
|
+
const rendered = evaluate(whole);
|
|
233
|
+
if (typeof rendered !== "string" || !rendered.trim()) throw new Error("The expression in Query did not give SQL text");
|
|
234
|
+
return {
|
|
235
|
+
query: rendered,
|
|
236
|
+
values: parameters
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
const numbered = driver === "postgres";
|
|
240
|
+
let sql = "";
|
|
241
|
+
let last = 0;
|
|
242
|
+
let next = 0;
|
|
243
|
+
let expressions = 0;
|
|
244
|
+
const inline = [];
|
|
245
|
+
const values = [];
|
|
246
|
+
const placeholders = [];
|
|
247
|
+
const mark = (value) => {
|
|
248
|
+
placeholders.push({
|
|
249
|
+
at: sql.length,
|
|
250
|
+
length: 1,
|
|
251
|
+
identifier: false
|
|
252
|
+
});
|
|
253
|
+
values.push(value);
|
|
254
|
+
sql += "?";
|
|
156
255
|
};
|
|
256
|
+
for (const token of queryTokens(query, driver)) {
|
|
257
|
+
sql += query.slice(last, token.at);
|
|
258
|
+
last = token.at + token.text.length;
|
|
259
|
+
if (token.kind === "expression") {
|
|
260
|
+
expressions += 1;
|
|
261
|
+
const bound = expressionValues(evaluate(token.text));
|
|
262
|
+
if (bound.length === 0) sql += "NULL";
|
|
263
|
+
for (const [index, value] of bound.entries()) {
|
|
264
|
+
if (index > 0) sql += ", ";
|
|
265
|
+
if (numbered) {
|
|
266
|
+
inline.push(value);
|
|
267
|
+
sql += `$${parameters.length + inline.length}`;
|
|
268
|
+
} else mark(value);
|
|
269
|
+
}
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
if (token.kind === "quoted" && /\{\{[\s\S]*?\}\}/.test(token.text)) throw new Error("An expression cannot be inside quotes or a name. Move it out and use a parameter instead");
|
|
273
|
+
if (token.kind === "mark" && token.text.length <= 2 && next < parameters.length) {
|
|
274
|
+
placeholders.push({
|
|
275
|
+
at: sql.length,
|
|
276
|
+
length: token.text.length,
|
|
277
|
+
identifier: token.text.length === 2
|
|
278
|
+
});
|
|
279
|
+
values.push(parameters[next++]);
|
|
280
|
+
}
|
|
281
|
+
sql += token.text;
|
|
282
|
+
}
|
|
283
|
+
sql += query.slice(last);
|
|
284
|
+
if (numbered) return {
|
|
285
|
+
query: sql,
|
|
286
|
+
values: [...parameters, ...inline]
|
|
287
|
+
};
|
|
288
|
+
const all = [...values, ...parameters.slice(next)];
|
|
289
|
+
return expressions > 0 ? {
|
|
290
|
+
query: sql,
|
|
291
|
+
values: all,
|
|
292
|
+
placeholders
|
|
293
|
+
} : {
|
|
294
|
+
query: sql,
|
|
295
|
+
values: all
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
/** Build one query for an item scope. */
|
|
299
|
+
function buildQuery(query, queryParameters, scope, driver) {
|
|
300
|
+
const evaluate = (expression) => (0, _zerodot_node_sdk.resolveTemplate)(expression, scope);
|
|
301
|
+
return bindQuery(query, queryParameterValues(queryParameters, evaluate), evaluate, driver);
|
|
157
302
|
}
|
|
158
303
|
// src/credential.ts
|
|
159
304
|
const sqlCredential = {
|
|
@@ -348,17 +493,18 @@ const nodes = [(0, _zerodot_node_sdk.defineNode)({
|
|
|
348
493
|
data: []
|
|
349
494
|
};
|
|
350
495
|
if (!cfg.query.trim()) throw new Error("Write a query");
|
|
496
|
+
const driver = sqlDriver(credential);
|
|
351
497
|
const queries = items.map((item, index) => buildQuery(cfg.query, cfg.queryParameters, {
|
|
352
498
|
...scope,
|
|
353
499
|
$item: item,
|
|
354
500
|
$json: item,
|
|
355
501
|
$index: index
|
|
356
|
-
}));
|
|
502
|
+
}, driver));
|
|
357
503
|
const timeoutSignal = AbortSignal.timeout(cfg.timeoutMs);
|
|
358
504
|
const combined = AbortSignal.any([signal, timeoutSignal]);
|
|
359
505
|
return {
|
|
360
506
|
port: "out",
|
|
361
|
-
data:
|
|
507
|
+
data: driver === "postgres" ? await executePostgres(cfg, queries, credential, combined) : await executeMysql(cfg, queries, credential, combined)
|
|
362
508
|
};
|
|
363
509
|
}
|
|
364
510
|
})];
|
package/package.json
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zerodot/sql",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Run parameterized SQL queries against Postgres or MySQL databases from a single generic SQL node.",
|
|
5
5
|
"license": "AGPL-3.0-only",
|
|
6
|
+
"homepage": "https://github.com/zerodot-io/nodes/tree/main/packages/sql",
|
|
6
7
|
"repository": {
|
|
7
8
|
"type": "git",
|
|
8
9
|
"url": "git+https://github.com/zerodot-io/nodes.git",
|