@aaqu/fromcubes-db 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.
Files changed (54) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +24 -0
  3. package/README.md +442 -2
  4. package/SECURITY.md +75 -0
  5. package/THIRD-PARTY-NOTICES.md +151 -0
  6. package/examples/Quick Start/All Databases.json +1719 -0
  7. package/examples/Quick Start/ClickHouse.json +278 -0
  8. package/examples/Quick Start/CockroachDB.json +280 -0
  9. package/examples/Quick Start/Firebird.json +278 -0
  10. package/examples/Quick Start/MariaDB.json +281 -0
  11. package/examples/Quick Start/MySQL.json +281 -0
  12. package/examples/Quick Start/Oracle.json +280 -0
  13. package/examples/Quick Start/PostgreSQL.json +280 -0
  14. package/examples/Quick Start/SQL Server.json +282 -0
  15. package/examples/Quick Start/SQLite.json +278 -0
  16. package/examples/Quick Start/TiDB.json +281 -0
  17. package/examples/Quick Start/YugabyteDB.json +280 -0
  18. package/examples/SQLite Sensor Log With Portal.json +391 -0
  19. package/examples/Select With Parameters.json +130 -0
  20. package/index.js +32 -0
  21. package/lib/adapters/clickhouse.js +254 -0
  22. package/lib/adapters/firebird.js +416 -0
  23. package/lib/adapters/index.js +37 -0
  24. package/lib/adapters/mssql.js +178 -0
  25. package/lib/adapters/mysql.js +171 -0
  26. package/lib/adapters/oracle.js +272 -0
  27. package/lib/adapters/postgres.js +161 -0
  28. package/lib/adapters/read.js +57 -0
  29. package/lib/adapters/sqlite.js +193 -0
  30. package/lib/adapters/time.js +89 -0
  31. package/lib/bound.js +29 -0
  32. package/lib/editor-api.js +134 -0
  33. package/lib/editor-preview.js +191 -0
  34. package/lib/errors.js +66 -0
  35. package/lib/params.js +966 -0
  36. package/lib/pool.js +391 -0
  37. package/lib/settings.js +302 -0
  38. package/lib/sql/compile.js +160 -0
  39. package/lib/sql/dialect.js +194 -0
  40. package/lib/sql/parse.js +202 -0
  41. package/lib/sql/types.js +1071 -0
  42. package/lib/sqlite-files.js +137 -0
  43. package/nodes/connection.html +728 -0
  44. package/nodes/connection.js +179 -0
  45. package/nodes/editor/ark-pixel.LICENSE.txt +96 -0
  46. package/nodes/editor/ark-pixel.woff2 +0 -0
  47. package/nodes/editor/mark.svg +5 -0
  48. package/nodes/editor/sql-editor.css +604 -0
  49. package/nodes/editor/sql-editor.js +1490 -0
  50. package/nodes/editor/sql-model.js +203 -0
  51. package/nodes/icons/fromcubes-db.svg +24 -0
  52. package/nodes/query.html +662 -0
  53. package/nodes/query.js +195 -0
  54. package/package.json +81 -4
