@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.
- package/LICENSE +201 -0
- package/NOTICE +24 -0
- package/README.md +442 -2
- package/SECURITY.md +75 -0
- package/THIRD-PARTY-NOTICES.md +151 -0
- package/examples/Quick Start/All Databases.json +1719 -0
- package/examples/Quick Start/ClickHouse.json +278 -0
- package/examples/Quick Start/CockroachDB.json +280 -0
- package/examples/Quick Start/Firebird.json +278 -0
- package/examples/Quick Start/MariaDB.json +281 -0
- package/examples/Quick Start/MySQL.json +281 -0
- package/examples/Quick Start/Oracle.json +280 -0
- package/examples/Quick Start/PostgreSQL.json +280 -0
- package/examples/Quick Start/SQL Server.json +282 -0
- package/examples/Quick Start/SQLite.json +278 -0
- package/examples/Quick Start/TiDB.json +281 -0
- package/examples/Quick Start/YugabyteDB.json +280 -0
- package/examples/SQLite Sensor Log With Portal.json +391 -0
- package/examples/Select With Parameters.json +130 -0
- package/index.js +32 -0
- package/lib/adapters/clickhouse.js +254 -0
- package/lib/adapters/firebird.js +416 -0
- package/lib/adapters/index.js +37 -0
- package/lib/adapters/mssql.js +178 -0
- package/lib/adapters/mysql.js +171 -0
- package/lib/adapters/oracle.js +272 -0
- package/lib/adapters/postgres.js +161 -0
- package/lib/adapters/read.js +57 -0
- package/lib/adapters/sqlite.js +193 -0
- package/lib/adapters/time.js +89 -0
- package/lib/bound.js +29 -0
- package/lib/editor-api.js +134 -0
- package/lib/editor-preview.js +191 -0
- package/lib/errors.js +66 -0
- package/lib/params.js +966 -0
- package/lib/pool.js +391 -0
- package/lib/settings.js +302 -0
- package/lib/sql/compile.js +160 -0
- package/lib/sql/dialect.js +194 -0
- package/lib/sql/parse.js +202 -0
- package/lib/sql/types.js +1071 -0
- package/lib/sqlite-files.js +137 -0
- package/nodes/connection.html +728 -0
- package/nodes/connection.js +179 -0
- package/nodes/editor/ark-pixel.LICENSE.txt +96 -0
- package/nodes/editor/ark-pixel.woff2 +0 -0
- package/nodes/editor/mark.svg +5 -0
- package/nodes/editor/sql-editor.css +604 -0
- package/nodes/editor/sql-editor.js +1490 -0
- package/nodes/editor/sql-model.js +203 -0
- package/nodes/icons/fromcubes-db.svg +24 -0
- package/nodes/query.html +662 -0
- package/nodes/query.js +195 -0
- package/package.json +81 -4
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const {
|
|
4
|
+
ConnectionError,
|
|
5
|
+
QueryError,
|
|
6
|
+
TimeoutError,
|
|
7
|
+
UniqueViolationError,
|
|
8
|
+
ForeignKeyViolationError,
|
|
9
|
+
NotNullViolationError,
|
|
10
|
+
CheckViolationError,
|
|
11
|
+
} = require("../errors");
|
|
12
|
+
|
|
13
|
+
const { Bound } = require("../bound");
|
|
14
|
+
const { prepareDatabase } = require("../sqlite-files");
|
|
15
|
+
const { exactNumber } = require("./read");
|
|
16
|
+
|
|
17
|
+
const DIALECT = "sqlite";
|
|
18
|
+
|
|
19
|
+
// Built on node:sqlite, part of Node itself since 22.5. That keeps the package
|
|
20
|
+
// free of a native build step, which is what makes it installable through the
|
|
21
|
+
// Node-RED palette manager on a Raspberry Pi.
|
|
22
|
+
const MIN_NODE = "22.5.0";
|
|
23
|
+
|
|
24
|
+
// node:sqlite always reports code "ERR_SQLITE_ERROR"; the extended result code
|
|
25
|
+
// in `errcode` is what tells the failures apart.
|
|
26
|
+
// https://www.sqlite.org/rescode.html
|
|
27
|
+
const RESULT_CODES = {
|
|
28
|
+
2067: UniqueViolationError, // SQLITE_CONSTRAINT_UNIQUE
|
|
29
|
+
1555: UniqueViolationError, // SQLITE_CONSTRAINT_PRIMARYKEY
|
|
30
|
+
787: ForeignKeyViolationError, // SQLITE_CONSTRAINT_FOREIGNKEY
|
|
31
|
+
1299: NotNullViolationError, // SQLITE_CONSTRAINT_NOTNULL
|
|
32
|
+
275: CheckViolationError, // SQLITE_CONSTRAINT_CHECK
|
|
33
|
+
5: TimeoutError, // SQLITE_BUSY
|
|
34
|
+
773: TimeoutError, // SQLITE_BUSY_TIMEOUT
|
|
35
|
+
6: TimeoutError, // SQLITE_LOCKED
|
|
36
|
+
14: ConnectionError, // SQLITE_CANTOPEN
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** Statements that hand back rows. Anything else reports a row count instead. */
|
|
40
|
+
const RETURNS_ROWS = /^\s*(?:WITH\b[\s\S]*?\b(?:SELECT|VALUES)|SELECT|VALUES|PRAGMA|EXPLAIN)\b/i;
|
|
41
|
+
const HAS_RETURNING = /\bRETURNING\b/i;
|
|
42
|
+
const INSERTS = /^\s*(?:INSERT|REPLACE)\b/i;
|
|
43
|
+
|
|
44
|
+
function requireSqlite() {
|
|
45
|
+
try {
|
|
46
|
+
return require("node:sqlite");
|
|
47
|
+
} catch (err) {
|
|
48
|
+
throw new ConnectionError(`SQLite needs Node ${MIN_NODE} or newer (running ${process.version})`, {
|
|
49
|
+
dialect: DIALECT,
|
|
50
|
+
cause: err,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function createPool(config) {
|
|
56
|
+
const { DatabaseSync } = requireSqlite();
|
|
57
|
+
|
|
58
|
+
const file = config.file || config.database;
|
|
59
|
+
if (!file) {
|
|
60
|
+
throw new ConnectionError("SQLite needs a database file (or :memory:)", { dialect: DIALECT });
|
|
61
|
+
}
|
|
62
|
+
// From a connection node: create <userDir>/fromcubes-db if it is missing,
|
|
63
|
+
// and refuse a database that has been replaced by a link.
|
|
64
|
+
if (config.directory) prepareDatabase({ file, directory: config.directory });
|
|
65
|
+
|
|
66
|
+
const db = new DatabaseSync(file, {
|
|
67
|
+
readOnly: config.readOnly === true,
|
|
68
|
+
...config.options,
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
// WAL lets readers work while a writer holds the file, which is what a flow
|
|
72
|
+
// with several query nodes actually does.
|
|
73
|
+
if (config.readOnly !== true && config.wal !== false) {
|
|
74
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
75
|
+
}
|
|
76
|
+
if (config.foreignKeys !== false) {
|
|
77
|
+
db.exec("PRAGMA foreign_keys = ON");
|
|
78
|
+
}
|
|
79
|
+
// Without this a second writer fails instantly with SQLITE_BUSY.
|
|
80
|
+
const busyMs = Number(config.busyTimeoutMs);
|
|
81
|
+
db.exec(`PRAGMA busy_timeout = ${Number.isFinite(busyMs) && busyMs >= 0 ? busyMs : 5000}`);
|
|
82
|
+
|
|
83
|
+
return db;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* node:sqlite binds null, numbers, bigints, strings and Uint8Arrays. Booleans
|
|
88
|
+
* and Dates are ordinary values in a flow, so they are mapped to what SQLite
|
|
89
|
+
* stores them as, rather than failing at the driver.
|
|
90
|
+
*/
|
|
91
|
+
function toSqliteValue(value) {
|
|
92
|
+
// A declared type changes nothing here: SQLite stores by affinity, and the
|
|
93
|
+
// forms below are the ones its own JSON and date functions read.
|
|
94
|
+
if (value instanceof Bound) return toSqliteValue(value.value);
|
|
95
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
96
|
+
if (value instanceof Date) return value.toISOString();
|
|
97
|
+
if (Buffer.isBuffer(value)) return new Uint8Array(value);
|
|
98
|
+
if (value !== null && typeof value === "object") return JSON.stringify(value);
|
|
99
|
+
return value;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Columns declared JSON: text in SQLite, an object on every other product. */
|
|
103
|
+
function jsonColumns(statement) {
|
|
104
|
+
const names = new Set();
|
|
105
|
+
for (const column of statement.columns()) {
|
|
106
|
+
if (column.type && /^json/i.test(column.type.trim())) names.add(column.name);
|
|
107
|
+
}
|
|
108
|
+
return names;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* A row the way the other products hand one over: an ordinary object (node:sqlite
|
|
113
|
+
* gives null-prototype ones, and row.hasOwnProperty() should not break), exact
|
|
114
|
+
* integers, Buffers rather than Uint8Arrays, and JSON columns parsed.
|
|
115
|
+
*/
|
|
116
|
+
function fromSqliteRow(row, json) {
|
|
117
|
+
const out = {};
|
|
118
|
+
for (const [key, value] of Object.entries(row)) {
|
|
119
|
+
let v = value;
|
|
120
|
+
if (typeof v === "bigint") v = exactNumber(v);
|
|
121
|
+
else if (v instanceof Uint8Array) v = Buffer.from(v.buffer, v.byteOffset, v.byteLength);
|
|
122
|
+
else if (typeof v === "string" && json.has(key)) {
|
|
123
|
+
try {
|
|
124
|
+
v = JSON.parse(v);
|
|
125
|
+
} catch {
|
|
126
|
+
// Not JSON after all: SQLite never checked. Hand on the text.
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
out[key] = v;
|
|
130
|
+
}
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function execute(db, compiled) {
|
|
135
|
+
const statement = db.prepare(compiled.text);
|
|
136
|
+
// An INTEGER past 2^53 otherwise throws and the whole row is unreadable.
|
|
137
|
+
statement.setReadBigInts(true);
|
|
138
|
+
const values = compiled.values.map(toSqliteValue);
|
|
139
|
+
|
|
140
|
+
// Whether a statement returns rows is a property of the SQL, never of the
|
|
141
|
+
// values, so reading it off the text keeps the guarantee intact.
|
|
142
|
+
const returnsRows = RETURNS_ROWS.test(compiled.text) || HAS_RETURNING.test(compiled.text);
|
|
143
|
+
|
|
144
|
+
if (returnsRows) {
|
|
145
|
+
// node:sqlite hands back null-prototype objects. Every other driver returns
|
|
146
|
+
// ordinary ones, and a function node calling row.hasOwnProperty() should not
|
|
147
|
+
// break just because the flow points at SQLite.
|
|
148
|
+
const json = jsonColumns(statement);
|
|
149
|
+
const rows = statement.all(...values).map((row) => fromSqliteRow(row, json));
|
|
150
|
+
return { rows, rowCount: rows.length };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const result = statement.run(...values);
|
|
154
|
+
return {
|
|
155
|
+
rows: [],
|
|
156
|
+
rowCount: Number(result.changes || 0),
|
|
157
|
+
// lastInsertRowid keeps whatever this connection inserted last, so after an
|
|
158
|
+
// UPDATE it is a stale id from an earlier statement. Only an INSERT gets to
|
|
159
|
+
// report one — a property of the SQL text, never of the values.
|
|
160
|
+
insertId: INSERTS.test(compiled.text) ? exactNumber(result.lastInsertRowid) : undefined,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function closePool(db) {
|
|
165
|
+
db.close();
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function translateError(err) {
|
|
169
|
+
if (!err || typeof err !== "object") {
|
|
170
|
+
return new QueryError(String(err), { dialect: DIALECT });
|
|
171
|
+
}
|
|
172
|
+
const options = { dialect: DIALECT, driverCode: err.errcode ?? err.code, cause: err };
|
|
173
|
+
const message = err.message || String(err);
|
|
174
|
+
|
|
175
|
+
const Specific = RESULT_CODES[err.errcode];
|
|
176
|
+
if (Specific) return new Specific(message, options);
|
|
177
|
+
|
|
178
|
+
// Fallback for paths that carry no result code, e.g. opening the file.
|
|
179
|
+
if (/unable to open database|no such file|not a database/i.test(message)) {
|
|
180
|
+
return new ConnectionError(message, options);
|
|
181
|
+
}
|
|
182
|
+
if (/UNIQUE constraint failed/i.test(message)) return new UniqueViolationError(message, options);
|
|
183
|
+
if (/NOT NULL constraint failed/i.test(message)) {
|
|
184
|
+
return new NotNullViolationError(message, options);
|
|
185
|
+
}
|
|
186
|
+
if (/FOREIGN KEY constraint failed/i.test(message)) {
|
|
187
|
+
return new ForeignKeyViolationError(message, options);
|
|
188
|
+
}
|
|
189
|
+
if (/CHECK constraint failed/i.test(message)) return new CheckViolationError(message, options);
|
|
190
|
+
return new QueryError(message, options);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
module.exports = { dialect: DIALECT, createPool, execute, closePool, translateError, toSqliteValue };
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Points in time on their way to a driver. Every adapter writes them in UTC:
|
|
5
|
+
* a JS Date is an instant, and a column without a time zone receives that
|
|
6
|
+
* instant's UTC wall clock — on every product, whatever zone Node-RED runs in.
|
|
7
|
+
* Letting each driver use the process's local zone shifted values by the
|
|
8
|
+
* server's offset and, west of UTC, moved a `date` to the day before.
|
|
9
|
+
*
|
|
10
|
+
* A value that `lib/params.js` kept as text (more digits than a Date holds, or
|
|
11
|
+
* an offset a Date would lose) is parsed here only far enough to rewrite it in
|
|
12
|
+
* UTC without dropping a digit.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const FRACTION = /\.(\d+)(?=\s*(?:Z|[+-]\d{2}(?::?\d{2})?)?\s*$)/i;
|
|
16
|
+
const OFFSET = /(?:Z|([+-])(\d{2}):?(\d{2})?)\s*$/i;
|
|
17
|
+
|
|
18
|
+
const { parseUtc } = require("../params");
|
|
19
|
+
|
|
20
|
+
const pad = (n, width = 2) => String(n).padStart(width, "0");
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The instant a value names, plus the fractional digits past the millisecond
|
|
24
|
+
* that a Date cannot carry ("4567" of ".1234567").
|
|
25
|
+
*
|
|
26
|
+
* @param {Date|string} value
|
|
27
|
+
* @returns {{ date: Date, extra: string }}
|
|
28
|
+
*/
|
|
29
|
+
function instant(value) {
|
|
30
|
+
if (value instanceof Date) return { date: value, extra: "" };
|
|
31
|
+
const text = String(value).trim();
|
|
32
|
+
const fraction = FRACTION.exec(text);
|
|
33
|
+
return { date: new Date(parseUtc(text)), extra: fraction && fraction[1].length > 3 ? fraction[1].slice(3) : "" };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Reads `YYYY-MM-DD[ T]HH:MM:SS[.f…]` with no zone as UTC, a signed year as astronomical. */
|
|
37
|
+
function fromUtcText(text, { bcSuffix = false } = {}) {
|
|
38
|
+
let t = String(text).trim();
|
|
39
|
+
if (/^-?infinity$/i.test(t)) return t.startsWith("-") ? -Infinity : Infinity;
|
|
40
|
+
let bc = false;
|
|
41
|
+
if (bcSuffix && / BC$/.test(t)) {
|
|
42
|
+
bc = true;
|
|
43
|
+
t = t.slice(0, -3);
|
|
44
|
+
}
|
|
45
|
+
const m = /^([+-]?)(\d{4,6})-(\d{2})-(\d{2})(?:[T\s](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?)?/.exec(t);
|
|
46
|
+
if (!m) return new Date(NaN);
|
|
47
|
+
const [, sign, y, mo, d, h = "0", mi = "0", s = "0", frac = ""] = m;
|
|
48
|
+
let year = Number(y) * (sign === "-" ? -1 : 1);
|
|
49
|
+
// "4713 BC" and Oracle's "-4713" both mean astronomical -4712: no year zero.
|
|
50
|
+
if (bc || sign === "-") year = bc ? 1 - Number(y) : year + 1;
|
|
51
|
+
const date = new Date(
|
|
52
|
+
Date.UTC(
|
|
53
|
+
2000,
|
|
54
|
+
Number(mo) - 1,
|
|
55
|
+
Number(d),
|
|
56
|
+
Number(h),
|
|
57
|
+
Number(mi),
|
|
58
|
+
Number(s),
|
|
59
|
+
Number(frac.padEnd(3, "0").slice(0, 3)),
|
|
60
|
+
),
|
|
61
|
+
);
|
|
62
|
+
date.setUTCFullYear(year);
|
|
63
|
+
return date;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Whether a text timestamp says which zone it is in. */
|
|
67
|
+
function hasOffset(value) {
|
|
68
|
+
return typeof value === "string" && /[T\s]\d{1,2}:\d{2}/.test(value) && OFFSET.test(value.trim());
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* `YYYY-MM-DD HH:MM:SS.fff[extra]` in UTC. `year` decides how a year outside
|
|
73
|
+
* 1..9999 is spelled, which is the one thing the products disagree on.
|
|
74
|
+
*
|
|
75
|
+
* @param {Date|string} value
|
|
76
|
+
* @param {{ separator?: string, year?: (y: number) => string }} [options]
|
|
77
|
+
*/
|
|
78
|
+
function utcWallClock(value, options = {}) {
|
|
79
|
+
const { date, extra } = instant(value);
|
|
80
|
+
const y = date.getUTCFullYear();
|
|
81
|
+
const year = options.year ? options.year(y) : pad(y, 4);
|
|
82
|
+
return (
|
|
83
|
+
`${year}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}` +
|
|
84
|
+
`${options.separator || " "}${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}` +
|
|
85
|
+
`.${pad(date.getUTCMilliseconds(), 3)}${extra}`
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
module.exports = { instant, hasOffset, utcWallClock, fromUtcText, pad };
|
package/lib/bound.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A parameter value together with the column type it was declared and checked
|
|
5
|
+
* as (`lib/params.js` → `bindParam`). Adapters read it to choose the driver's
|
|
6
|
+
* bind type; everything else treats it as opaque. It never reaches SQL text:
|
|
7
|
+
* compile() only places it in the values it hands to the driver.
|
|
8
|
+
*/
|
|
9
|
+
class Bound {
|
|
10
|
+
/**
|
|
11
|
+
* @param {unknown} value already checked and converted by coerceParam
|
|
12
|
+
* @param {string} type canonical type name in lib/sql/types.js
|
|
13
|
+
* @param {import('./sql/types').ColumnType} spec
|
|
14
|
+
* @param {object} declared parseTypeSpec() of what the user wrote
|
|
15
|
+
*/
|
|
16
|
+
constructor(value, type, spec, declared) {
|
|
17
|
+
this.value = value;
|
|
18
|
+
this.type = type;
|
|
19
|
+
this.spec = spec;
|
|
20
|
+
this.declared = declared;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The plain value behind a parameter, whether or not it was declared. */
|
|
25
|
+
function plain(value) {
|
|
26
|
+
return value instanceof Bound ? value.value : value;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
module.exports = { Bound, plain };
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const path = require("node:path");
|
|
4
|
+
const { preview } = require("./editor-preview");
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Admin routes behind the SQL Editor (nodes/editor/). Same arrangement as the
|
|
8
|
+
* React Editor in @aaqu/fromcubes-react, without depending on it:
|
|
9
|
+
*
|
|
10
|
+
* - Monaco from this package's own node_modules, and the editor's files, each
|
|
11
|
+
* served twice — plain and under this package's version
|
|
12
|
+
* (`fromcubes-db/0.1.0/vs/…`). The template loads the versioned path, so no
|
|
13
|
+
* cache between the browser and Node-RED can hand a new editor an old file,
|
|
14
|
+
* or a 404 it remembered. Path, not query string: some caches ignore those.
|
|
15
|
+
* - POST /fromcubes-db/sql/preview — placeholders, each parameter against a
|
|
16
|
+
* sample message, the compiled statement. Nothing is executed.
|
|
17
|
+
* - Capture: the editor arms one node, that node copies the next message it
|
|
18
|
+
* receives, the editor reads it. Unarmed, a node copies nothing.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const ASSET_VERSION = String(require("../package.json").version).replace(/[^0-9A-Za-z.+-]/g, "");
|
|
22
|
+
/** Relative to the admin root, as the editor needs it (no leading slash). */
|
|
23
|
+
const ASSET_BASE = `fromcubes-db/${ASSET_VERSION}/`;
|
|
24
|
+
|
|
25
|
+
/** A captured message bigger than this is refused, not cut: a cut one would mislead. */
|
|
26
|
+
const MAX_CAPTURE_BYTES = 256 * 1024;
|
|
27
|
+
/** An arming nobody answered expires, so a forgotten editor tab costs nothing. */
|
|
28
|
+
const CAPTURE_TTL_MS = 5 * 60 * 1000;
|
|
29
|
+
|
|
30
|
+
/** nodeId → expiry of the arming. */
|
|
31
|
+
const armed = new Map();
|
|
32
|
+
/** nodeId → { at, msg } | { at, error } */
|
|
33
|
+
const captured = new Map();
|
|
34
|
+
|
|
35
|
+
/** Called by a query node on every input; costs a Map lookup unless armed. */
|
|
36
|
+
function offerMessage(nodeId, msg, clone) {
|
|
37
|
+
const until = armed.get(nodeId);
|
|
38
|
+
if (until === undefined) return;
|
|
39
|
+
armed.delete(nodeId);
|
|
40
|
+
if (until < Date.now()) return;
|
|
41
|
+
try {
|
|
42
|
+
const copy = clone(msg);
|
|
43
|
+
// _msgid and the like are Node-RED's, not the user's input.
|
|
44
|
+
delete copy._msgid;
|
|
45
|
+
const json = JSON.stringify(copy);
|
|
46
|
+
if (json === undefined || Buffer.byteLength(json) > MAX_CAPTURE_BYTES) {
|
|
47
|
+
captured.set(nodeId, { at: Date.now(), error: `larger than ${MAX_CAPTURE_BYTES / 1024} KB` });
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
captured.set(nodeId, { at: Date.now(), msg: JSON.parse(json) });
|
|
51
|
+
} catch (err) {
|
|
52
|
+
captured.set(nodeId, { at: Date.now(), error: `cannot be copied: ${err.message}` });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** A node that is gone or redeployed drops what it held. */
|
|
57
|
+
function forgetNode(nodeId) {
|
|
58
|
+
armed.delete(nodeId);
|
|
59
|
+
captured.delete(nodeId);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const NODE_ID = /^[0-9A-Za-z._-]{1,64}$/;
|
|
63
|
+
|
|
64
|
+
function registerEditorApi(RED) {
|
|
65
|
+
const read = RED.auth.needsPermission("fromcubes-db-query.read");
|
|
66
|
+
const write = RED.auth.needsPermission("fromcubes-db-query.write");
|
|
67
|
+
|
|
68
|
+
/** Static files without express: sendFile's `root` refuses anything outside it. */
|
|
69
|
+
function serveStatic(name, dir) {
|
|
70
|
+
const handler = (req, res, next) => {
|
|
71
|
+
if (req.method !== "GET" && req.method !== "HEAD") return next();
|
|
72
|
+
const rel = decodeURIComponent(req.path || "").replace(/^\/+/, "");
|
|
73
|
+
if (rel === "" || rel.split("/").some((part) => part === ".." || part.startsWith("."))) {
|
|
74
|
+
res.status(404).end();
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
res.sendFile(rel, { root: dir, dotfiles: "deny", maxAge: 0 }, (err) => {
|
|
78
|
+
if (err && !res.headersSent) res.status(err.statusCode === 404 || err.code === "ENOENT" ? 404 : 500).end();
|
|
79
|
+
});
|
|
80
|
+
};
|
|
81
|
+
RED.httpAdmin.use(`/fromcubes-db/${name}`, read, handler);
|
|
82
|
+
RED.httpAdmin.use(`/${ASSET_BASE}${name}`, read, handler);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// monaco-editor's `exports` map hides package.json; its CommonJS entry is
|
|
86
|
+
// min/vs/index.js, beside loader.js and editor/editor.main.js (the AMD build).
|
|
87
|
+
serveStatic("vs", path.dirname(require.resolve("monaco-editor")));
|
|
88
|
+
serveStatic("editor", path.join(__dirname, "..", "nodes", "editor"));
|
|
89
|
+
// The node icon, for the status bar and the overlay's header — Node-RED's
|
|
90
|
+
// own /icons route is keyed by the package name, which the editor need not know.
|
|
91
|
+
serveStatic("icons", path.join(__dirname, "..", "nodes", "icons"));
|
|
92
|
+
|
|
93
|
+
RED.httpAdmin.post("/fromcubes-db/sql/preview", read, (req, res) => {
|
|
94
|
+
const body = req.body && typeof req.body === "object" ? req.body : {};
|
|
95
|
+
try {
|
|
96
|
+
res.json(preview(body));
|
|
97
|
+
} catch (err) {
|
|
98
|
+
RED.log.warn(`fromcubes-db: SQL Editor preview failed: ${err.message}`);
|
|
99
|
+
res.status(500).json({ error: "Preview failed" });
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
RED.httpAdmin.post("/fromcubes-db/sql/capture/:id", write, (req, res) => {
|
|
104
|
+
const id = req.params.id;
|
|
105
|
+
if (!NODE_ID.test(id) || !RED.nodes.getNode(id)) {
|
|
106
|
+
res.status(404).json({ error: "No deployed query node with that id" });
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
captured.delete(id);
|
|
110
|
+
armed.set(id, Date.now() + CAPTURE_TTL_MS);
|
|
111
|
+
res.json({ armed: true, expiresInMs: CAPTURE_TTL_MS });
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
RED.httpAdmin.delete("/fromcubes-db/sql/capture/:id", write, (req, res) => {
|
|
115
|
+
if (NODE_ID.test(req.params.id)) armed.delete(req.params.id);
|
|
116
|
+
res.status(204).end();
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
RED.httpAdmin.get("/fromcubes-db/sql/capture/:id", read, (req, res) => {
|
|
120
|
+
const id = req.params.id;
|
|
121
|
+
if (!NODE_ID.test(id)) {
|
|
122
|
+
res.status(404).end();
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
const got = captured.get(id);
|
|
126
|
+
if (got) {
|
|
127
|
+
res.json(got);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
res.json({ waiting: armed.has(id) && armed.get(id) > Date.now() });
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
module.exports = { registerEditorApi, offerMessage, forgetNode, ASSET_BASE, MAX_CAPTURE_BYTES };
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { parseSql } = require("./sql/parse");
|
|
4
|
+
const { compile } = require("./sql/compile");
|
|
5
|
+
const { isProduct } = require("./sql/dialect");
|
|
6
|
+
const { bindParam } = require("./params");
|
|
7
|
+
const { Bound } = require("./bound");
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* What the SQL Editor shows beside a query: where its placeholders are, what
|
|
11
|
+
* each parameter resolves to against a sample message, whether its declared
|
|
12
|
+
* type accepts that, and the statement the database would receive.
|
|
13
|
+
*
|
|
14
|
+
* Every answer comes from the functions a deployed node runs — parseSql,
|
|
15
|
+
* bindParam, compile — so the preview cannot disagree with the deploy. Pure:
|
|
16
|
+
* no Node-RED, no database, nothing executed.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
// Resolved here from the sample message. The rest — flow and global context,
|
|
20
|
+
// env, JSONata — exist only inside a running flow, and env in particular must
|
|
21
|
+
// not travel to the browser: an editor user could read any variable through it.
|
|
22
|
+
const LOCAL_SOURCES = new Set(["msg", "str", "num", "bool", "json", "bin", "date"]);
|
|
23
|
+
|
|
24
|
+
/** Placeholders with their character offsets in the SQL, for editor markers. */
|
|
25
|
+
function placeholdersOf(parsed) {
|
|
26
|
+
const out = [];
|
|
27
|
+
let offset = 0;
|
|
28
|
+
for (const token of parsed.tokens) {
|
|
29
|
+
if (token.kind === "text") {
|
|
30
|
+
offset += token.text.length;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
const length = 1 + (token.spread ? 3 : 0) + token.name.length;
|
|
34
|
+
out.push({ name: token.name, spread: token.spread, start: offset, end: offset + length });
|
|
35
|
+
offset += length;
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A dotted / bracketed msg path, the way the editor's typedInput writes it. */
|
|
41
|
+
function getPath(obj, path) {
|
|
42
|
+
const parts = [];
|
|
43
|
+
const re = /([^.[\]]+)|\[(\d+)\]|\["([^"]*)"\]|\['([^']*)'\]/g;
|
|
44
|
+
let m;
|
|
45
|
+
while ((m = re.exec(String(path))) !== null) parts.push(m[1] ?? m[2] ?? m[3] ?? m[4]);
|
|
46
|
+
let value = obj;
|
|
47
|
+
for (const part of parts) {
|
|
48
|
+
if (value === null || value === undefined) return undefined;
|
|
49
|
+
value = value[part];
|
|
50
|
+
}
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A typedInput value from the sample message, as evaluateNodeProperty would give it. */
|
|
55
|
+
function resolveLocal(type, value, msg) {
|
|
56
|
+
switch (type) {
|
|
57
|
+
case "msg":
|
|
58
|
+
return getPath(msg, value);
|
|
59
|
+
case "str":
|
|
60
|
+
return String(value ?? "");
|
|
61
|
+
case "num": {
|
|
62
|
+
const n = Number(value);
|
|
63
|
+
if (String(value).trim() === "" || Number.isNaN(n)) throw new Error(`"${value}" is not a number`);
|
|
64
|
+
return n;
|
|
65
|
+
}
|
|
66
|
+
case "bool":
|
|
67
|
+
return value === true || value === "true";
|
|
68
|
+
case "json":
|
|
69
|
+
return JSON.parse(value);
|
|
70
|
+
case "bin":
|
|
71
|
+
return Buffer.from(JSON.parse(value));
|
|
72
|
+
case "date":
|
|
73
|
+
return Date.now();
|
|
74
|
+
default:
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** One value as the browser shows it: JSON-safe, with what it was. */
|
|
80
|
+
function shown(value) {
|
|
81
|
+
if (value instanceof Bound) return { ...shown(value.value), as: value.type };
|
|
82
|
+
if (value === undefined) return { kind: "undefined" };
|
|
83
|
+
if (value === null) return { kind: "null" };
|
|
84
|
+
if (value instanceof Date) return { kind: "date", text: value.toISOString() };
|
|
85
|
+
if (Buffer.isBuffer(value)) return { kind: "bytes", text: `${value.length} bytes` };
|
|
86
|
+
if (typeof value === "bigint") return { kind: "bigint", text: String(value) };
|
|
87
|
+
if (typeof value === "number" && !Number.isFinite(value)) return { kind: "number", text: String(value) };
|
|
88
|
+
if (Array.isArray(value)) return { kind: "array", text: JSON.stringify(value.map(plain)), items: value.map(shown) };
|
|
89
|
+
if (typeof value === "object") return { kind: "object", text: JSON.stringify(plain(value)) };
|
|
90
|
+
return { kind: typeof value, text: typeof value === "string" ? value : JSON.stringify(value) };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function plain(value) {
|
|
94
|
+
if (value instanceof Bound) return plain(value.value);
|
|
95
|
+
if (value instanceof Date) return value.toISOString();
|
|
96
|
+
if (Buffer.isBuffer(value)) return `<${value.length} bytes>`;
|
|
97
|
+
if (typeof value === "bigint") return String(value);
|
|
98
|
+
if (Array.isArray(value)) return value.map(plain);
|
|
99
|
+
if (value && typeof value === "object")
|
|
100
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, plain(v)]));
|
|
101
|
+
return value;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The dialog keeps a declared type and its arguments apart: varchar + 50. */
|
|
105
|
+
function declaredType(param) {
|
|
106
|
+
const as = param.as;
|
|
107
|
+
if (!as || as === "auto") return as;
|
|
108
|
+
const args = param.asArgs === undefined ? "" : String(param.asArgs).trim();
|
|
109
|
+
return args === "" ? as : `${as}(${args})`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* @param {{ product: string, sql: string, params?: object[], msg?: object }} input
|
|
114
|
+
*/
|
|
115
|
+
function preview(input) {
|
|
116
|
+
const product = String(input.product || "");
|
|
117
|
+
if (!isProduct(product)) return { error: { kind: "product", message: `Unknown database: ${product}` } };
|
|
118
|
+
const params = Array.isArray(input.params) ? input.params : [];
|
|
119
|
+
const msg = input.msg && typeof input.msg === "object" ? input.msg : {};
|
|
120
|
+
|
|
121
|
+
let parsed;
|
|
122
|
+
try {
|
|
123
|
+
parsed = parseSql(String(input.sql ?? ""), product);
|
|
124
|
+
} catch (err) {
|
|
125
|
+
return { product, error: { kind: "sql", message: err.message } };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const placeholders = placeholdersOf(parsed);
|
|
129
|
+
const names = parsed.names;
|
|
130
|
+
const declared = params.map((p) => String(p.name || "").trim());
|
|
131
|
+
|
|
132
|
+
const values = {};
|
|
133
|
+
const results = params.map((param, index) => {
|
|
134
|
+
const name = declared[index];
|
|
135
|
+
const base = { index, name, used: names.includes(name) };
|
|
136
|
+
if (!name) return { ...base, status: "error", message: "A parameter is missing its name" };
|
|
137
|
+
if (!LOCAL_SOURCES.has(param.type || "str")) {
|
|
138
|
+
values[name] = null;
|
|
139
|
+
return { ...base, status: "runtime", message: `${param.type} is read when the flow runs` };
|
|
140
|
+
}
|
|
141
|
+
try {
|
|
142
|
+
const raw = resolveLocal(param.type || "str", param.value, msg);
|
|
143
|
+
const bound = bindParam(name, raw, declaredType(param), product);
|
|
144
|
+
values[name] = bound;
|
|
145
|
+
if (raw === undefined) {
|
|
146
|
+
// The deployed node would stop here ("Missing value"); the preview
|
|
147
|
+
// shows the statement anyway, with NULL in its place.
|
|
148
|
+
values[name] = null;
|
|
149
|
+
return { ...base, status: "missing", message: `msg.${param.value} is not in the sample message` };
|
|
150
|
+
}
|
|
151
|
+
if (parsed.spreadNames.has(name) && !Array.isArray(raw)) {
|
|
152
|
+
return { ...base, status: "error", value: shown(raw), message: `:...${name} needs an array` };
|
|
153
|
+
}
|
|
154
|
+
return { ...base, status: "ok", value: shown(bound) };
|
|
155
|
+
} catch (err) {
|
|
156
|
+
values[name] = null;
|
|
157
|
+
return { ...base, status: "error", message: err.message };
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
let compiled;
|
|
162
|
+
try {
|
|
163
|
+
// Missing names and runtime values compile as NULL, so the statement the
|
|
164
|
+
// database would receive is shown even before every value is there.
|
|
165
|
+
const all = { ...Object.fromEntries(names.map((n) => [n, null])), ...values };
|
|
166
|
+
for (const n of parsed.spreadNames) if (!Array.isArray(all[n])) all[n] = [];
|
|
167
|
+
const out = compile(parsed, all, product);
|
|
168
|
+
compiled = {
|
|
169
|
+
binding: out.binding,
|
|
170
|
+
text: out.text,
|
|
171
|
+
values: Array.isArray(out.values)
|
|
172
|
+
? out.values.map(shown)
|
|
173
|
+
: Object.fromEntries(Object.entries(out.values).map(([k, v]) => [k, shown(v)])),
|
|
174
|
+
};
|
|
175
|
+
} catch (err) {
|
|
176
|
+
compiled = { error: err.message };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
product,
|
|
181
|
+
placeholders,
|
|
182
|
+
names,
|
|
183
|
+
spread: [...parsed.spreadNames],
|
|
184
|
+
params: results,
|
|
185
|
+
missing: names.filter((n) => !declared.includes(n)),
|
|
186
|
+
unused: declared.filter((n) => n && !names.includes(n)),
|
|
187
|
+
compiled,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
module.exports = { preview, placeholdersOf, getPath, LOCAL_SOURCES };
|