jsql-neo 6.8.11 → 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.11** — 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.11 — 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
@@ -42,6 +42,26 @@ function bsonDocument(obj) {
42
42
  continue;
43
43
  }
44
44
  if (typeof v === 'number') {
45
+ // #284:整数按 BSON 规范编 Int32(0x10) / Int64(0x12),只有真正的浮点
46
+ // 才用 Double(0x01)。此前一律编 double,导致线上类型与驱动预期不符
47
+ // ($type:'int' 永远匹配不到),且 int32 本可 4 字节却占了 8 字节。
48
+ if (Number.isInteger(v)) {
49
+ if (v >= -2147483648 && v <= 2147483647) {
50
+ const b = Buffer.alloc(4);
51
+ b.writeInt32LE(v, 0);
52
+ body = Buffer.concat([body, Buffer.from([0x10]), name, Buffer.from([0]), b]);
53
+ } else if (Number.isSafeInteger(v)) {
54
+ const b = Buffer.alloc(8);
55
+ b.writeBigInt64LE(BigInt(v), 0);
56
+ body = Buffer.concat([body, Buffer.from([0x12]), name, Buffer.from([0]), b]);
57
+ } else {
58
+ // 超出安全整数范围:double 已是唯一无损的表示
59
+ const b = Buffer.alloc(8);
60
+ b.writeDoubleLE(v, 0);
61
+ body = Buffer.concat([body, Buffer.from([0x01]), name, Buffer.from([0]), b]);
62
+ }
63
+ continue;
64
+ }
45
65
  const b = Buffer.alloc(8);
46
66
  b.writeDoubleLE(v, 0);
47
67
  body = Buffer.concat([body, Buffer.from([0x01]), name, Buffer.from([0]), b]);
@@ -65,9 +85,16 @@ function bsonDocument(obj) {
65
85
  continue;
66
86
  }
67
87
  if (Buffer.isBuffer(v)) {
88
+ // #285:BSON Binary 布局 = type 0x05 + 字段名 + int32 长度 +
89
+ // **1 字节 subtype** + length 字节数据。
90
+ // 此前写成 Buffer.from([0, 0])(两个字节),比规范多 1 字节 ——
91
+ // 解码端按规范只跳 1 个 subtype 字节,于是冗余 0x00 被当成数据首字节,
92
+ // 整个字节流错位([1,2,3,4] 读回成 [0,0,1,2]),且后续字段解析失步。
68
93
  const lenBuf = Buffer.alloc(4);
69
94
  lenBuf.writeInt32LE(v.length, 0);
70
- body = Buffer.concat([body, Buffer.from([0x05]), name, Buffer.from([0]), lenBuf, Buffer.from([0, v.buffer ? 0 : 0]), v]);
95
+ const subtype = (v.subtype !== undefined && v.subtype !== null) ? (v.subtype & 0xff) : 0;
96
+ body = Buffer.concat([body, Buffer.from([0x05]), name, Buffer.from([0]), lenBuf,
97
+ Buffer.from([subtype]), v]);
71
98
  continue;
72
99
  }
73
100
  if (v instanceof Date) {
@@ -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
@@ -3787,20 +3787,84 @@ function bigintExactArith(l, r, op) {
3787
3787
  * 恒小,于是 ORDER BY col DESC 时 NULL 跑到最前,与普通 SELECT 的 ORDER BY
3788
3788
  * 不一致;抽成一个函数后两条排序路径不会再各写一套。
3789
3789
  */
3790
+ /**
3791
+ * SQL 比较用的类型归一(Issue #291 / #292)。
3792
+ *
3793
+ * MySQL 8.0(11.2 Type Conversion in Expression Evaluation):
3794
+ * "If one operand is a number and the other is a string, the string is
3795
+ * converted to a number."
3796
+ *
3797
+ * 因此混合类型比较时,若一侧是数值、另一侧是可解析为有限数值的字符串,
3798
+ * 应按数值比较,而不是退化成字典序。
3799
+ *
3800
+ * 返回归一后的值;两侧无法按数值统一时返回 undefined(调用方回退原逻辑)。
3801
+ */
3802
+ function sqlNumericCoerce(v) {
3803
+ if (typeof v === 'number') return Number.isFinite(v) ? v : undefined;
3804
+ if (typeof v === 'bigint') return undefined; // BigInt 与 number 混用另有口径
3805
+ if (typeof v === 'boolean') return v ? 1 : 0;
3806
+ if (typeof v === 'string') {
3807
+ const t = v.trim();
3808
+ if (t === '') return undefined;
3809
+ // 必须整串都是数字(可含小数/指数),否则 'abc' 不能当 0
3810
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(t)) return undefined;
3811
+ const n = Number(t);
3812
+ return Number.isFinite(n) ? n : undefined;
3813
+ }
3814
+ return undefined;
3815
+ }
3816
+
3817
+ /**
3818
+ * 分组键 / 窗口分区键的归一化(Issue #291)。
3819
+ *
3820
+ * 分组按 SQL 比较规则分组:数字 1 与字符串 '1' 是同一个键值,必须落在
3821
+ * 同一组。此前直接对原始 JS 值做 JSON.stringify,两个键文本不同 →
3822
+ * 被拆成两个伪组,COUNT(*) 偏小、SUM/AVG 被割裂。
3823
+ *
3824
+ * 归一规则:
3825
+ * · 字符串能解析为有限数值 → 折叠为数值表示(与数字同键)
3826
+ * · 布尔 → 0/1
3827
+ * · 其余原样
3828
+ */
3829
+ function sqlGroupKeyNormalize(v) {
3830
+ if (v === null || v === undefined) return v;
3831
+ if (typeof v === 'boolean') return v ? 1 : 0;
3832
+ if (typeof v === 'string') {
3833
+ const n = sqlNumericCoerce(v);
3834
+ if (n !== undefined) return n;
3835
+ return v;
3836
+ }
3837
+ return v;
3838
+ }
3839
+
3790
3840
  function compareSqlValues(av, bv, dir) {
3791
- const desc = dir === 'desc';
3792
- if (av === bv) return 0;
3793
- const aNull = av === null || av === undefined;
3794
- const bNull = bv === null || bv === undefined;
3795
- if (aNull || bNull) {
3796
- if (aNull && bNull) return 0;
3797
- const r = aNull ? -1 : 1;
3841
+ const desc = dir === 'desc';
3842
+ if (av === bv) return 0;
3843
+ const aNull = av === null || av === undefined;
3844
+ const bNull = bv === null || bv === undefined;
3845
+ if (aNull || bNull) {
3846
+ if (aNull && bNull) return 0;
3847
+ const r = aNull ? -1 : 1;
3848
+ return desc ? -r : r;
3849
+ }
3850
+ let r;
3851
+ if (typeof av === 'number' && typeof bv === 'number') {
3852
+ r = av - bv;
3853
+ } else {
3854
+ // #292:混合 number/string 时先按 SQL 规则归一为数值比较。
3855
+ // 此前只要一侧是字符串就退化成字典序,于是 '10' 与 2 的排序反了
3856
+ // (实际输出 1, 10, 2;MySQL 是 1, 2, 10)。
3857
+ const na = sqlNumericCoerce(av);
3858
+ const nb = sqlNumericCoerce(bv);
3859
+ if (na !== undefined && nb !== undefined
3860
+ && (typeof av !== 'string' || typeof bv !== 'string' || na !== nb)) {
3861
+ // 两侧都是字符串且归一后相等(如 '1' 与 '1.0')→ 视为相等
3862
+ r = na === nb ? 0 : (na < nb ? -1 : 1);
3863
+ } else {
3864
+ r = String(av) < String(bv) ? -1 : String(av) > String(bv) ? 1 : 0;
3865
+ }
3866
+ }
3798
3867
  return desc ? -r : r;
3799
- }
3800
- const r = typeof av === 'number' && typeof bv === 'number'
3801
- ? av - bv
3802
- : (String(av) < String(bv) ? -1 : String(av) > String(bv) ? 1 : 0);
3803
- return desc ? -r : r;
3804
3868
  }
3805
3869
 
3806
3870
  function resolveOperand(operand, row, ctx) {
@@ -6783,7 +6847,11 @@ class SQLExecutor {
6783
6847
  const v = d[col];
6784
6848
  if (v === undefined || v === null) continue; // UNIQUE 允许多个 NULL
6785
6849
  const s = String(v);
6786
- 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
+ }
6787
6855
  used.add(s);
6788
6856
  }
6789
6857
  }
@@ -9071,7 +9139,7 @@ class SQLExecutor {
9071
9139
  const buckets = new Map();
9072
9140
  rows.forEach((r, idx) => {
9073
9141
  const key = partBy.length
9074
- ? partBy.map(p => JSON.stringify(resolveOperand(p, r, this.ctx))).join('')
9142
+ ? partBy.map(p => JSON.stringify(sqlGroupKeyNormalize(resolveOperand(p, r, this.ctx)))).join('')
9075
9143
  : '';
9076
9144
  if (!buckets.has(key)) buckets.set(key, []);
9077
9145
  buckets.get(key).push(idx);
@@ -9623,21 +9691,28 @@ class SQLExecutor {
9623
9691
  // 表达式分组(#51):直接对原始行求值表达式
9624
9692
  if (g && typeof g === 'object') {
9625
9693
  const v = resolveOperand(g, row, this.ctx);
9626
- return typeof v === 'bigint' ? v.toString() + 'n' : v;
9694
+ // #291:分组键按 SQL 比较规则归一 —— 数字 1 与字符串 '1'
9695
+ // 是同一个键值,必须落在同一组。
9696
+ const nv = sqlGroupKeyNormalize(v);
9697
+ return typeof nv === 'bigint' ? nv.toString() + 'n' : nv;
9627
9698
  }
9628
9699
  const key = String(g).toLowerCase();
9629
9700
  if (aliases[key]) {
9630
9701
  // 优先用行中已有的 alias 值(投影后才有),没有则尝试从原始列取值
9631
- if (row[key] !== undefined) return row[key];
9702
+ if (row[key] !== undefined) return sqlGroupKeyNormalize(row[key]);
9632
9703
  // alias → 原始列名 的映射(如 b → a),从原始行取该列的值
9633
- if (aliasToCol[key]) return resolveOperand({ type: 'column', name: aliasToCol[key] }, row, this.ctx);
9704
+ if (aliasToCol[key]) {
9705
+ return sqlGroupKeyNormalize(resolveOperand({ type: 'column', name: aliasToCol[key] }, row, this.ctx));
9706
+ }
9634
9707
  if (aliasExpr[key]) {
9635
9708
  const v = resolveOperand(aliasExpr[key], row, this.ctx);
9636
- return typeof v === 'bigint' ? v.toString() + 'n' : v;
9709
+ const nv = sqlGroupKeyNormalize(v);
9710
+ return typeof nv === 'bigint' ? nv.toString() + 'n' : nv;
9637
9711
  }
9638
9712
  return row[key]; // row[key] 为 undefined,但保持一致
9639
9713
  }
9640
- return resolveOperand({ type: 'column', name: g }, row, this.ctx);
9714
+ // #291:列分组的键同样归一
9715
+ return sqlGroupKeyNormalize(resolveOperand({ type: 'column', name: g }, row, this.ctx));
9641
9716
  }));
9642
9717
  if (!groups.has(key)) groups.set(key, []);
9643
9718
  groups.get(key).push(row);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.8.11",
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",
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",
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,154 @@
1
+ /* ---- 回归:#284 / #285 / #291 / #292 (+ #290 位运算) ---- */
2
+ /*
3
+ * #284 Mongo BSON 编码把所有整数都写成 Double(0x01),从不写 Int32(0x10)。
4
+ * #285 Mongo BSON Binary(0x05) 编码多写一个 subtype 字节,往返损坏错位。
5
+ * #291 GROUP BY 键未做 SQL 类型归一:数字 1 与字符串 '1' 被拆成两个组。
6
+ * #292 ORDER BY 混合 number/string 时退化为字典序,数值顺序排错。
7
+ * #290 位非 `~` 按 32 位有符号整数取反,与 MySQL 的 64 位无符号语义不符。
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 { createMongoServer, bsonDocument, bsonReadDocument } = require(path.join(ROOT, 'lib/mongo_server.js'));
14
+
15
+ let pass = 0, fail = 0;
16
+ function ok(name, cond, got) {
17
+ if (cond) { pass++; console.log('[OK] ' + name); }
18
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
19
+ }
20
+
21
+ function mongoOpMsg(doc) {
22
+ const p = bsonDocument(doc);
23
+ const h = Buffer.alloc(16);
24
+ h.writeInt32LE(16 + 4 + 1 + p.length, 0);
25
+ h.writeInt32LE(1, 4); h.writeInt32LE(0, 8); h.writeInt32LE(2013, 12);
26
+ return Buffer.concat([h, Buffer.alloc(4), Buffer.from([0]), p]);
27
+ }
28
+ function mongoCall(srv, doc) {
29
+ return new Promise((resolve, reject) => {
30
+ const sock = net.connect(srv._server.address().port, '127.0.0.1', () => sock.write(mongoOpMsg(doc)));
31
+ const chunks = [];
32
+ sock.on('error', reject);
33
+ sock.on('data', (c) => {
34
+ chunks.push(c);
35
+ const buf = Buffer.concat(chunks);
36
+ if (buf.length >= 16 && buf.length >= buf.readInt32LE(0)) {
37
+ try { resolve({ raw: buf, doc: bsonReadDocument(buf.slice(21), 0).value }); }
38
+ catch (e) { reject(e); }
39
+ sock.end();
40
+ }
41
+ });
42
+ });
43
+ }
44
+
45
+ (async () => {
46
+ // ================= #284 BSON 整数类型 =================
47
+ const enc = bsonDocument({ n: 30 });
48
+ const hex = enc.toString('hex');
49
+ // size(4) + type(1) + 'n'(2) + int32(4)
50
+ ok("编码 {n:30} 用 Int32(type byte 0x10)", hex.includes('106e00'), hex);
51
+ ok("Int32 只占 4 字节(文档总长 12)", enc.readInt32LE(0) === 12, enc.readInt32LE(0));
52
+
53
+ const encF = bsonDocument({ n: 2.5 });
54
+ ok("浮点仍用 Double(type byte 0x01)", encF.toString('hex').includes('016e00'), encF.toString('hex'));
55
+
56
+ const encBig = bsonDocument({ n: 3000000000 });
57
+ ok("超 int32 范围用 Int64(type byte 0x12)", encBig.toString('hex').includes('126e00'), encBig.toString('hex'));
58
+
59
+ // 端到端:线上回包的 type byte
60
+ const msrv = createMongoServer({ dataDir: ':memory:' });
61
+ await new Promise((r) => msrv.listen(r));
62
+ await mongoCall(msrv, { insert: 'it', documents: [{ n: 30 }], $db: 'test' });
63
+ const r1 = await mongoCall(msrv, { find: 'it', filter: {}, $db: 'test' });
64
+ const i1 = r1.raw.indexOf(Buffer.from('n\0'));
65
+ const typeByte = r1.raw.slice(i1 - 1, i1).toString('hex');
66
+ ok('线上回包 n 的 type byte = 10(int32)', typeByte === '10', typeByte);
67
+ ok('回读值仍是 30', r1.doc.cursor.firstBatch[0].n === 30, r1.doc.cursor.firstBatch[0].n);
68
+
69
+ // ================= #285 BSON Binary 往返 =================
70
+ const orig = Buffer.from([1, 2, 3, 4]);
71
+ const bEnc = bsonDocument({ data: orig });
72
+ const bHex = bEnc.toString('hex');
73
+ // size(4) + type(1) + 'data\0'(5) + len(4) + subtype(1) + data(4) + 结束符(1) = 20
74
+ ok('Binary 编码长度正确(20 字节)', bEnc.readInt32LE(0) === 20, bEnc.readInt32LE(0));
75
+ ok('Binary 只写 1 个 subtype 字节', /05646174610004000000 00 01020304/.test(bHex.replace(/ /g, ''))
76
+ || bHex.includes('056461746100040000000001020304'), bHex);
77
+ const bDec = bsonReadDocument(bEnc, 0).value;
78
+ ok('Binary 往返逐字节相等', Buffer.from(bDec.data).equals(orig), Buffer.from(bDec.data));
79
+
80
+ // 多字段文档:Binary 之后的字段不能解析失步
81
+ const multi = bsonDocument({ data: orig, tail: 7 });
82
+ const mDec = bsonReadDocument(multi, 0).value;
83
+ ok('Binary 之后的字段仍能正确解析', mDec.tail === 7, mDec);
84
+ ok('多字段文档里 Binary 数据完好', Buffer.from(mDec.data).equals(orig), Buffer.from(mDec.data));
85
+
86
+ // 端到端往返
87
+ await mongoCall(msrv, { insert: 'bin', documents: [{ _id: 'b', data: orig }], $db: 'test' });
88
+ const r2 = await mongoCall(msrv, { find: 'bin', filter: {}, $db: 'test' });
89
+ const got = Buffer.from(r2.doc.cursor.firstBatch[0].data);
90
+ ok('服务端往返二进制数据完好', got.equals(orig), got);
91
+
92
+ msrv.close();
93
+
94
+ // ================= #291 GROUP BY 键归一 =================
95
+ const db = new Database(':memory:', { autoSave: false });
96
+ const q = async (sql) => (await executeSQL(db, sql, { safety: false })).rows;
97
+
98
+ await q('CREATE TABLE m (k TEXT, v INT)');
99
+ await q("INSERT INTO m VALUES ('1',10),(1,20),('2',30),(2,40)");
100
+ const grouped = await q('SELECT k, COUNT(*), SUM(v) FROM m GROUP BY k ORDER BY k');
101
+ ok("GROUP BY 把 '1' 与 1 合并成 1 组", grouped.length === 2, grouped);
102
+ ok("GROUP BY '1' 组 COUNT=2, SUM=30",
103
+ JSON.stringify(grouped[0]) === JSON.stringify(['1', 2, 30]), grouped);
104
+ ok("GROUP BY '2' 组 COUNT=2, SUM=70",
105
+ JSON.stringify(grouped[1]) === JSON.stringify(['2', 2, 70]), grouped);
106
+
107
+ // 纯数值分组不回归
108
+ await q('CREATE TABLE m2 (k INT, v INT)');
109
+ await q('INSERT INTO m2 VALUES (1,10),(1,20),(2,30)');
110
+ const g2 = await q('SELECT k, COUNT(*), SUM(v) FROM m2 GROUP BY k ORDER BY k');
111
+ ok('纯数值 GROUP BY 不回归',
112
+ JSON.stringify(g2) === JSON.stringify([[1, 2, 30], [2, 1, 30]]), g2);
113
+
114
+ // ================= #292 ORDER BY 混合类型 =================
115
+ await q('CREATE TABLE s (k TEXT)');
116
+ await q("INSERT INTO s VALUES ('10'),(2),('1')");
117
+ const ordered = await q('SELECT k FROM s ORDER BY k');
118
+ const keys = ordered.map(r => r[0]);
119
+ ok("ORDER BY 混合类型按数值排序:1, 2, 10",
120
+ keys.length === 3 && Number(keys[0]) === 1 && Number(keys[1]) === 2 && Number(keys[2]) === 10, keys);
121
+
122
+ // 纯字符串排序仍按字典序
123
+ await q('CREATE TABLE s2 (k TEXT)');
124
+ await q("INSERT INTO s2 VALUES ('b'),('a'),('c')");
125
+ const o2 = await q('SELECT k FROM s2 ORDER BY k');
126
+ ok('纯字符串 ORDER BY 仍按字典序',
127
+ JSON.stringify(o2.map(r => r[0])) === JSON.stringify(['a', 'b', 'c']), o2);
128
+
129
+ // 非数字字符串仍按字典序(不能被误当数值)
130
+ await q('CREATE TABLE s3 (k TEXT)');
131
+ await q("INSERT INTO s3 VALUES ('b'),('10'),('a')");
132
+ const o3 = await q('SELECT k FROM s3 ORDER BY k');
133
+ ok("非数字字符串仍按字典序('10' < 'a' < 'b')",
134
+ JSON.stringify(o3.map(r => r[0])) === JSON.stringify(['10', 'a', 'b']), o3);
135
+
136
+ // ================= #290 位运算 64 位无符号 =================
137
+ const one = async (sql) => (await q(sql))[0][0];
138
+ ok("~0 = 18446744073709551615(MySQL 64 位无符号)",
139
+ String(await one('SELECT ~0')) === '18446744073709551615', null);
140
+ ok("~5 = 18446744073709551610",
141
+ String(await one('SELECT ~5')) === '18446744073709551610', null);
142
+ ok('5 & ~1 = 4', await one('SELECT 5 & ~1') === 4, null);
143
+ ok('12 & 10 = 8', await one('SELECT 12 & 10') === 8, null);
144
+ ok('12 | 10 = 14', await one('SELECT 12 | 10') === 14, null);
145
+ ok('12 ^ 10 = 6', await one('SELECT 12 ^ 10') === 6, null);
146
+ ok('1 << 63 仍是精确 BigInt',
147
+ String(await one('SELECT 1 << 63')) === '9223372036854775808', null);
148
+
149
+ console.log(`\n${pass} passed, ${fail} failed`);
150
+ process.exit(fail === 0 ? 0 : 1);
151
+ })().catch(e => {
152
+ console.log('[FAIL] unexpected exception: ' + (e.stack || e).split('\n').slice(0, 4).join('\n'));
153
+ process.exit(1);
154
+ });
@@ -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')");