@@ -0,0 +1,130 @@
1
+ [
2
+ {
3
+ "id": "fc_demo_tab",
4
+ "type": "tab",
5
+ "label": "fromcubes-db demo",
6
+ "disabled": false,
7
+ "info": "Reads a user by id, then inserts an audit row. Both statements bind every value as a parameter.\n\nEdit the `demo db` connection with your own host and credentials before deploying."
8
+ },
9
+ {
10
+ "id": "fc_demo_inject",
11
+ "type": "inject",
12
+ "z": "fc_demo_tab",
13
+ "name": "userId = 1",
14
+ "props": [
15
+ {
16
+ "p": "payload"
17
+ }
18
+ ],
19
+ "repeat": "",
20
+ "once": false,
21
+ "topic": "",
22
+ "payload": "{\"userId\":1}",
23
+ "payloadType": "json",
24
+ "x": 150,
25
+ "y": 100,
26
+ "wires": [["fc_demo_select"]]
27
+ },
28
+ {
29
+ "id": "fc_demo_select",
30
+ "type": "fromcubes-db-query",
31
+ "z": "fc_demo_tab",
32
+ "name": "find user",
33
+ "connection": "fc_demo_conn",
34
+ "sql": "SELECT id, name, email\nFROM users\nWHERE id = :id",
35
+ "params": [
36
+ {
37
+ "name": "id",
38
+ "type": "msg",
39
+ "value": "payload.userId",
40
+ "as": "integer"
41
+ }
42
+ ],
43
+ "output": "single",
44
+ "target": "payload",
45
+ "timeoutMs": "",
46
+ "x": 340,
47
+ "y": 100,
48
+ "wires": [["fc_demo_audit"]]
49
+ },
50
+ {
51
+ "id": "fc_demo_audit",
52
+ "type": "fromcubes-db-query",
53
+ "z": "fc_demo_tab",
54
+ "name": "write audit row",
55
+ "connection": "fc_demo_conn",
56
+ "sql": "INSERT INTO audit_log (subject, action)\nVALUES (:subject, :action)",
57
+ "params": [
58
+ {
59
+ "name": "subject",
60
+ "type": "msg",
61
+ "value": "payload.name",
62
+ "as": "string"
63
+ },
64
+ {
65
+ "name": "action",
66
+ "type": "str",
67
+ "value": "read",
68
+ "as": "string"
69
+ }
70
+ ],
71
+ "output": "count",
72
+ "target": "audited",
73
+ "timeoutMs": "",
74
+ "x": 550,
75
+ "y": 100,
76
+ "wires": [["fc_demo_debug"]]
77
+ },
78
+ {
79
+ "id": "fc_demo_debug",
80
+ "type": "debug",
81
+ "z": "fc_demo_tab",
82
+ "name": "result",
83
+ "active": true,
84
+ "complete": "true",
85
+ "targetType": "full",
86
+ "x": 760,
87
+ "y": 100,
88
+ "wires": []
89
+ },
90
+ {
91
+ "id": "fc_demo_catch",
92
+ "type": "catch",
93
+ "z": "fc_demo_tab",
94
+ "name": "database errors",
95
+ "scope": ["fc_demo_select", "fc_demo_audit"],
96
+ "uncaught": false,
97
+ "x": 350,
98
+ "y": 180,
99
+ "wires": [["fc_demo_error_debug"]]
100
+ },
101
+ {
102
+ "id": "fc_demo_error_debug",
103
+ "type": "debug",
104
+ "z": "fc_demo_tab",
105
+ "name": "error",
106
+ "active": true,
107
+ "complete": "error",
108
+ "targetType": "msg",
109
+ "x": 560,
110
+ "y": 180,
111
+ "wires": []
112
+ },
113
+ {
114
+ "id": "fc_demo_conn",
115
+ "type": "fromcubes-db-connection",
116
+ "name": "demo db",
117
+ "dialect": "postgres",
118
+ "host": "localhost",
119
+ "port": 5432,
120
+ "database": "demo",
121
+ "options": "",
122
+ "poolMin": 0,
123
+ "poolMax": 10,
124
+ "idleTimeoutMs": 30000,
125
+ "connectTimeoutMs": 15000,
126
+ "queryTimeoutMs": 30000,
127
+ "queueMax": 100,
128
+ "undefinedAsNull": false
129
+ }
130
+ ]
package/index.js ADDED
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Public entry point. The Node-RED nodes are thin wrappers over this, so the
5
+ * same safe query path is available from a function node or plain Node.js:
6
+ *
7
+ * const { ManagedPool } = require('@aaqu/fromcubes-db');
8
+ * const pool = new ManagedPool({ dialect: 'postgres', host: 'localhost', ... });
9
+ * const { rows } = await pool.query('SELECT * FROM t WHERE id = :id', { id: 5 });
10
+ * await pool.close();
11
+ */
12
+
13
+ const { ManagedPool, STATES, DEFAULTS } = require("./lib/pool");
14
+ const { compile, unusedValueKeys } = require("./lib/sql/compile");
15
+ const { parseSql } = require("./lib/sql/parse");
16
+ const { DIALECTS, isDialect } = require("./lib/sql/dialect");
17
+ const { coerceParam, PARAM_TYPES } = require("./lib/params");
18
+ const errors = require("./lib/errors");
19
+
20
+ module.exports = {
21
+ ManagedPool,
22
+ STATES,
23
+ DEFAULTS,
24
+ DIALECTS,
25
+ isDialect,
26
+ parseSql,
27
+ compile,
28
+ unusedValueKeys,
29
+ coerceParam,
30
+ PARAM_TYPES,
31
+ ...errors,
32
+ };
@@ -0,0 +1,254 @@
1
+ "use strict";
2
+
3
+ const {
4
+ ConnectionError,
5
+ QueryError,
6
+ TimeoutError,
7
+ NotNullViolationError,
8
+ CheckViolationError,
9
+ ParameterError,
10
+ } = require("../errors");
11
+
12
+ const { Bound } = require("../bound");
13
+ const { utcWallClock } = require("./time");
14
+ const { exactNumber } = require("./read");
15
+
16
+ const DIALECT = "clickhouse";
17
+
18
+ // ClickHouse error codes (`err.code`, a numeric string), from
19
+ // https://github.com/ClickHouse/ClickHouse/blob/master/src/Common/ErrorCodes.cpp
20
+ const ERROR_CODES = {
21
+ 469: CheckViolationError, // VIOLATED_CONSTRAINT — a table CONSTRAINT … CHECK
22
+ 159: TimeoutError, // TIMEOUT_EXCEEDED — max_execution_time
23
+ };
24
+ const CONNECTION_ERROR_CODES = new Set([
25
+ "516", // AUTHENTICATION_FAILED
26
+ "192", // UNKNOWN_USER
27
+ "194", // REQUIRED_PASSWORD
28
+ "81", // UNKNOWN_DATABASE
29
+ "210", // NETWORK_ERROR
30
+ "209", // SOCKET_TIMEOUT
31
+ "497", // ACCESS_DENIED
32
+ ]);
33
+ const CONNECTION_CODES = new Set(["ECONNREFUSED", "ENOTFOUND", "ETIMEDOUT", "EHOSTUNREACH", "ECONNRESET", "EPIPE"]);
34
+
35
+ /**
36
+ * Settings every session runs with. Each one closes a gap where the server's
37
+ * default would hand a flow something other than what was sent or stored:
38
+ *
39
+ * - session_timezone UTC: a DateTime column without a zone, and naive text,
40
+ * mean UTC wall clock — as on every other product.
41
+ * - input_format_null_as_default 0: NULL into a column that is not Nullable is
42
+ * refused; the default silently stores 0 or '' instead (measured).
43
+ * - output_format_json_quote_*: 64-bit and wider integers, decimals and
44
+ * nan/inf arrive as text, not as JSON numbers a double would round.
45
+ * - date_time_output_format iso: DateTime as `…Z` in UTC whatever the column's
46
+ * own zone, so it is one instant, not a wall clock in some zone.
47
+ * - async_insert 0: an INSERT is written when the node reports it, and its
48
+ * error is the statement's, not a batch's.
49
+ * - mutations_sync 1: ALTER … UPDATE/DELETE has finished when it returns.
50
+ */
51
+ const SESSION_SETTINGS = {
52
+ session_timezone: "UTC",
53
+ input_format_null_as_default: 0,
54
+ output_format_json_quote_64bit_integers: 1,
55
+ output_format_json_quote_decimals: 1,
56
+ output_format_json_quote_denormals: 1,
57
+ date_time_output_format: "iso",
58
+ // Text into DateTime read as ISO 8601 — `T`, fractions, `Z`, offsets —
59
+ // on every version; the basic format of older servers refuses `.000` (26.3).
60
+ date_time_input_format: "best_effort",
61
+ // Decimal(12,2) 1.10 as "1.10", not "1.1": the scale the column has.
62
+ output_format_decimal_trailing_zeros: 1,
63
+ async_insert: 0,
64
+ mutations_sync: "1",
65
+ };
66
+
67
+ // Statements that answer with rows — decided from the SQL text, never a value.
68
+ const RETURNS_ROWS = /^(?:\(|WITH|SELECT|SHOW|DESC|DESCRIBE|EXISTS|EXPLAIN|VALUES)\b/i;
69
+ const INSERTS = /^INSERT\b/i;
70
+
71
+ /** The statement with leading comments and whitespace removed, for the two checks above. */
72
+ function head(text) {
73
+ let s = text;
74
+ for (;;) {
75
+ const t = s.replace(/^\s+/, "");
76
+ if (t.startsWith("--") || t.startsWith("#")) {
77
+ const nl = t.indexOf("\n");
78
+ s = nl === -1 ? "" : t.slice(nl + 1);
79
+ } else if (t.startsWith("/*")) {
80
+ const end = t.indexOf("*/");
81
+ s = end === -1 ? "" : t.slice(end + 2);
82
+ } else return t;
83
+ }
84
+ }
85
+
86
+ /** A ClickHouse literal for a value inside an array, tuple or map. */
87
+ function literal(value) {
88
+ if (value === null || value === undefined) return "NULL";
89
+ if (typeof value === "number") {
90
+ if (Number.isNaN(value)) return "nan";
91
+ if (value === Infinity) return "inf";
92
+ if (value === -Infinity) return "-inf";
93
+ return String(value);
94
+ }
95
+ if (typeof value === "bigint") return String(value);
96
+ if (typeof value === "boolean") return value ? "true" : "false";
97
+ if (Array.isArray(value)) return `[${value.map(literal).join(",")}]`;
98
+ if (typeof value === "object" && !(value instanceof Date) && !Buffer.isBuffer(value)) {
99
+ return `{${Object.entries(value)
100
+ .map(([k, v]) => `${literal(k)}:${literal(v)}`)
101
+ .join(",")}}`;
102
+ }
103
+ const text = scalarText(value);
104
+ return `'${text.replace(/[\\'\n\r\t\0]/g, (c) => ({ "\\": "\\\\", "'": "\\'", "\n": "\\n", "\r": "\\r", "\t": "\\t", "\0": "\\0" })[c])}'`;
105
+ }
106
+
107
+ /** Text for one scalar. A parameter is always `Nullable(String)`; the server converts. */
108
+ function scalarText(value) {
109
+ if (value instanceof Date) return utcWallClock(value);
110
+ if (Buffer.isBuffer(value)) {
111
+ // Parameters travel in the URL as UTF-8: bytes that are not UTF-8 cannot
112
+ // arrive as they were. Refused rather than replaced with U+FFFD.
113
+ const text = value.toString("utf8");
114
+ if (!Buffer.from(text, "utf8").equals(value)) {
115
+ throw new ParameterError(
116
+ "ClickHouse takes parameters as UTF-8 text, and these bytes are not UTF-8 — send them as hex and write unhex(:name) in the SQL",
117
+ { dialect: DIALECT },
118
+ );
119
+ }
120
+ return text;
121
+ }
122
+ if (typeof value === "boolean") return value ? "1" : "0";
123
+ if (typeof value === "number") return literal(value);
124
+ return String(value);
125
+ }
126
+
127
+ /**
128
+ * What goes into query_params. Every placeholder is `{pN:Nullable(String)}`
129
+ * (lib/sql/compile.js) — fixed text that depends on the SQL alone — so every
130
+ * value is text here, and ClickHouse converts it to the column's type. A
131
+ * Tuple takes `(…)`, everything else composite its literal.
132
+ */
133
+ function toClickHouse(value) {
134
+ if (value === null || value === undefined) return null;
135
+ if (value instanceof Bound) {
136
+ const v = value.value;
137
+ if (v === null || v === undefined) return null;
138
+ if (value.spec.category === "json" && typeof v !== "string") return JSON.stringify(v);
139
+ if (value.spec.tuple && Array.isArray(v)) return `(${v.map(literal).join(",")})`;
140
+ return toClickHouse(v);
141
+ }
142
+ if (Array.isArray(value) || (typeof value === "object" && !(value instanceof Date) && !Buffer.isBuffer(value))) {
143
+ return literal(value);
144
+ }
145
+ return scalarText(value);
146
+ }
147
+
148
+ async function createPool(config) {
149
+ const { createClient, ClickHouseLogLevel } = require("@clickhouse/client");
150
+ const options = { ...(config.options || {}) };
151
+ const userSettings = options.clickhouse_settings || {};
152
+ delete options.clickhouse_settings;
153
+
154
+ const settings = { ...SESSION_SETTINGS };
155
+ // The connection's query timeout is a ceiling, as on PostgreSQL and Oracle.
156
+ if (config.queryTimeoutMs > 0) settings.max_execution_time = Math.ceil(config.queryTimeoutMs / 1000);
157
+
158
+ const client = createClient({
159
+ url: config.url || `${config.tls ? "https" : "http"}://${config.host}:${config.port}`,
160
+ username: config.user || "default",
161
+ password: config.password || "",
162
+ database: config.database || "default",
163
+ max_open_connections: config.poolMax || 10,
164
+ request_timeout: Math.max(config.queryTimeoutMs || 0, 30000) + 5000,
165
+ // The client logs every failed request itself; the node reports them.
166
+ log: { level: ClickHouseLogLevel.OFF },
167
+ ...options,
168
+ clickhouse_settings: { ...settings, ...userSettings },
169
+ });
170
+
171
+ // ping() resolves {success:false} on a wrong password; a query does not.
172
+ try {
173
+ await (await client.query({ query: "SELECT 1", format: "JSON" })).json();
174
+ } catch (err) {
175
+ await client.close().catch(() => {});
176
+ throw err;
177
+ }
178
+ return client;
179
+ }
180
+
181
+ /** The type a column holds, without the wrappers that do not change its values. */
182
+ function baseType(type) {
183
+ let t = String(type);
184
+ for (;;) {
185
+ const m = /^(?:Nullable|LowCardinality)\((.*)\)$/.exec(t);
186
+ if (!m) return t;
187
+ t = m[1];
188
+ }
189
+ }
190
+
191
+ const WIDE_INTEGER = /^U?Int(?:64|128|256)$/;
192
+ const FLOAT_TEXT = { nan: NaN, "-nan": NaN, inf: Infinity, "+inf": Infinity, "-inf": -Infinity };
193
+
194
+ /** One value as the other adapters would hand it over (see lib/adapters/read.js). */
195
+ function fromClickHouse(value, type) {
196
+ if (value === null || value === undefined) return value;
197
+ const t = baseType(type);
198
+ if (WIDE_INTEGER.test(t) && typeof value === "string") return exactNumber(value);
199
+ if (/^(?:Float32|Float64|BFloat16)$/.test(t) && typeof value === "string" && value in FLOAT_TEXT) {
200
+ return FLOAT_TEXT[value];
201
+ }
202
+ if ((t === "Date" || t === "Date32") && typeof value === "string") return new Date(`${value}T00:00:00.000Z`);
203
+ if (/^DateTime(?:32)?(?:\(|$)/.test(t) && typeof value === "string") return new Date(value);
204
+ const p64 = /^DateTime64\((\d+)/.exec(t);
205
+ // Past milliseconds a Date would cut the value: it stays text, ISO in UTC.
206
+ if (p64 && typeof value === "string") return Number(p64[1]) <= 3 ? new Date(value) : value;
207
+ return value;
208
+ }
209
+
210
+ async function execute(client, compiled) {
211
+ const params = {};
212
+ for (const [key, value] of Object.entries(compiled.values)) params[key] = toClickHouse(value);
213
+ const statement = head(compiled.text);
214
+
215
+ if (RETURNS_ROWS.test(statement)) {
216
+ const result = await client.query({ query: compiled.text, query_params: params, format: "JSON" });
217
+ const { meta = [], data = [] } = await result.json();
218
+ const types = Object.fromEntries(meta.map((m) => [m.name, m.type]));
219
+ const rows = data.map((row) => {
220
+ const out = {};
221
+ for (const [key, value] of Object.entries(row)) out[key] = fromClickHouse(value, types[key]);
222
+ return out;
223
+ });
224
+ return { rows, rowCount: rows.length };
225
+ }
226
+
227
+ const result = await client.command({ query: compiled.text, query_params: params });
228
+ // Only an INSERT counts what it wrote. ALTER … UPDATE/DELETE and the
229
+ // lightweight UPDATE/DELETE report 0 whatever they changed (measured), so
230
+ // they report no count at all rather than a plausible wrong one.
231
+ const written = result && result.summary ? Number(result.summary.written_rows) : NaN;
232
+ return { rows: [], rowCount: INSERTS.test(statement) && Number.isFinite(written) ? written : null };
233
+ }
234
+
235
+ async function closePool(client) {
236
+ await client.close();
237
+ }
238
+
239
+ function translateError(err) {
240
+ if (!err || typeof err !== "object") return new QueryError(String(err), { dialect: DIALECT });
241
+ if (err instanceof ParameterError) return err;
242
+ const code = err.code === undefined ? undefined : String(err.code);
243
+ const options = { dialect: DIALECT, driverCode: code, cause: err };
244
+ // TYPE_MISMATCH covers more than NULLs; only this message is the NOT NULL case.
245
+ if (code === "53" && /Cannot insert NULL value/.test(err.message)) {
246
+ return new NotNullViolationError(err.message, options);
247
+ }
248
+ const Specific = ERROR_CODES[code];
249
+ if (Specific) return new Specific(err.message, options);
250
+ if (CONNECTION_ERROR_CODES.has(code) || CONNECTION_CODES.has(code)) return new ConnectionError(err.message, options);
251
+ return new QueryError(err.message, options);
252
+ }
253
+
254
+ module.exports = { dialect: DIALECT, createPool, execute, closePool, translateError, toClickHouse, fromClickHouse };