@aaqu/fromcubes-db 0.0.0-stage → 0.1.1

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,171 @@
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 { utcWallClock } = require("./time");
15
+
16
+ const DIALECT = "mysql";
17
+
18
+ const ERROR_NUMBERS = {
19
+ 1062: UniqueViolationError, // ER_DUP_ENTRY
20
+ 1169: UniqueViolationError, // ER_DUP_UNIQUE
21
+ 1451: ForeignKeyViolationError, // row is referenced
22
+ 1452: ForeignKeyViolationError, // no referenced row
23
+ 1048: NotNullViolationError,
24
+ 3819: CheckViolationError,
25
+ 3024: TimeoutError, // max_execution_time exceeded
26
+ };
27
+
28
+ const CONNECTION_CODES = new Set([
29
+ "ECONNREFUSED",
30
+ "ENOTFOUND",
31
+ "ETIMEDOUT",
32
+ "EHOSTUNREACH",
33
+ "ECONNRESET",
34
+ "EPIPE",
35
+ "PROTOCOL_CONNECTION_LOST",
36
+ "PROTOCOL_SEQUENCE_TIMEOUT",
37
+ "ER_ACCESS_DENIED_ERROR",
38
+ "ER_BAD_DB_ERROR",
39
+ "ER_CON_COUNT_ERROR",
40
+ ]);
41
+
42
+ /**
43
+ * The session time_zone matching mysql2's `timezone` option, or null to leave
44
+ * the server's. Only "Z" and ±HH:MM qualify; the result is a fixed shape, never
45
+ * the user's text, because it is spliced into a SET statement.
46
+ */
47
+ function sessionTimeZone(timezone) {
48
+ if (/^z$/i.test(timezone)) return "+00:00";
49
+ const m = /^([+-])(\d{2}):?(\d{2})$/.exec(String(timezone));
50
+ return m ? `${m[1]}${m[2]}:${m[3]}` : null;
51
+ }
52
+
53
+ async function createPool(config) {
54
+ const mysql = require("mysql2/promise");
55
+
56
+ const pool = mysql.createPool({
57
+ host: config.host,
58
+ port: config.port,
59
+ database: config.database,
60
+ user: config.user,
61
+ password: config.password,
62
+ connectionLimit: config.poolMax,
63
+ connectTimeout: config.connectTimeoutMs,
64
+ idleTimeout: config.idleTimeoutMs,
65
+ waitForConnections: true,
66
+ // A bounded queue: under overload callers get an error instead of piling up
67
+ // messages in memory until the process dies.
68
+ queueLimit: config.queueMax,
69
+ enableKeepAlive: true,
70
+ // Values are bound as parameters, so multi-statement SQL is never needed and
71
+ // leaving it off removes a whole class of injection escalation.
72
+ multipleStatements: false,
73
+ // Dates travel as UTC, like on every other product (see ./time.js) …
74
+ timezone: "Z",
75
+ // A BIGINT past 2^53 as text instead of a double that is a different
76
+ // number; DECIMAL is text already.
77
+ supportBigNumbers: true,
78
+ ...config.options,
79
+ });
80
+
81
+ // … and the session reads them in the same zone, so a TIMESTAMP column —
82
+ // which the server converts from the session zone — stores the instant that
83
+ // was sent, not one shifted by the server's own zone. NOW() is UTC in these
84
+ // sessions. The connection's Timezone field still wins; "local" leaves the
85
+ // session on the server's default, as before this policy.
86
+ const sessionZone = sessionTimeZone((config.options && config.options.timezone) || "Z");
87
+ if (sessionZone) {
88
+ pool.pool.on("connection", (connection) => {
89
+ connection.query(`SET time_zone = '${sessionZone}'`);
90
+ });
91
+ }
92
+
93
+ const probe = await pool.getConnection();
94
+ probe.release();
95
+
96
+ return pool;
97
+ }
98
+
99
+ /**
100
+ * The value mysql2 should send. JSON goes as text: mysql2 sends an object with
101
+ * the binary character set, which a JSON column refuses. A bit string becomes
102
+ * the bytes it spells — sent as text, '101' is three bytes, not three bits. A
103
+ * vector is its float32 bytes, which a VECTOR column takes as they are — or,
104
+ * where the catalogue says `bindAs: "text"` (TiDB), its `[1,2.5]` text.
105
+ */
106
+ function toMysql(value) {
107
+ if (value instanceof Bound) {
108
+ const v = value.value;
109
+ if (v === null || v === undefined) return v;
110
+ switch (value.spec.category) {
111
+ case "json":
112
+ return JSON.stringify(v);
113
+ case "vector": {
114
+ if (value.spec.bindAs === "text") return JSON.stringify(Array.from(v));
115
+ const bytes = Buffer.alloc(v.length * 4);
116
+ v.forEach((n, i) => bytes.writeFloatLE(n, i * 4));
117
+ return bytes;
118
+ }
119
+ case "date": {
120
+ // Written out here rather than by mysql2, which would hand a DATE
121
+ // column 23:59:59.999 and let the server round it into the next day.
122
+ const wall = utcWallClock(v);
123
+ return value.type === "date" ? wall.slice(0, wall.indexOf(" ")) : wall;
124
+ }
125
+ }
126
+ if (value.type === "bit" && typeof v === "string") return bitBytes(v);
127
+ return toMysql(v);
128
+ }
129
+ return value;
130
+ }
131
+
132
+ function bitBytes(bits) {
133
+ const padded = bits.padStart(Math.max(8, Math.ceil(bits.length / 8) * 8), "0");
134
+ const bytes = Buffer.alloc(padded.length / 8);
135
+ for (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(padded.slice(i * 8, i * 8 + 8), 2);
136
+ return bytes;
137
+ }
138
+
139
+ async function execute(pool, compiled) {
140
+ const [result] = await pool.execute(compiled.text, compiled.values.map(toMysql));
141
+
142
+ // SELECT gives an array of rows; DML gives a ResultSetHeader.
143
+ if (Array.isArray(result)) {
144
+ return { rows: result, rowCount: result.length };
145
+ }
146
+ return {
147
+ rows: [],
148
+ rowCount: typeof result.affectedRows === "number" ? result.affectedRows : 0,
149
+ // 0 is what an UPDATE or DELETE reports, not an id — leave it out rather
150
+ // than handing the flow a plausible-looking zero.
151
+ insertId: result.insertId > 0 ? result.insertId : undefined,
152
+ };
153
+ }
154
+
155
+ async function closePool(pool) {
156
+ await pool.end();
157
+ }
158
+
159
+ function translateError(err) {
160
+ if (!err || typeof err !== "object") {
161
+ return new QueryError(String(err), { dialect: DIALECT });
162
+ }
163
+ const options = { dialect: DIALECT, driverCode: err.errno ?? err.code, cause: err };
164
+
165
+ const Specific = ERROR_NUMBERS[err.errno];
166
+ if (Specific) return new Specific(err.message, options);
167
+ if (CONNECTION_CODES.has(err.code)) return new ConnectionError(err.message, options);
168
+ return new QueryError(err.message, options);
169
+ }
170
+
171
+ module.exports = { dialect: DIALECT, createPool, execute, closePool, translateError, toMysql, sessionTimeZone };
@@ -0,0 +1,272 @@
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 { utcWallClock, hasOffset } = require("./time");
15
+ const { exactNumber, vectorArray } = require("./read");
16
+
17
+ const DIALECT = "oracle";
18
+
19
+ const ORA_NUMBERS = {
20
+ 1: UniqueViolationError, // ORA-00001 unique constraint violated
21
+ 1400: NotNullViolationError, // cannot insert NULL
22
+ 1407: NotNullViolationError,
23
+ 2290: CheckViolationError,
24
+ 2291: ForeignKeyViolationError, // parent key not found
25
+ 2292: ForeignKeyViolationError, // child record found
26
+ 3156: TimeoutError, // call timeout
27
+ };
28
+
29
+ const CONNECTION_ORA = new Set([
30
+ 1017, // invalid credential
31
+ 12154, // TNS could not resolve connect identifier
32
+ 12505,
33
+ 12514, // listener does not know of service
34
+ 12541, // no listener
35
+ 12545,
36
+ 28000, // account locked
37
+ ]);
38
+
39
+ async function createPool(config) {
40
+ const oracledb = require("oracledb");
41
+
42
+ // Thin mode (the default since node-oracledb 6) needs no Oracle Client
43
+ // libraries, which keeps the Node-RED install a plain npm install.
44
+ oracledb.outFormat = oracledb.OUT_FORMAT_OBJECT;
45
+ oracledb.fetchAsString = [oracledb.CLOB];
46
+
47
+ const userSessionCallback = config.options && config.options.sessionCallback;
48
+ const pool = await oracledb.createPool({
49
+ user: config.user,
50
+ password: config.password,
51
+ connectString: connectStringFor(config),
52
+ poolMin: config.poolMin,
53
+ poolMax: config.poolMax,
54
+ poolTimeout: Math.ceil(config.idleTimeoutMs / 1000),
55
+ queueTimeout: config.connectTimeoutMs,
56
+ // Bounded queue — see the MySQL adapter for the reasoning.
57
+ queueMax: config.queueMax,
58
+ ...config.options,
59
+ sessionCallback: (connection, requestedTag, callback) => {
60
+ connection
61
+ .execute(SESSION_SETUP)
62
+ .then(() =>
63
+ typeof userSessionCallback === "function"
64
+ ? userSessionCallback(connection, requestedTag, callback)
65
+ : callback(),
66
+ )
67
+ .catch((err) => callback(err));
68
+ },
69
+ });
70
+
71
+ pool.__queryTimeoutMs = config.queryTimeoutMs;
72
+ return pool;
73
+ }
74
+
75
+ /**
76
+ * Every session reads dates the way the adapter writes them: UTC, and ISO 8601
77
+ * with a signed year (Oracle starts in 4712 BC). The NLS formats are what an
78
+ * implicit conversion from text uses — so a timestamp kept as text for its
79
+ * nine fractional digits lands in the column instead of failing with ORA-01843
80
+ * — and `.` is the decimal point for an exact number sent as text whatever
81
+ * territory the database was created with. CURRENT_TIMESTAMP and SYSDATE-free
82
+ * defaults that depend on the session zone are therefore UTC.
83
+ */
84
+ const SESSION_SETUP = `ALTER SESSION SET
85
+ TIME_ZONE = '+00:00'
86
+ NLS_DATE_FORMAT = 'SYYYY-MM-DD"T"HH24:MI:SS'
87
+ NLS_TIMESTAMP_FORMAT = 'SYYYY-MM-DD"T"HH24:MI:SS.FF9'
88
+ NLS_TIMESTAMP_TZ_FORMAT = 'SYYYY-MM-DD"T"HH24:MI:SS.FF9TZH:TZM'
89
+ NLS_NUMERIC_CHARACTERS = '.,'`;
90
+
91
+ /** A year the way SYYYY reads it. Oracle has no year zero: astronomical 0 is 1 BC, -0001. */
92
+ const oracleYear = (y) => (y <= 0 ? `-${String(1 - y).padStart(4, "0")}` : String(y).padStart(4, "0"));
93
+
94
+ /**
95
+ * What oracledb should bind. Two things make Oracle different from the other
96
+ * drivers. oracledb reads any plain object as a bind *definition* — `{val,
97
+ * dir, type}` — so an object from a flow either fails (NJS-044) or, worse,
98
+ * is obeyed; every object is therefore wrapped as `{ val }` with an explicit
99
+ * type. And a Date is bound as a local-time timestamp, so it is sent as UTC
100
+ * text in the session's NLS format instead.
101
+ */
102
+ function toOracle(oracledb, value) {
103
+ if (value instanceof Bound) {
104
+ const v = value.value;
105
+ const isNull = v === null || v === undefined;
106
+ switch (value.spec.category) {
107
+ case "json":
108
+ return { val: isNull ? null : v, type: oracledb.DB_TYPE_JSON };
109
+ case "vector": {
110
+ if (isNull) return { val: null, type: oracledb.DB_TYPE_VECTOR };
111
+ const format = value.declared.format;
112
+ const Typed = format === "float32" ? Float32Array : format === "int8" ? Int8Array : Float64Array;
113
+ return { val: Typed.from(v), type: oracledb.DB_TYPE_VECTOR };
114
+ }
115
+ case "boolean":
116
+ return { val: isNull ? null : v, type: oracledb.DB_TYPE_BOOLEAN };
117
+ case "date":
118
+ if (isNull) return null;
119
+ if (v instanceof Date && inDriverRange(v)) return { val: v, type: oracledb.DB_TYPE_TIMESTAMP_TZ };
120
+ return oracleTimestamp(v, value.type);
121
+ }
122
+ return toOracle(oracledb, v);
123
+ }
124
+ // As TIMESTAMP WITH TIME ZONE a Date names its instant, and the server turns
125
+ // it into the session's zone — UTC — for a DATE or TIMESTAMP column.
126
+ // Outside years 1..9999 the driver encodes whatever it is given (year 10000
127
+ // is stored), so such a Date goes as text, which the server range-checks.
128
+ if (value instanceof Date) {
129
+ if (inDriverRange(value)) return { val: value, type: oracledb.DB_TYPE_TIMESTAMP_TZ };
130
+ // The column type is unknown: whole seconds read into DATE and TIMESTAMP alike.
131
+ return oracleTimestamp(value, value.getUTCMilliseconds() === 0 ? "date" : "timestamp");
132
+ }
133
+ if (typeof value === "bigint") return String(value);
134
+ if (value !== null && typeof value === "object" && !Buffer.isBuffer(value)) {
135
+ return { val: value, type: oracledb.DB_TYPE_JSON };
136
+ }
137
+ return value;
138
+ }
139
+
140
+ const inDriverRange = (date) => date.getUTCFullYear() >= 1 && date.getUTCFullYear() <= 9999;
141
+
142
+ /** A point in time as text in the session's NLS format for that column type. */
143
+ function oracleTimestamp(value, type) {
144
+ const wall = utcWallClock(value, { separator: "T", year: oracleYear });
145
+ if (type === "date") return wall.slice(0, wall.indexOf("."));
146
+ if (type === "timestamp with time zone") {
147
+ // The offset the value was written with survives; a Date is UTC.
148
+ if (hasOffset(value)) return keepOffset(String(value).trim());
149
+ return `${wall}+00:00`;
150
+ }
151
+ return wall;
152
+ }
153
+
154
+ /** ISO text with its own offset, rewritten into NLS_TIMESTAMP_TZ_FORMAT. */
155
+ function keepOffset(text) {
156
+ const m =
157
+ /^([+-]?\d{4,})-(\d{2})-(\d{2})[T\s](\d{1,2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?\s*(Z|[+-]\d{2}(?::?\d{2})?)$/i.exec(
158
+ text,
159
+ );
160
+ if (!m) return text;
161
+ const [, y, mo, d, h, mi, sec = "00", frac = "0", zone] = m;
162
+ const offset = /^z$/i.test(zone)
163
+ ? "+00:00"
164
+ : zone.length === 3
165
+ ? `${zone}:00`
166
+ : zone.replace(/^([+-]\d{2}):?(\d{2})$/, "$1:$2");
167
+ return `${y}-${mo}-${d}T${h.padStart(2, "0")}:${mi}:${sec}.${frac}${offset}`;
168
+ }
169
+
170
+ /**
171
+ * The read side: oracledb (Thin) decodes DATE and TIMESTAMP into a Date whose
172
+ * *local* fields hold the stored wall clock. Here that wall clock is UTC, so
173
+ * the same fields are read back as UTC. Oracle's year is signed with no year
174
+ * zero (-4712 is 4712 BC), a Date's is astronomical (-4711). TIMESTAMP WITH
175
+ * TIME ZONE already names its instant and is left to the driver.
176
+ */
177
+ function utcFetch(oracledb) {
178
+ const asUtc = new Set([oracledb.DB_TYPE_DATE, oracledb.DB_TYPE_TIMESTAMP, oracledb.DB_TYPE_TIMESTAMP_LTZ]);
179
+ return (metadata) => {
180
+ if (asUtc.has(metadata.dbType)) return { converter: localFieldsAsUtc };
181
+ switch (metadata.dbType) {
182
+ // NUMBER is fetched as text and becomes a number only when the double is
183
+ // exactly it: oracledb's own conversion turned 9007199254740993 into
184
+ // …992 and 38-digit values into their first 17 digits.
185
+ case oracledb.DB_TYPE_NUMBER:
186
+ return { type: oracledb.STRING, converter: exactNumber };
187
+ // A LOB arrives as a Lob stream object otherwise — nothing a flow can
188
+ // use, and the debug sidebar chokes on it.
189
+ case oracledb.DB_TYPE_CLOB:
190
+ case oracledb.DB_TYPE_NCLOB:
191
+ return { type: oracledb.STRING };
192
+ case oracledb.DB_TYPE_BLOB:
193
+ return { type: oracledb.BUFFER };
194
+ case oracledb.DB_TYPE_VECTOR:
195
+ return { converter: vectorArray };
196
+ }
197
+ return undefined;
198
+ };
199
+ }
200
+
201
+ function localFieldsAsUtc(d) {
202
+ if (!(d instanceof Date) || Number.isNaN(d.getTime())) return d;
203
+ const utc = new Date(
204
+ Date.UTC(2000, d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()),
205
+ );
206
+ const year = d.getFullYear();
207
+ utc.setUTCFullYear(year < 0 ? year + 1 : year);
208
+ return utc;
209
+ }
210
+
211
+ async function execute(pool, compiled) {
212
+ const oracledb = require("oracledb");
213
+ const values = Object.fromEntries(Object.entries(compiled.values).map(([k, v]) => [k, toOracle(oracledb, v)]));
214
+ const connection = await pool.getConnection();
215
+
216
+ // callTimeout aborts the round trip driver-side, so a hung statement releases
217
+ // its pool slot instead of holding it until the server gives up.
218
+ if (pool.__queryTimeoutMs) connection.callTimeout = pool.__queryTimeoutMs;
219
+
220
+ try {
221
+ const result = await connection.execute(compiled.text, values, {
222
+ outFormat: oracledb.OUT_FORMAT_OBJECT,
223
+ fetchTypeHandler: utcFetch(oracledb),
224
+ autoCommit: true,
225
+ });
226
+ return {
227
+ rows: result.rows || [],
228
+ rowCount: typeof result.rowsAffected === "number" ? result.rowsAffected : (result.rows || []).length,
229
+ };
230
+ } finally {
231
+ // Always returns the session to the pool, including on error and timeout.
232
+ await connection.close().catch(() => {});
233
+ }
234
+ }
235
+
236
+ async function closePool(pool) {
237
+ // 10 s drain, then force. Node-RED gives a node 15 s to close.
238
+ await pool.close(10);
239
+ }
240
+
241
+ function connectStringFor(config) {
242
+ if (config.options && config.options.connectString) return config.options.connectString;
243
+ if (config.connectString) return config.connectString;
244
+ const port = config.port || 1521;
245
+ return `${config.host}:${port}/${config.database}`;
246
+ }
247
+
248
+ function translateError(err) {
249
+ if (!err || typeof err !== "object") {
250
+ return new QueryError(String(err), { dialect: DIALECT });
251
+ }
252
+ const num = err.errorNum;
253
+ const options = { dialect: DIALECT, driverCode: num ?? err.code, cause: err };
254
+ const message = err.message || String(err);
255
+
256
+ if (typeof err.code === "string" && /DPI-1067|NJS-05\d\d/.test(err.code)) {
257
+ return new TimeoutError(message, options);
258
+ }
259
+ const Specific = ORA_NUMBERS[num];
260
+ if (Specific) return new Specific(message, options);
261
+ if (CONNECTION_ORA.has(num)) return new ConnectionError(message, options);
262
+ // NJS-040 (no free session in time), NJS-047 (no such pool) and NJS-50x
263
+ // (connection closed, lost, TLS) are about reaching the database. The rest of
264
+ // the NJS-04x range is about the statement — NJS-044 is a malformed bind —
265
+ // and must not read as an outage.
266
+ if (typeof err.code === "string" && /^NJS-(?:04[07]|50\d)$/.test(err.code)) {
267
+ return new ConnectionError(message, options);
268
+ }
269
+ return new QueryError(message, options);
270
+ }
271
+
272
+ module.exports = { dialect: DIALECT, createPool, execute, closePool, translateError, toOracle, SESSION_SETUP };
@@ -0,0 +1,161 @@
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 { instant, utcWallClock, fromUtcText, pad } = require("./time");
15
+ const { exactNumber, vectorArray } = require("./read");
16
+
17
+ const DIALECT = "postgres";
18
+
19
+ // https://www.postgresql.org/docs/current/errcodes-appendix.html
20
+ const SQLSTATE = {
21
+ 23505: UniqueViolationError,
22
+ 23503: ForeignKeyViolationError,
23
+ 23502: NotNullViolationError,
24
+ 23514: CheckViolationError,
25
+ 57014: TimeoutError, // query_canceled — what statement_timeout raises
26
+ };
27
+
28
+ const CONNECTION_CODES = new Set([
29
+ "ECONNREFUSED",
30
+ "ENOTFOUND",
31
+ "ETIMEDOUT",
32
+ "EHOSTUNREACH",
33
+ "ECONNRESET",
34
+ "EPIPE",
35
+ "28P01", // invalid_password
36
+ "28000", // invalid_authorization_specification
37
+ "3D000", // invalid_catalog_name
38
+ "53300", // too_many_connections
39
+ ]);
40
+
41
+ async function createPool(config) {
42
+ const { Pool } = require("pg");
43
+
44
+ const pool = new Pool({
45
+ host: config.host,
46
+ port: config.port,
47
+ database: config.database,
48
+ user: config.user,
49
+ password: config.password,
50
+ max: config.poolMax,
51
+ min: config.poolMin,
52
+ idleTimeoutMillis: config.idleTimeoutMs,
53
+ connectionTimeoutMillis: config.connectTimeoutMs,
54
+ // Applied per connection, so a runaway statement cannot pin a pool slot.
55
+ statement_timeout: config.queryTimeoutMs,
56
+ query_timeout: config.queryTimeoutMs,
57
+ application_name: "fromcubes-db",
58
+ // The read side of ./time.js: a timestamp without a zone and a date are UTC
59
+ // wall clocks here, as they were written. For this pool only — pg's global
60
+ // parsers belong to every other pg user in the Node-RED process.
61
+ types: utcTypes(require("pg").types),
62
+ ...config.options,
63
+ });
64
+
65
+ // Without this listener an error on an idle client is an unhandled 'error'
66
+ // event, which takes the whole Node-RED process down.
67
+ const onError = (err) => config.onPoolError(translateError(err));
68
+ pool.on("error", onError);
69
+ pool.__onError = onError;
70
+
71
+ // Fail fast on bad credentials/host instead of surfacing it on first message.
72
+ const probe = await pool.connect();
73
+ probe.release();
74
+
75
+ return pool;
76
+ }
77
+
78
+ /**
79
+ * A timestamp as PostgreSQL and CockroachDB read it, in UTC. pg's own
80
+ * conversion uses the process's local zone (and spells 4713 BC with a local
81
+ * mean time offset, "+01:24 BC", which CockroachDB refuses).
82
+ */
83
+ function pgTimestamp(value) {
84
+ const { date } = instant(value);
85
+ const bc = date.getUTCFullYear() <= 0;
86
+ const wall = utcWallClock(value, { year: (y) => pad(y <= 0 ? 1 - y : y, 4) });
87
+ return `${wall}+00${bc ? " BC" : ""}`;
88
+ }
89
+
90
+ const TIMESTAMP_OID = 1114;
91
+ const DATE_OID = 1082;
92
+ const INT8_OID = 20;
93
+ // CockroachDB's built-in VECTOR has a fixed oid; pgvector's is per-database.
94
+ const CRDB_VECTOR_OID = 90006;
95
+
96
+ /**
97
+ * Read-side parsers for this pool. Timestamps without a zone and dates are
98
+ * UTC wall clocks; BIGINT is a number when the double is exactly that number
99
+ * and text otherwise (pg's default is always text, so `SELECT count(*)` was a
100
+ * string); a CockroachDB vector is an array of numbers.
101
+ */
102
+ function utcTypes(types) {
103
+ return {
104
+ getTypeParser(oid, format) {
105
+ if (format !== "binary") {
106
+ if (oid === TIMESTAMP_OID) return (text) => fromUtcText(text, { bcSuffix: true });
107
+ if (oid === DATE_OID) return (text) => fromUtcText(text, { bcSuffix: true });
108
+ if (oid === INT8_OID) return exactNumber;
109
+ if (oid === CRDB_VECTOR_OID) return vectorArray;
110
+ }
111
+ return types.getTypeParser(oid, format);
112
+ },
113
+ };
114
+ }
115
+
116
+ /**
117
+ * The value pg should send. A declared json type is sent as JSON text — pg
118
+ * would otherwise write a JS array as a PostgreSQL array literal, `{1,2}`,
119
+ * which no json column takes. A vector is pgvector's text form.
120
+ */
121
+ function toPg(value) {
122
+ if (value instanceof Bound) {
123
+ const v = value.value;
124
+ if (v === null || v === undefined) return v;
125
+ if (value.spec.category === "json") return JSON.stringify(v);
126
+ if (value.spec.category === "vector") return `[${v.join(",")}]`;
127
+ if (value.spec.category === "date") return pgTimestamp(v);
128
+ return toPg(v);
129
+ }
130
+ if (value instanceof Date) return pgTimestamp(value);
131
+ return value;
132
+ }
133
+
134
+ async function execute(pool, compiled) {
135
+ const result = await pool.query({ text: compiled.text, values: compiled.values.map(toPg) });
136
+ return {
137
+ rows: Array.isArray(result.rows) ? result.rows : [],
138
+ rowCount: typeof result.rowCount === "number" ? result.rowCount : 0,
139
+ command: result.command,
140
+ };
141
+ }
142
+
143
+ async function closePool(pool) {
144
+ if (pool.__onError) pool.off("error", pool.__onError);
145
+ await pool.end();
146
+ }
147
+
148
+ function translateError(err) {
149
+ if (!err || typeof err !== "object") {
150
+ return new QueryError(String(err), { dialect: DIALECT });
151
+ }
152
+ const code = err.code;
153
+ const options = { dialect: DIALECT, driverCode: code, cause: err };
154
+
155
+ const Specific = SQLSTATE[code];
156
+ if (Specific) return new Specific(err.message, options);
157
+ if (CONNECTION_CODES.has(code)) return new ConnectionError(err.message, options);
158
+ return new QueryError(err.message, options);
159
+ }
160
+
161
+ module.exports = { dialect: DIALECT, createPool, execute, closePool, translateError, toPg };
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * The read side's one rule: a value comes back as the driver reported it
5
+ * unless that loses something. Drivers turn exact numbers into doubles
6
+ * (MySQL's BIGINT, Oracle's NUMBER), so 9007199254740993 arrives as
7
+ * …992 and the flow never learns. Here an exact number becomes a JS number
8
+ * only when the double *is* that number, and otherwise stays text — the shape
9
+ * pg has always used for BIGINT and NUMERIC.
10
+ */
11
+
12
+ // A double holds every decimal of up to 15 significant digits exactly enough
13
+ // to print back the same digits.
14
+ const MAX_EXACT_DIGITS = 15;
15
+
16
+ /**
17
+ * @param {string|number|bigint|null} value as the driver produced it, ideally text
18
+ * @returns {number|string|null}
19
+ */
20
+ function exactNumber(value) {
21
+ if (value === null || value === undefined) return value;
22
+ if (typeof value === "bigint") {
23
+ return value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER)
24
+ ? Number(value)
25
+ : String(value);
26
+ }
27
+ if (typeof value === "number") return value;
28
+ const text = String(value).trim();
29
+ const m = /^([+-]?)(\d*)(?:\.(\d*))?$/.exec(text);
30
+ if (!m || (m[2] === "" && (m[3] === undefined || m[3] === ""))) return text;
31
+ const whole = m[2].replace(/^0+/, "");
32
+ const fraction = (m[3] || "").replace(/0+$/, "");
33
+ if (fraction === "") {
34
+ const n = Number(text);
35
+ return Number.isSafeInteger(n) ? n : text;
36
+ }
37
+ const significant = (whole + fraction).replace(/^0+/, "").length;
38
+ return significant <= MAX_EXACT_DIGITS ? Number(text) : text;
39
+ }
40
+
41
+ /** A vector as a plain array of numbers, whatever the driver handed over. */
42
+ function vectorArray(value) {
43
+ if (value === null || value === undefined) return value;
44
+ if (Array.isArray(value)) return value;
45
+ if (ArrayBuffer.isView(value) && !Buffer.isBuffer(value)) return Array.from(value);
46
+ if (typeof value === "string") {
47
+ try {
48
+ const parsed = JSON.parse(value);
49
+ if (Array.isArray(parsed)) return parsed;
50
+ } catch {
51
+ // Not the text form after all — hand it on untouched.
52
+ }
53
+ }
54
+ return value;
55
+ }
56
+
57
+ module.exports = { exactNumber, vectorArray, MAX_EXACT_DIGITS };