jsql-neo 6.8.12 → 6.8.13

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 CHANGED
@@ -3,7 +3,7 @@
3
3
  > **One engine to rule them all** — a Rust-powered embedded database that speaks your language:
4
4
  > MySQL, PostgreSQL, MongoDB, Redis, SQL, TypeScript, **and the browser**.
5
5
 
6
- > **v6.8.12** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
6
+ > **v6.8.13** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
7
7
 
8
8
  ![Engines](https://img.shields.io/badge/engines-Native%20%7C%20WASM%20%7C%20Pure%20JS-7ee787)
9
9
  ![MySQL](https://img.shields.io/badge/protocol-MySQL%20compatible-1f6feb)
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.8.12 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.8.13 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
package/lib/cache.js CHANGED
@@ -82,7 +82,11 @@ class Cache {
82
82
  if (!this._getData().has(k)) return 0;
83
83
  const s = typeof seconds === 'bigint' ? seconds.toString() : String(seconds);
84
84
  if (!/^[-+]?\d+$/.test(s.trim())) throw new Error('value is not an integer or out of range');
85
- this._getExpires().set(k, Date.now() + Number(s) * 1000);
85
+ // #304:Redis 对负 TTL 报 invalid expire time。
86
+ // 此前负数被放行并返回 1,键被静默立即失效(ttl 变 -2),排查时看不到错误。
87
+ const n = Number(s);
88
+ if (n <= 0) throw new Error('invalid expire time');
89
+ this._getExpires().set(k, Date.now() + n * 1000);
86
90
  return 1;
87
91
  }
88
92
  ttl(key) {
package/lib/client.js CHANGED
@@ -20,6 +20,11 @@ class JSQL {
20
20
  this.port = opts.port || 3000;
21
21
  this.dataDir = opts.dataDir || null;
22
22
  this._process = null;
23
+ // #301:数据请求超时(默认 30s,可通过 timeoutMs 配置)。
24
+ // 服务端挂起 / 网络半开时,请求必须失败而不是永久 pending。
25
+ this.timeoutMs = Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0
26
+ ? Math.trunc(opts.timeoutMs)
27
+ : 30000;
23
28
  }
24
29
 
25
30
  async start() {
@@ -79,6 +84,7 @@ class JSQL {
79
84
  method,
80
85
  headers: body ? { 'Content-Type': 'application/json' } : {},
81
86
  };
87
+ let settled = false;
82
88
  const req = http.request(opts, (res) => {
83
89
  // P3-7: 未处理 res 错误——非 2xx 状态码应 reject
84
90
  if (res.statusCode < 200 || res.statusCode >= 300) {
@@ -95,6 +101,14 @@ class JSQL {
95
101
  });
96
102
  });
97
103
  req.on('error', reject);
104
+ // #301:主请求必须设超时。
105
+ // 此前只有健康检查有 500ms 超时,数据请求路径完全没有 ——
106
+ // 服务端接受连接后不响应(挂死 / 网络半开)时,Promise 永久 pending,
107
+ // 调用方 await 后再无后续,表现为「接口偶发卡死不返回」。
108
+ const timeoutMs = this.timeoutMs;
109
+ req.setTimeout(timeoutMs, () => {
110
+ req.destroy(new Error(`请求超时(${timeoutMs}ms):${method} ${path}`));
111
+ });
98
112
  if (body) req.write(JSON.stringify(body));
99
113
  req.end();
100
114
  });
package/lib/database.js CHANGED
@@ -2158,8 +2158,11 @@ class Database {
2158
2158
  async insert(tableName, data) {
2159
2159
  const table = this._ensureTable(tableName);
2160
2160
  if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2161
- const arr = Array.isArray(data) ? data : [data];
2162
- if (!(await this._runHooks('beforeInsert', [tableName, arr]))) return [];
2161
+ // #303:beforeInsert 可返回「修改后 data」(PLUGINS.md 契约)。
2162
+ // 钩子返回值通过 args 数组原地写回,这里必须读回被替换后的 arr。
2163
+ const hookArgs = [tableName, Array.isArray(data) ? data : [data]];
2164
+ if (!(await this._runHooks('beforeInsert', hookArgs))) return [];
2165
+ const arr = hookArgs[1];
2163
2166
  const pk = this._pkOf(table);
2164
2167
  // #201:多行 INSERT 走 insertMany,逐行校验全部通过后再统一落库
2165
2168
  const inserted = (arr.length > 1 && typeof table.insertMany === 'function')
@@ -2311,7 +2314,11 @@ class Database {
2311
2314
  async updateById(tableName, id, data) {
2312
2315
  const table = this._ensureTable(tableName);
2313
2316
  if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2314
- if (!(await this._runHooks('beforeUpdate', [tableName, id, data]))) return;
2317
+ // #303:beforeUpdate 可返回「修改后 data」(PLUGINS.md 契约),
2318
+ // 写回后必须用改写后的值继续。
2319
+ const hookArgs = [tableName, id, data];
2320
+ if (!(await this._runHooks('beforeUpdate', hookArgs))) return;
2321
+ data = hookArgs[2];
2315
2322
  // P1-9: updateById 绕过类型校验——先校验再更新
2316
2323
  const validated = table._validateDataTypes({ ...data }, true);
2317
2324
  const row = this._resolveId(table, id);
@@ -2336,7 +2343,7 @@ class Database {
2336
2343
  const clash = typeof table._uniqueConflictRow === 'function'
2337
2344
  ? table._uniqueConflictRow(field, nv, row)
2338
2345
  : table._rows.find(r => r !== row && r[field] === nv);
2339
- if (clash) throw createError('ER_DUP_ENTRY', `Duplicate entry '${nv}' for key '${field}'`);
2346
+ if (clash) throw createError('ER_DUP_ENTRY', String(nv), field);
2340
2347
  }
2341
2348
  // 外键:改主键时按 ON UPDATE 传播到引用它的子表;改自身外键列时校验引用存在。
2342
2349
  // 此前这里直接 Object.assign 绕过 Table.updateById,ON UPDATE CASCADE / RESTRICT
@@ -622,6 +622,37 @@ class Datastore {
622
622
  return ix;
623
623
  }
624
624
 
625
+ /**
626
+ * 移除指定字段的索引(#302)。
627
+ * NeDB 的 Datastore 接口包含 removeIndex(fieldName, cb);
628
+ * 此前完全缺失,调用即 TypeError,迁移应用启动清理旧索引时直接崩。
629
+ * 支持同步返回与 NeDB 风格的 callback 两种签名。
630
+ */
631
+ async removeIndex(fieldName, cb) {
632
+ const name = String(fieldName);
633
+ const before = this._indexes.length;
634
+ this._indexes = this._indexes.filter(i => !i || i.fieldName !== name);
635
+ const removed = before - this._indexes.length;
636
+ const p = Promise.resolve(removed);
637
+ if (cb) p.then(n => cb(null, n), err => cb(err));
638
+ return p;
639
+ }
640
+
641
+ /**
642
+ * 列出当前所有索引(#302)。
643
+ * NeDB 的 Datastore 接口包含 getIndexes();此前缺失,调用即 TypeError。
644
+ * 支持同步返回与 NeDB 风格的 callback 两种签名。
645
+ */
646
+ async getIndexes(cb) {
647
+ const list = (this._indexes || []).map(i => ({
648
+ fieldName: i.fieldName,
649
+ unique: i.unique === true,
650
+ }));
651
+ const p = Promise.resolve(list);
652
+ if (cb) p.then(n => cb(null, n), err => cb(err));
653
+ return p;
654
+ }
655
+
625
656
  async compaction() {
626
657
  const db = await this._ensureEngine();
627
658
  if (typeof db.compact === 'function') return db.compact();
package/lib/plugin.js CHANGED
@@ -239,6 +239,28 @@ function applyPlugin(engine, plugin, opts) {
239
239
  * - 任一钩子返回 false → 中止(返回 false),引擎据此跳过本次操作;
240
240
  * - native 引擎置 `_forbidReentry`,钩子内再次触发引擎操作会抛 ER_PLUGIN_REENTRY。
241
241
  */
242
+ /**
243
+ * 执行插件钩子。
244
+ *
245
+ * 返回值契约(#303):
246
+ * · 返回 `false` → 中止(调用方按 falsy 判断并放弃操作)
247
+ * · 返回 `undefined` / `null` → 继续,参数不变
248
+ * · 返回其它值 → **写回**到对应位置的参数(`beforeInsert` 返回改写后的
249
+ * data 数组、`beforeUpdate` 返回改写后的 data),后续钩子与实际写入
250
+ * 都使用写回后的值。
251
+ *
252
+ * 此前只识别 `false`,其余返回值一律丢弃 —— 与 PLUGINS.md 承诺的
253
+ * 「修改后 data / false 中止」不符:按文档写的脱敏 / 审计插件静默失效。
254
+ *
255
+ * 写回规则:返回值替换**最后一个**参数(`beforeInsert(table, data[])` 的
256
+ * data、`beforeUpdate(table, id, data)` 的 data)。若返回值是数组且原
257
+ * 最后一个参数也是数组,则整体替换;否则按标量替换。
258
+ *
259
+ * @param {object} engine
260
+ * @param {string} hookName
261
+ * @param {Array} args 初始参数
262
+ * @returns {Promise<boolean>} true=继续,false=中止
263
+ */
242
264
  function runHooks(engine, hookName, args) {
243
265
  const hooks = engine._hooks && engine._hooks[hookName];
244
266
  if (!hooks || hooks.length === 0) return true;
@@ -260,6 +282,18 @@ function runHooks(engine, hookName, args) {
260
282
  for (const entry of ordered) {
261
283
  const result = await entry.fn(...args);
262
284
  if (result === false) return false;
285
+ // #303:非 false / undefined 的返回值写回参数(PLUGINS.md 契约)
286
+ if (result !== undefined && result !== null && args.length > 0) {
287
+ const last = args.length - 1;
288
+ // 原参数是数组时,只接受数组返回值(否则调用方会拿到非数组而崩)。
289
+ // beforeInsert(table, data[]) → 返回改写后的数组;
290
+ // beforeUpdate(table, id, data) → 返回改写后的 data 对象。
291
+ if (Array.isArray(args[last])) {
292
+ if (Array.isArray(result)) args[last] = result;
293
+ } else if (!Array.isArray(result)) {
294
+ args[last] = result;
295
+ }
296
+ }
263
297
  }
264
298
  return true;
265
299
  } finally {
package/lib/sql.js CHANGED
@@ -6847,7 +6847,11 @@ class SQLExecutor {
6847
6847
  const v = d[col];
6848
6848
  if (v === undefined || v === null) continue; // UNIQUE 允许多个 NULL
6849
6849
  const s = String(v);
6850
- if (used.has(s)) throw new Error(`ER_DUP_ENTRY: Duplicate entry '${s}' for unique column '${col}'`);
6850
+ if (used.has(s)) {
6851
+ // #305:与其它 ER_DUP_ENTRY 调用统一用模板拼装,
6852
+ // 消息形态与 MySQL 一致:Duplicate entry 'x' for key 'col'
6853
+ throw createError('ER_DUP_ENTRY', s, col);
6854
+ }
6851
6855
  used.add(s);
6852
6856
  }
6853
6857
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.8.12",
3
+ "version": "6.8.13",
4
4
  "description": "JSQL-NEO — Rust-powered embedded database with WASM, REST API, B-Tree indexes, WAL, crash recovery",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -52,12 +52,12 @@
52
52
  "build:native": "node scripts/build-native.js",
53
53
  "check:release": "node scripts/check-release-metadata.js",
54
54
  "release:prep": "node scripts/release.js",
55
- "test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js",
55
+ "test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js && node test/issue-301-305.test.js",
56
56
  "test:parser": "node test/sql-parser.test.js",
57
57
  "test:btree": "node test/btree.test.js",
58
58
  "test:native": "node test/native.test.js",
59
59
  "test:regress": "node test/regress-5.1.0.js",
60
- "test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js",
60
+ "test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js && node test/issue-301-305.test.js",
61
61
  "test:coverage": "c8 --all --include='lib/**' --exclude='lib/web_ui.js' --reporter=text --reporter=lcov node test/coverage.js",
62
62
  "test:orms": "node examples/orms/run-all.js",
63
63
  "test:dml": "node test/dml-constraints.test.js",
@@ -37,7 +37,10 @@ async function main() {
37
37
  await executeSQL(db, "INSERT INTO t (id,v) VALUES (1,'a')", { safety: false });
38
38
  let dup = null;
39
39
  try { await executeSQL(db, "INSERT INTO t (id,v) VALUES (2,'a')", { safety: false }); } catch (e) { dup = e; }
40
- ok('#138 唯一索引插入重复报错', !!dup && /DUP_ENTRY/.test(dup.message));
40
+ // #305:唯一冲突统一用 MySQL 的 ER_DUP_ENTRY(1062) 模板,
41
+ // 消息形态为 "Duplicate entry 'x' for key 'y'"(不再二次格式化)。
42
+ ok('#138 唯一索引插入重复报错', !!dup && dup.code === 1062 && /Duplicate entry/.test(dup.message),
43
+ dup && dup.message);
41
44
  await executeSQL(db, "INSERT INTO t (id,v) VALUES (2,'b')", { safety: false });
42
45
  let updErr = null;
43
46
  try { await executeSQL(db, "UPDATE t SET v='b' WHERE id=1", { safety: false }); } catch (e) { updErr = e; }
@@ -0,0 +1,165 @@
1
+ /* ---- 回归:#301 / #302 / #303 / #304 / #305 ---- */
2
+ /*
3
+ * #301 HttpJSQL._request 主请求无超时,服务端挂起则 Promise 永久 pending。
4
+ * #302 NeDB 兼容层缺 removeIndex / getIndexes,调用即 TypeError。
5
+ * #303 插件钩子返回的修改后 data 被丢弃,与 PLUGINS.md 承诺不符。
6
+ * #304 Cache.expire 接受负数秒并返回 1,Redis 对负 TTL 报 invalid expire time。
7
+ * #305 更新路径上的唯一冲突错误消息被二次格式化。
8
+ */
9
+ const path = require('path');
10
+ const net = require('net');
11
+ const ROOT = path.join(__dirname, '..');
12
+ const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
13
+ const Cache = require(path.join(ROOT, 'lib/cache.js'));
14
+ const { JSQL: HttpJSQL } = require(path.join(ROOT, 'lib/client.js'));
15
+ const { Datastore } = require(path.join(ROOT, 'lib/nedb_compat.js'));
16
+
17
+ let pass = 0, fail = 0;
18
+ function ok(name, cond, got) {
19
+ if (cond) { pass++; console.log('[OK] ' + name); }
20
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
21
+ }
22
+
23
+ (async () => {
24
+ // ================= #305 唯一冲突错误消息 =================
25
+ const db = new Database(':memory:', { autoSave: false });
26
+ const q = async (sql) => (await executeSQL(db, sql, { safety: false })).rows;
27
+ await q('CREATE TABLE us (id INT PRIMARY KEY, e VARCHAR(10) UNIQUE)');
28
+ await q("INSERT INTO us VALUES (1,'a'),(2,'b')");
29
+
30
+ let sqlErr = null;
31
+ try { await q("UPDATE us SET e='b' WHERE id=1"); } catch (e) { sqlErr = e; }
32
+ ok('SQL UPDATE 唯一冲突报错', !!sqlErr, sqlErr && sqlErr.message);
33
+ ok("错误消息是 'Duplicate entry \\'b\\' for key \\'e\\''(无二次格式化)",
34
+ sqlErr && sqlErr.message === "Duplicate entry 'b' for key 'e'", sqlErr && sqlErr.message);
35
+ ok('错误消息不含字面 %s', sqlErr && !/%s/.test(sqlErr.message), sqlErr && sqlErr.message);
36
+ ok('错误消息不含嵌套的 Duplicate entry',
37
+ sqlErr && (sqlErr.message.match(/Duplicate entry/g) || []).length === 1, sqlErr && sqlErr.message);
38
+
39
+ let apiErr = null;
40
+ try { await db.updateById('us', 1, { e: 'b' }); } catch (e) { apiErr = e; }
41
+ ok('API updateById 唯一冲突报错', !!apiErr, apiErr && apiErr.message);
42
+ ok("API 错误消息同样是 'Duplicate entry \\'b\\' for key \\'e\\''",
43
+ apiErr && apiErr.message === "Duplicate entry 'b' for key 'e'", apiErr && apiErr.message);
44
+ ok('冲突后数据未被破坏',
45
+ JSON.stringify(await q('SELECT * FROM us')) === '[[1,"a"],[2,"b"]]', null);
46
+
47
+ // INSERT 路径消息形态:同样不得二次格式化、不得残留 %s
48
+ let insErr = null;
49
+ try { await q("INSERT INTO us VALUES (3,'b')"); } catch (e) { insErr = e; }
50
+ ok('INSERT 路径唯一冲突报错', !!insErr, insErr && insErr.message);
51
+ ok('INSERT 路径错误消息不含字面 %s', insErr && !/%s/.test(insErr.message), insErr && insErr.message);
52
+ ok('INSERT 路径错误消息不含嵌套的 Duplicate entry',
53
+ insErr && (insErr.message.match(/Duplicate entry/g) || []).length === 1, insErr && insErr.message);
54
+
55
+ // ================= #304 Cache.expire 负数 =================
56
+ const cache = new Cache();
57
+ cache.set('k', 'v');
58
+ let negErr = null;
59
+ try { cache.expire('k', -5); } catch (e) { negErr = e; }
60
+ ok('Cache.expire 负数报 invalid expire time',
61
+ negErr && /invalid expire time/i.test(negErr.message), negErr && negErr.message);
62
+ ok('负数 expire 后键仍有效(未被静默立即失效)', cache.get('k') === 'v', cache.get('k'));
63
+ ok('负数 expire 不改变 TTL', cache.ttl('k') === -1, cache.ttl('k'));
64
+ ok('Cache.expire 正数仍返回 1', cache.expire('k', 100) === 1, null);
65
+ ok('Cache.expire 正数后 TTL 生效', cache.ttl('k') > 0, cache.ttl('k'));
66
+ let fracErr = null;
67
+ try { cache.expire('k', 1.5); } catch (e) { fracErr = e; }
68
+ ok('Cache.expire 小数仍报 not an integer',
69
+ fracErr && /not an integer/i.test(fracErr.message), fracErr && fracErr.message);
70
+ cache.close();
71
+
72
+ // ================= #302 NeDB removeIndex / getIndexes =================
73
+ const ndb = new Datastore();
74
+ await ndb.loadDatabase();
75
+ await ndb.ensureIndex({ fieldName: 'email' });
76
+ ok('NeDB getIndexes 是函数', typeof ndb.getIndexes === 'function', typeof ndb.getIndexes);
77
+ ok('NeDB removeIndex 是函数', typeof ndb.removeIndex === 'function', typeof ndb.removeIndex);
78
+ const idxList = await ndb.getIndexes();
79
+ ok('getIndexes 返回已登记的索引', Array.isArray(idxList) && idxList.length === 1, idxList);
80
+ ok('getIndexes 含 fieldName', idxList[0] && idxList[0].fieldName === 'email', idxList);
81
+ const removed = await ndb.removeIndex('email');
82
+ ok('removeIndex 返回移除数量', removed === 1, removed);
83
+ const after = await ndb.getIndexes();
84
+ ok('removeIndex 后索引列表为空', after.length === 0, after);
85
+
86
+ // callback 风格
87
+ await ndb.ensureIndex({ fieldName: 'a' });
88
+ await ndb.ensureIndex({ fieldName: 'b', unique: true });
89
+ let cbIdx = null;
90
+ await new Promise((res) => ndb.getIndexes((e, list) => { cbIdx = list; res(); }));
91
+ ok('getIndexes 支持 callback 签名', cbIdx && cbIdx.length === 2, cbIdx);
92
+ let cbRemoved = null;
93
+ await new Promise((res) => ndb.removeIndex('a', (e, n) => { cbRemoved = n; res(); }));
94
+ ok('removeIndex 支持 callback 签名', cbRemoved === 1, cbRemoved);
95
+
96
+ // ================= #303 插件钩子写回 =================
97
+ const db2 = new Database(':memory:', { autoSave: false });
98
+ await db2.createTable('t', { id: { type: 'integer', primaryKey: true }, name: { type: 'string' } });
99
+ db2.use({
100
+ name: 'tagger',
101
+ hooks: {
102
+ beforeInsert(table, arr) { return arr.map(r => ({ ...r, via: 'hook' })); },
103
+ },
104
+ });
105
+ await db2.insert('t', { name: 'a' });
106
+ const rows = await db2.find('t', {});
107
+ ok("beforeInsert 返回的修改后 data 生效(via='hook' 落库)",
108
+ rows.length === 1 && rows[0].via === 'hook', rows);
109
+
110
+ // 标量参数写回:beforeUpdate 返回改写后的 data
111
+ await db2.insert('t', { id: 2, name: 'b' });
112
+ db2.use({
113
+ name: 'updater',
114
+ hooks: {
115
+ beforeUpdate(table, id, data) { return { ...data, name: 'patched' }; },
116
+ },
117
+ });
118
+ await db2.updateById('t', 2, { name: 'x' });
119
+ const after2 = await db2.find('t', {});
120
+ ok('beforeUpdate 返回的修改后 data 生效',
121
+ after2.some(r => r.id === 2 && r.name === 'patched'), after2);
122
+
123
+ // 返回 false 仍然中止
124
+ const db3 = new Database(':memory:', { autoSave: false });
125
+ await db3.createTable('t3', { id: { type: 'integer', primaryKey: true }, name: { type: 'string' } });
126
+ db3.use({
127
+ name: 'veto',
128
+ hooks: { beforeInsert() { return false; } },
129
+ });
130
+ await db3.insert('t3', { name: 'a' });
131
+ const rows3 = await db3.find('t3', {});
132
+ ok('beforeInsert 返回 false 仍中止写入', rows3.length === 0, rows3);
133
+
134
+ // 返回 undefined 不影响数据
135
+ const db4 = new Database(':memory:', { autoSave: false });
136
+ await db4.createTable('t4', { id: { type: 'integer', primaryKey: true }, name: { type: 'string' } });
137
+ db4.use({ name: 'noop', hooks: { beforeInsert(table, arr) { return undefined; } } });
138
+ await db4.insert('t4', { name: 'a' });
139
+ const rows4 = await db4.find('t4', {});
140
+ ok('beforeInsert 返回 undefined 不影响写入',
141
+ rows4.length === 1 && rows4[0].name === 'a', rows4);
142
+
143
+ // ================= #301 HttpJSQL 超时 =================
144
+ const srv = net.createServer(() => { /* 故意不写任何响应 */ });
145
+ await new Promise((r) => srv.listen(0, '127.0.0.1', r));
146
+ const port = srv.address().port;
147
+ const client = new HttpJSQL({ port, host: '127.0.0.1', timeoutMs: 300 });
148
+ let settled = false;
149
+ let rejectMsg = null;
150
+ client.find('t', { a: 1 })
151
+ .then(() => { rejectMsg = null; })
152
+ .catch(e => { rejectMsg = e.message; })
153
+ .finally(() => { settled = true; });
154
+ await new Promise((r) => setTimeout(r, 900));
155
+ ok('服务端挂起时请求超时并 reject(不再永久 pending)', settled, settled);
156
+ ok('超时错误消息含「超时」字样',
157
+ rejectMsg && /超时|timeout/i.test(rejectMsg), rejectMsg);
158
+ srv.close();
159
+
160
+ console.log(`\n${pass} passed, ${fail} failed`);
161
+ process.exit(fail === 0 ? 0 : 1);
162
+ })().catch(e => {
163
+ console.log('[FAIL] unexpected exception: ' + (e.stack || e).split('\n').slice(0, 4).join('\n'));
164
+ process.exit(1);
165
+ });
@@ -429,12 +429,19 @@ async function main() {
429
429
  const dupErrMsg = async (sql) => {
430
430
  try { await run(sql); return null; } catch (e) { return e.message; }
431
431
  };
432
+ const dupErrCode = async (sql) => {
433
+ try { await run(sql); return null; } catch (e) { return e.code; }
434
+ };
432
435
  await run('CREATE TABLE u (id SERIAL PRIMARY KEY, email TEXT UNIQUE, nick TEXT UNIQUE)');
433
436
  await run("INSERT INTO u (email, nick) VALUES ('a@x.com', 'a')");
437
+ // #305:唯一冲突统一用 MySQL 的 ER_DUP_ENTRY(1062) 模板,
438
+ // 消息形态为 "Duplicate entry 'x' for key 'y'"(不再二次格式化)。
434
439
  ok('唯一列重复 → ER_DUP_ENTRY',
435
- /ER_DUP_ENTRY/.test(await dupErrMsg("INSERT INTO u (email, nick) VALUES ('a@x.com', 'z')") || ''));
440
+ await dupErrCode("INSERT INTO u (email, nick) VALUES ('a@x.com', 'z')") === 1062);
441
+ ok('唯一列重复消息形态正确',
442
+ /Duplicate entry 'a@x\.com' for key 'email'/.test(await dupErrMsg("INSERT INTO u (email, nick) VALUES ('a@x.com', 'z')") || ''));
436
443
  ok('批内唯一重复 → ER_DUP_ENTRY',
437
- /ER_DUP_ENTRY/.test(await dupErrMsg("INSERT INTO u (email, nick) VALUES ('b@x.com', 'n1'), ('c@x.com', 'n1')") || ''));
444
+ await dupErrCode("INSERT INTO u (email, nick) VALUES ('b@x.com', 'n1'), ('c@x.com', 'n1')") === 1062);
438
445
  const r1 = await run('SELECT id FROM u');
439
446
  ok('冲突后仍只有 1 行', r1.rows.length === 1, r1.rows);
440
447
  await run("INSERT INTO u (email, nick) VALUES (NULL, 'x'), (NULL, 'y')");