jsql-neo 6.8.25 → 6.8.26

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.25** — 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.26** — 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/bin/jsql CHANGED
@@ -241,7 +241,13 @@ const cli = (yaggs || require('./yaggs-fallback').buildYaggsFallback(_pkg))({
241
241
  if (!table || !outFile) throw new Error('Usage: jsql export <table> <file.json|csv> [--db <path>]');
242
242
  const db = new Database(argv.db || './db.json', { autoSave: false });
243
243
  await db.loadDatabase ? db.loadDatabase() : null;
244
- const bytes = await migrate.exportToFile(db, table, outFile);
244
+ let bytes;
245
+ try {
246
+ bytes = await migrate.exportToFile(db, table, outFile);
247
+ } finally {
248
+ // #355:CLI 是一次性进程,不 close 会留下 .lock,30 秒内第二条命令直接撞锁。
249
+ if (typeof db.close === 'function') await db.close();
250
+ }
245
251
  if (argv.json) console.log(JSON.stringify({ ok: true, table, file: outFile, bytes }));
246
252
  else console.log(`Exported '${table}' (${bytes} bytes) to ${outFile}`);
247
253
  } catch (e) { fail(e); }
@@ -260,6 +266,7 @@ const cli = (yaggs || require('./yaggs-fallback').buildYaggsFallback(_pkg))({
260
266
  await db.loadDatabase ? db.loadDatabase() : null;
261
267
  const ext = path.extname(file).toLowerCase();
262
268
  let result;
269
+ try {
263
270
  if (ext === '.sql') {
264
271
  result = await migrate.importDumpFile(db, file, { strict: !!argv.strict });
265
272
  } else if (ext === '.json') {
@@ -273,6 +280,10 @@ const cli = (yaggs || require('./yaggs-fallback').buildYaggsFallback(_pkg))({
273
280
  } else {
274
281
  throw new Error('Unsupported file type: ' + ext);
275
282
  }
283
+ } finally {
284
+ // #355:导入完成即释放锁,否则连续两条 CLI 命令会互相撞 .lock。
285
+ if (typeof db.close === 'function') await db.close();
286
+ }
276
287
  if (argv.json) {
277
288
  console.log(JSON.stringify({ ok: true, ...result }));
278
289
  } else {
package/index.d.ts CHANGED
@@ -348,8 +348,7 @@ declare namespace JSQLNeo {
348
348
  prepare(sql: string): PreparedStatement;
349
349
  query(sql: string, paramsOrOpts?: unknown[] | SQLOptions, opts?: SQLOptions): Promise<SQLResult>;
350
350
  update(table: string, filter: Record<string, unknown>, data: Record<string, unknown>): Promise<number>;
351
- remove(table: string, filter: Record<string, unknown>): Promise<number>;
352
- findOne(table: string, filter?: Record<string, unknown>): Promise<Row | null>;
351
+ removeWhere(table: string, filter: Record<string, unknown>): Promise<number>;
353
352
  count(table: string): Promise<number>;
354
353
  getTables(): Promise<string[]>;
355
354
  dropTable(name: string): Promise<void>;
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.8.25 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.8.26 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
@@ -129,8 +129,23 @@ function injectMySQLCompat(mod) {
129
129
  return touched;
130
130
  }
131
131
 
132
+ // #327:公共导出的 JSQL 此前直接挂纯内存的 WasmClient.JSQL,`path`/`mode`
133
+ // 被静默丢弃 —— README 主推的 `new JSQL({ path, mode: 'disk' })` 进程退出即全丢。
134
+ // 这里保持构造签名与 API 不变:disk/持久化模式且存在带落盘能力的回退实现时,
135
+ // 转交该实现;其余情况仍走原 WASM/JS 引擎,不统一两套引擎。
136
+ function JSQL(opts) {
137
+ const o = (typeof opts === 'string') ? { path: opts } : (opts || {});
138
+ const wantDisk = !!o.path && o.path !== ':memory:' && (o.mode || 'disk') !== 'memory';
139
+ if (wantDisk && NativeClient._DiskFallbackJSQL) {
140
+ return new NativeClient._DiskFallbackJSQL(opts);
141
+ }
142
+ return new WasmClient.JSQL(opts);
143
+ }
144
+ // 保留原型引用习惯(instanceof 链与原 WASM 实现一致)
145
+ JSQL.prototype = WasmClient.JSQL.prototype;
146
+
132
147
  module.exports = {
133
- JSQL: WasmClient.JSQL,
148
+ JSQL,
134
149
  // jsql 1.0.0 怀旧兼容层(同步 createTable/dropTable + db.<表名> 属性)
135
150
  // 用法:const { Database } = require('jsql-neo/compat/v1');
136
151
  compatV1: require('./lib/compat/v1'),
package/lib/cache.js CHANGED
@@ -17,7 +17,15 @@ class Cache {
17
17
  this._startTTLCleaner();
18
18
  }
19
19
 
20
- set(key, value) { this._getData().set(String(key), String(value)); this._dirty = true; return 'OK'; }
20
+ set(key, value) {
21
+ const k = String(key);
22
+ this._getData().set(k, String(value));
23
+ // #382:普通 SET 必须清除既有 TTL(Redis 语义),否则新值会继承旧过期时间,
24
+ // 甚至已过期但尚未清理的键被“复活”。
25
+ this._getExpires().delete(k);
26
+ this._dirty = true;
27
+ return 'OK';
28
+ }
21
29
  get(key) {
22
30
  const k = String(key);
23
31
  if (this._isExpired(k)) return null;
package/lib/database.js CHANGED
@@ -1198,6 +1198,32 @@ class Database {
1198
1198
  * 表改名后重写所有子表的外键引用(Issue #246)。
1199
1199
  * 把 fk.table 从旧表名改成新表名,并同步 _indexRegistry 里的登记。
1200
1200
  */
1201
+ _rewriteViewTableRefs(oldName, newName) {
1202
+ const oldLower = String(oldName).toLowerCase();
1203
+ const walk = (node) => {
1204
+ if (!node || typeof node !== 'object') return false;
1205
+ let changed = false;
1206
+ if (Array.isArray(node)) {
1207
+ for (const item of node) if (walk(item)) changed = true;
1208
+ return changed;
1209
+ }
1210
+ for (const key of Object.keys(node)) {
1211
+ const val = node[key];
1212
+ if (key === 'table' && typeof val === 'string' && val.toLowerCase() === oldLower) {
1213
+ node[key] = newName;
1214
+ changed = true;
1215
+ } else if (walk(val)) {
1216
+ changed = true;
1217
+ }
1218
+ }
1219
+ return changed;
1220
+ };
1221
+ if (!this._views) return;
1222
+ for (const view of Object.values(this._views)) {
1223
+ if (view && view.select) walk(view.select);
1224
+ }
1225
+ }
1226
+
1201
1227
  _rewriteForeignKeyRefs(oldName, newName) {
1202
1228
  const oldKey = String(oldName).toLowerCase();
1203
1229
  for (const table of Object.values(this._tables)) {
@@ -1286,6 +1312,18 @@ class Database {
1286
1312
  // MySQL 8.0 的 RENAME TABLE 同样会更新数据字典里的外键引用。
1287
1313
  this._rewriteForeignKeyRefs(oldName, newName);
1288
1314
 
1315
+ // #385:视图 AST 里快照了建视图时的基表名,RENAME TABLE 不重写 → 视图悬空。
1316
+ this._rewriteViewTableRefs(oldName, newName);
1317
+
1318
+ // #358:CREATE INDEX 时按索引名登记了 索引名 → { table, columns }。
1319
+ // RENAME TABLE 只改 _tables 键,登记表还指旧名 → 之后无条件 DROP INDEX
1320
+ // 按名反查不到表,索引删不掉且登记项残留。
1321
+ if (this._indexRegistry && typeof this._indexRegistry.forEach === 'function') {
1322
+ for (const entry of this._indexRegistry.values()) {
1323
+ if (entry && String(entry.table).toLowerCase() === String(oldName).toLowerCase()) entry.table = newName;
1324
+ }
1325
+ }
1326
+
1289
1327
  this._tableNames.delete(oldName);
1290
1328
  this._tableNames.add(newName);
1291
1329
 
@@ -2489,35 +2527,36 @@ class Database {
2489
2527
  return this.findByIds(tableName, ids);
2490
2528
  }
2491
2529
 
2492
- async count(tableName) {
2530
+ async count(tableName, filter) {
2493
2531
  const table = this._ensureTable(tableName);
2494
2532
  if (!table) throw this._noSuchTable(tableName);
2495
- if (!(await this._runHooks('beforeCount', [tableName]))) return undefined;
2533
+ if (!(await this._runHooks('beforeCount', [tableName, filter]))) return 0; // #383 钩子中止按数字契约兜底
2496
2534
  // P1-4: 软删除模式下只统计可见行
2497
- const n = table._softDelete ? table._getVisibleRows().length : table._rows.length;
2535
+ // #334:api-reference.md 承诺 count(table, filter) 按条件计数,第二参数此前被丢弃。
2536
+ // 这里复用 find 的过滤路径(_applyFilterOptimized),保证与 find 语义一致。
2537
+ const visible = table._softDelete ? table._getVisibleRows() : table._rows;
2538
+ const n = filter && Object.keys(filter).length
2539
+ ? table._applyFilterOptimized(visible, filter).length
2540
+ : visible.length;
2498
2541
  this._touchTable(tableName);
2499
2542
  await this._runHooks('afterCount', [tableName, n]);
2500
2543
  return n;
2501
2544
  }
2502
2545
 
2503
- async updateById(tableName, id, data) {
2504
- const table = this._ensureTable(tableName);
2505
- if (!table) throw this._noSuchTable(tableName);
2506
- // #303:beforeUpdate 可返回「修改后 data」(PLUGINS.md 契约),
2507
- // 写回后必须用改写后的值继续。
2508
- const hookArgs = [tableName, id, data];
2509
- if (!(await this._runHooks('beforeUpdate', hookArgs))) return;
2510
- data = hookArgs[2];
2511
- // P1-9: updateById 绕过类型校验——先校验再更新
2546
+ /**
2547
+ * #418:单条更新的公共写入内核(类型/NOT NULL/唯一/外键/CHECK 校验 + 索引同步),
2548
+ * 供 updateById / updateByIds 复用。批量路径此前只跑 CHECK 就 Object.assign,
2549
+ * 绕过了类型、NOT NULL、唯一冲突、外键校验与主键/唯一索引维护,导致 pkIndex
2550
+ * 与行不一致、非法约束数据落库。返回 { row, validated };行不存在或已软删返回 null。
2551
+ */
2552
+ _applyUpdateToRow(table, id, data) {
2553
+ // P1-9: 先做类型校验再更新
2554
+
2512
2555
  const validated = table._validateDataTypes({ ...data }, true);
2513
2556
  const row = this._resolveId(table, id);
2514
2557
  // P1-4: 软删除行不可更新
2515
- if (!row || row._deleted) return { ok: false, error: 'not found' };
2558
+ if (!row || row._deleted) return null;
2516
2559
  // 改主键/唯一列时要先确认新值不与其它行冲突。
2517
- // 此前直接 Object.assign,导致
2518
- // UPDATE t SET id = 1 WHERE id = 2 (t 已有 id=1)
2519
- // 静默产生两行同主键 —— 主键索引只留一个,SELECT 结果与实际存储不一致。
2520
- // MySQL / SQLite 都会报 UNIQUE constraint failed。
2521
2560
  // 注意:UNIQUE 列记录在 table._cachedUniqueFields(不是 _indexes),
2522
2561
  // 逐行比对即可,未建索引时也能正确拦截。
2523
2562
  const pk = this._pkOf(table);
@@ -2526,33 +2565,26 @@ class Database {
2526
2565
  if (!field || !Object.prototype.hasOwnProperty.call(validated, field)) continue;
2527
2566
  const nv = validated[field];
2528
2567
  if (nv === row[field]) continue; // 值没变,不算冲突
2529
- // #245:唯一性判定必须与等值比较同一口径(默认大小写不敏感)。
2530
- // 此处此前用严格 ===,于是 'a' 与 'A' 能共存 —— 与 WHERE e='a'
2531
- // 的折叠比较互相拆台。改用 Table 层的折叠键判定。
2568
+ // #245:唯一性判定必须与等值比较同一口径(默认大小写不敏感),
2569
+ // 改用 Table 层的折叠键判定。
2532
2570
  const clash = typeof table._uniqueConflictRow === 'function'
2533
2571
  ? table._uniqueConflictRow(field, nv, row)
2534
2572
  : table._rows.find(r => r !== row && r[field] === nv);
2535
2573
  if (clash) throw createError('ER_DUP_ENTRY', String(nv), field);
2536
2574
  }
2537
2575
  // 外键:改主键时按 ON UPDATE 传播到引用它的子表;改自身外键列时校验引用存在。
2538
- // 此前这里直接 Object.assign 绕过 Table.updateById,ON UPDATE CASCADE / RESTRICT
2539
- // 与 FK 校验全部失效(外键形同虚设)。
2540
2576
  if (pk && Object.prototype.hasOwnProperty.call(validated, pk) && validated[pk] !== row[pk]) {
2541
2577
  table._propagatePKUpdate(row[pk], validated[pk]);
2542
2578
  }
2543
2579
  if (table._foreignKeys && table._foreignKeys.length) {
2544
2580
  table._validateForeignKeys({ ...row, ...validated });
2545
2581
  }
2546
- // #250:updateById 必须与 db.update() 走同一套约束校验。
2547
- // 此前只补了 CHECK / 复合唯一,漏了 NOT NULL(required)——
2548
- // 于是 updateById 能把 NULL 写进 NOT NULL 列,而 db.update() 会正确报 1048。
2549
- // 两条 API 路径必须一致。
2582
+ // #250:与 db.update() 走同一套约束校验(NOT NULL / required)。
2550
2583
  if (typeof table._validateConstraints === 'function') {
2551
2584
  const rowIdx = table._rows.indexOf(row);
2552
2585
  table._validateConstraints({ ...row, ...validated }, rowIdx);
2553
2586
  }
2554
- // CHECK 约束(Issue #70):Database.updateById 直接 Object.assign 写行,
2555
- // 绕过了 Table.updateById 的约束校验,导致 CHECK 在 UPDATE 上失效。
2587
+ // CHECK 约束(Issue #70)
2556
2588
  if (typeof table._enforceChecks === 'function') {
2557
2589
  table._enforceChecks({ ...row, ...validated });
2558
2590
  }
@@ -2578,6 +2610,20 @@ class Database {
2578
2610
  if (rowIndex !== -1) table._addToIndexes(rowIndex, row);
2579
2611
  if (typeof table._markRowDirty === 'function') table._markRowDirty(row, oldPk);
2580
2612
  }
2613
+ return { row, validated };
2614
+ }
2615
+
2616
+ async updateById(tableName, id, data) {
2617
+ const table = this._ensureTable(tableName);
2618
+ if (!table) throw this._noSuchTable(tableName);
2619
+ // #303:beforeUpdate 可返回「修改后 data」(PLUGINS.md 契约),
2620
+ // 写回后必须用改写后的值继续。
2621
+ const hookArgs = [tableName, id, data];
2622
+ if (!(await this._runHooks('beforeUpdate', hookArgs))) return { ok: false, error: 'aborted' }; // #383
2623
+ data = hookArgs[2];
2624
+ const applied = this._applyUpdateToRow(table, id, data);
2625
+ if (!applied) return { ok: false, error: 'not found' };
2626
+ const { row, validated } = applied;
2581
2627
  this._walLogUpsert(tableName, [row]);
2582
2628
  this._emit('update', { table: tableName, id, data: validated });
2583
2629
  await this._runHooks('afterUpdate', [tableName, id, validated, { ok: true }]);
@@ -2589,20 +2635,14 @@ class Database {
2589
2635
  const table = this._ensureTable(tableName);
2590
2636
  if (!table) throw this._noSuchTable(tableName);
2591
2637
  const pairs = entries.map(([id, data]) => [id, data]);
2592
- if (!(await this._runHooks('beforeUpdate', [tableName, pairs]))) return;
2593
- const pk = this._pkOf(table);
2638
+ if (!(await this._runHooks('beforeUpdate', [tableName, pairs]))) return { ok: false, count: 0, error: 'aborted' }; // #383
2594
2639
  let count = 0;
2595
2640
  const changed = [];
2596
2641
  for (const [id, data] of pairs) {
2597
- const row = this._resolveId(table, id);
2598
- if (row) {
2599
- // CHECK 约束(Issue #70):批量更新同样不能在无校验的情况下写行
2600
- if (typeof table._enforceChecks === 'function') table._enforceChecks({ ...row, ...data });
2601
- const oldPk = pk ? row[pk] : undefined;
2602
- Object.assign(row, data);
2603
- if (typeof table._markRowDirty === 'function') table._markRowDirty(row, oldPk);
2642
+ const applied = this._applyUpdateToRow(table, id, data);
2643
+ if (applied) {
2644
+ changed.push(applied.row);
2604
2645
  count++;
2605
- changed.push(row);
2606
2646
  }
2607
2647
  }
2608
2648
  if (changed.length) this._walLogUpsert(tableName, changed);
@@ -2615,7 +2655,7 @@ class Database {
2615
2655
  async removeById(tableName, id) {
2616
2656
  const table = this._ensureTable(tableName);
2617
2657
  if (!table) throw this._noSuchTable(tableName);
2618
- if (!(await this._runHooks('beforeDelete', [tableName, id]))) return;
2658
+ if (!(await this._runHooks('beforeDelete', [tableName, id]))) return { ok: false, error: 'aborted' }; // #383
2619
2659
  if (table._primaryKey) {
2620
2660
  const removed = table.removeById(id);
2621
2661
  if (removed === 0) return { ok: false, error: 'not found' };
@@ -2641,7 +2681,7 @@ class Database {
2641
2681
  async removeByIds(tableName, ids) {
2642
2682
  const table = this._ensureTable(tableName);
2643
2683
  if (!table) throw this._noSuchTable(tableName);
2644
- if (!(await this._runHooks('beforeDelete', [tableName, ids]))) return;
2684
+ if (!(await this._runHooks('beforeDelete', [tableName, ids]))) return { ok: false, count: 0, error: 'aborted' }; // #383
2645
2685
  let removed = 0;
2646
2686
  if (table._primaryKey) {
2647
2687
  for (const id of ids) removed += table.removeById(id);
package/lib/migrate.js CHANGED
@@ -303,10 +303,21 @@ async function importFromCSV(engine, table, csv, opts = {}) {
303
303
  }
304
304
  const chunkSize = opts.chunkSize != null ? opts.chunkSize : DEFAULT_CHUNK_SIZE;
305
305
  let inserted = 0;
306
+ // #362:行宽与表头不一致此前完全静默 —— 多出来的字段被丢掉,缺的列补 NULL,
307
+ // 导入后行数对得上、数据却缺一块。这里统计并按 strictRows 决定是否中止。
308
+ const warnings = [];
309
+ let rowNo = start;
306
310
  // 不攒 dataRows 全量,边解析边分块写入 —— 避免 2M 行全在内存里
307
311
  for (let i = start; i < rows.length; i += chunkSize) {
308
312
  const chunk = rows.slice(i, i + chunkSize);
309
313
  const dataRows = chunk.map(raw => {
314
+ rowNo++;
315
+ if (raw.length !== columns.length) {
316
+ const kind = raw.length > columns.length ? 'extra' : 'missing';
317
+ const n = Math.abs(raw.length - columns.length);
318
+ if (warnings.length < 50) warnings.push({ row: rowNo, kind, count: n, expected: columns.length, actual: raw.length });
319
+ if (opts.strictRows) throw new Error(`CSV row ${rowNo}: expected ${columns.length} fields, got ${raw.length}`);
320
+ }
310
321
  const row = {};
311
322
  for (let j = 0; j < columns.length; j++) {
312
323
  const type = schema && schema[columns[j]] ? schema[columns[j]].type : 'string';
@@ -318,7 +329,9 @@ async function importFromCSV(engine, table, csv, opts = {}) {
318
329
  const ids = await engine.insert(table, dataRows);
319
330
  inserted += Array.isArray(ids) ? ids.length : dataRows.length;
320
331
  }
321
- return { inserted };
332
+ const out = { inserted };
333
+ if (warnings.length > 0) out.warnings = warnings;
334
+ return out;
322
335
  }
323
336
 
324
337
  /* ---------- mysqldump ---------- */
@@ -23,6 +23,34 @@ const OP_COMPRESSED = 2012;
23
23
  const OP_QUERY = 2004;
24
24
  const OP_REPLY = 1;
25
25
 
26
+ const INT64_MIN = -(2n ** 63n);
27
+ const INT64_MAX = 2n ** 63n - 1n;
28
+
29
+ /**
30
+ * #396:把扩展 JSON 的 Int64 标记(`$numberLong` / `$long`)或 BigInt 解析成
31
+ * 范围内的 BigInt。直接 `BigInt(String(...))` 解析,不经过 `Number()` 中转
32
+ * (先 Number 会把 >2^53 的值四舍五入,再 BigInt 触发裸 RangeError);
33
+ * 越界给明确的 BSON 错误,而不是静默截断。
34
+ */
35
+ function parseInt64Value(marker, field) {
36
+ let raw = marker;
37
+ if (marker && typeof marker === 'object' && !Array.isArray(marker)) {
38
+ raw = marker.$numberLong !== undefined ? marker.$numberLong : marker.$long;
39
+ }
40
+ let val;
41
+ if (typeof raw === 'bigint') val = raw;
42
+ else {
43
+ const s = String(raw === null ? '' : raw).trim();
44
+ if (!/^[+-]?\d+$/.test(s)) throw new Error(`BSON $numberLong invalid value: '${raw}' (field '${field}')`);
45
+ try { val = BigInt(s); }
46
+ catch (e) { throw new Error(`BSON $numberLong invalid value: '${raw}' (field '${field}')`); }
47
+ }
48
+ if (val < INT64_MIN || val > INT64_MAX) {
49
+ throw new Error(`BSON $numberLong out of int64 range: '${raw}' (field '${field}')`);
50
+ }
51
+ return val;
52
+ }
53
+
26
54
  /* ------------------------------------------------------------------ */
27
55
  /* BSON */
28
56
  /* ------------------------------------------------------------------ */
@@ -67,9 +95,20 @@ function bsonDocument(obj) {
67
95
  body = Buffer.concat([body, Buffer.from([0x01]), name, Buffer.from([0]), b]);
68
96
  continue;
69
97
  }
70
- if (v && v.$long !== undefined) {
98
+ if (typeof v === 'bigint') {
99
+ // #396:原生 BigInt 直接按 Int64 写入,越界显式报错
100
+ if (v < INT64_MIN || v > INT64_MAX) throw new Error(`BSON bigint out of int64 range: ${v} (field '${k}')`);
71
101
  const b = Buffer.alloc(8);
72
- b.writeBigInt64LE(BigInt(Math.trunc(Number(v.$long))), 0);
102
+ b.writeBigInt64LE(v, 0);
103
+ body = Buffer.concat([body, Buffer.from([0x12]), name, Buffer.from([0]), b]);
104
+ continue;
105
+ }
106
+ if (v && typeof v === 'object' && !Array.isArray(v) && (v.$numberLong !== undefined || v.$long !== undefined)) {
107
+ // #396:扩展 JSON Int64 标记 `$numberLong` / `$long` 都编成 0x12;
108
+ // 直接 BigInt 解析十进制字符串,不走 Number() 中转,越界抛明确错误。
109
+ const val = parseInt64Value(v, k);
110
+ const b = Buffer.alloc(8);
111
+ b.writeBigInt64LE(val, 0);
73
112
  body = Buffer.concat([body, Buffer.from([0x12]), name, Buffer.from([0]), b]);
74
113
  continue;
75
114
  }
@@ -170,7 +209,12 @@ function bsonReadValue(buf, pos, type, end) {
170
209
  case 0x0A: { return { value: null, pos }; }
171
210
  case 0x10: { return { value: buf.readInt32LE(pos), pos: pos + 4 }; }
172
211
  case 0x11: { return { value: Number(buf.readBigInt64LE(pos)), pos: pos + 8 }; }
173
- case 0x12: { return { value: Number(buf.readBigInt64LE(pos)), pos: pos + 8 }; }
212
+ case 0x12: {
213
+ // #396:Int64 必须无损往返 —— 保留完整 64 位值为扩展 JSON `$numberLong`
214
+ // 字符串标记,不再经 Number() 降级成双精度(>2^53 会丢末三位精度)。
215
+ const big = buf.readBigInt64LE(pos);
216
+ return { value: { $numberLong: big.toString() }, pos: pos + 8 };
217
+ }
174
218
  case 0x13: { return { value: buf.readDoubleLE(pos + 1), pos: pos + 17 }; }
175
219
  default: return { value: null, pos: end };
176
220
  }
@@ -316,6 +360,12 @@ class MongoServer {
316
360
  this._indexesByColl = new Map(); // "db.coll" → [{ name, columns, unique }]
317
361
  this._cursors = new Map(); // #278:find/getMore 游标
318
362
  this._nextCursorId = 1;
363
+ // #428:游标空闲超时(默认 10 分钟,与 MongoDB 默认 cursor 超时一致),
364
+ // 超时后后台清扫回收;可经 options.cursorIdleTimeoutMs 覆盖。
365
+ this._cursorIdleTimeoutMs = Number(options.cursorIdleTimeoutMs) > 0
366
+ ? Number(options.cursorIdleTimeoutMs) : 10 * 60 * 1000;
367
+ this._cursorTimer = setInterval(() => this._sweepIdleCursors(), Math.min(this._cursorIdleTimeoutMs, 60 * 1000));
368
+ if (typeof this._cursorTimer.unref === 'function') this._cursorTimer.unref();
319
369
  this._autoCollections = new Set(); // db.collection 由 Mongo 自动建表(可继续补列)
320
370
  }
321
371
 
@@ -662,6 +712,9 @@ class MongoServer {
662
712
  const ordered = doc.ordered !== false;
663
713
  for (let i = 0; i < docs.length; i++) {
664
714
  const doc2 = { ...docs[i] };
715
+ // #430:文档缺省 `_id` 时服务端兜底生成 ObjectId —— MongoDB 每条文档
716
+ // 必有 `_id`;生成后再走既有唯一性查重与落库流程。
717
+ if (doc2._id === undefined) doc2._id = ObjectId.generate();
665
718
  // 检查 _id 唯一性
666
719
  // Issue #44:索引查找是严格相等的,空结果不能直接当「不存在」——
667
720
  // 查询值与已存值的类型不一致时会漏判。这里再加一道按 schema 归一的直接扫描。
@@ -821,21 +874,45 @@ class MongoServer {
821
874
  let cursorId = 0;
822
875
  if (rows.length > firstBatch.length) {
823
876
  cursorId = this._nextCursorId++;
824
- this._cursors.set(cursorId, { rows: rows.slice(firstBatch.length), ns, coll, db: this._dbOf(doc), batchSize });
877
+ this._cursors.set(cursorId, { rows: rows.slice(firstBatch.length), ns, coll, db: this._dbOf(doc), batchSize, lastActive: Date.now() });
825
878
  }
826
879
  return { ok: 1, cursor: { id: { $long: cursorId }, ns, firstBatch } };
827
880
  }
828
881
  case 'getMore': {
829
- const idIn = doc.getMore;
830
- const id = idIn && typeof idIn === 'object' ? Number(idIn.$long ?? idIn.low ?? 0) : Number(idIn || 0);
882
+ const id = this._parseCursorId(doc.getMore);
831
883
  const cur = this._cursors.get(id);
832
884
  if (!cur) return { ok: 0, errmsg: 'cursor not found', code: 43 };
885
+ // #428:空闲超时后游标已被清扫,再 getMore 回 cursorNotFound(43)。
886
+ if (Date.now() - (cur.lastActive || 0) > this._cursorIdleTimeoutMs) {
887
+ this._cursors.delete(id);
888
+ return { ok: 0, errmsg: 'cursor not found', code: 43 };
889
+ }
890
+ cur.lastActive = Date.now();
833
891
  const nextBatch = cur.rows.slice(0, cur.batchSize);
834
892
  cur.rows = cur.rows.slice(nextBatch.length);
835
893
  let nextId = id;
836
894
  if (cur.rows.length === 0) { this._cursors.delete(id); nextId = 0; }
837
895
  return { ok: 1, cursor: { id: { $long: nextId }, ns: cur.ns, nextBatch } };
838
896
  }
897
+ case 'killCursors': {
898
+ // #428:主动销毁游标。按 MongoDB 口径回
899
+ // cursorsKilled / cursorsNotFound / cursorsAlive / cursorsUnknown。
900
+ const ids = Array.isArray(doc.cursors) ? doc.cursors : [];
901
+ const cursorsKilled = [];
902
+ const cursorsNotFound = [];
903
+ const cursorsAlive = [];
904
+ const cursorsUnknown = [];
905
+ for (const raw of ids) {
906
+ const id = this._parseCursorId(raw);
907
+ if (this._cursors.has(id)) {
908
+ this._cursors.delete(id);
909
+ cursorsKilled.push(raw);
910
+ } else {
911
+ cursorsNotFound.push(raw);
912
+ }
913
+ }
914
+ return { ok: 1, cursorsKilled, cursorsNotFound, cursorsAlive, cursorsUnknown };
915
+ }
839
916
  case 'update': {
840
917
  const coll = String(doc.update);
841
918
  const engine = await this._ensureCollection(coll, this._dbOf(doc));
@@ -962,7 +1039,7 @@ class MongoServer {
962
1039
  const engine = await this._ensureCollection(coll, this._dbOf(doc));
963
1040
  const pipeline = doc.pipeline || [];
964
1041
  let rows = await engine.find(coll, {});
965
- const STAGES = new Set(['$match', '$count', '$limit', '$skip', '$sort', '$project', '$unwind', '$lookup', '$group']);
1042
+ const STAGES = new Set(['$match', '$count', '$limit', '$skip', '$sort', '$project', '$unwind', '$lookup', '$group', '$addFields', '$set']);
966
1043
  for (const stage of pipeline) {
967
1044
  const stageName = Object.keys(stage || {})[0];
968
1045
  if (!STAGES.has(stageName)) {
@@ -988,6 +1065,17 @@ class MongoServer {
988
1065
  return out;
989
1066
  });
990
1067
  }
1068
+ else if (stage.$addFields || stage.$set) {
1069
+ // #328:$addFields 是 MongoDB 4.2 起的标准 stage,$set 是它的别名。
1070
+ // 之前只列在 doc/mongodb.md 的支持表里,实现里没有分支,v6.8.21 把未知 stage
1071
+ // 改成显式 40324 之后,按文档写管道的用户会直接失败。
1072
+ const spec = stage.$addFields || stage.$set;
1073
+ rows = rows.map((r) => {
1074
+ const out = Object.assign({}, r);
1075
+ for (const [k, e] of Object.entries(spec || {})) setPath(out, k, evalMongoExpr(e, r));
1076
+ return out;
1077
+ });
1078
+ }
991
1079
  else if (stage.$unwind) {
992
1080
  const cfg = typeof stage.$unwind === 'string'
993
1081
  ? { path: stage.$unwind }
@@ -1231,6 +1319,22 @@ class MongoServer {
1231
1319
  }
1232
1320
  }
1233
1321
 
1322
+ /** #428:清扫超过空闲超时仍未被 getMore 访问的游标,释放结果集快照。 */
1323
+ _sweepIdleCursors() {
1324
+ const now = Date.now();
1325
+ for (const [id, cur] of this._cursors) {
1326
+ if (now - (cur.lastActive || 0) > this._cursorIdleTimeoutMs) this._cursors.delete(id);
1327
+ }
1328
+ }
1329
+
1330
+ /** 解析游标 id(兼容 number / `$long` / `$numberLong` 标记)。 */
1331
+ _parseCursorId(raw) {
1332
+ if (raw && typeof raw === 'object') {
1333
+ return Number(raw.$long ?? raw.$numberLong ?? raw.low ?? 0);
1334
+ }
1335
+ return Number(raw || 0);
1336
+ }
1337
+
1234
1338
  async _removeRows(engine, coll, rows) {
1235
1339
  // 收集所有需要删除的行的 id,走 engine.removeByIds
1236
1340
  // 这样会写 WAL、触发 hooks、检查约束
@@ -1339,6 +1443,7 @@ class MongoServer {
1339
1443
  }
1340
1444
 
1341
1445
  close(cb) {
1446
+ if (this._cursorTimer) { clearInterval(this._cursorTimer); this._cursorTimer = null; }
1342
1447
  for (const s of this._sockets) s.destroy();
1343
1448
  const done = () => {
1344
1449
  if (this._server) { this._server.close(cb || (() => {})); this._server = null; }