jsql-neo 6.7.5 → 6.7.7

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.
@@ -11,9 +11,11 @@
11
11
  * insert / find / getMore / update / delete / count / aggregate($match,$count)
12
12
  */
13
13
  const net = require('net');
14
+ const fs = require('fs');
14
15
  const path = require('path');
15
16
  const zlib = require('zlib');
16
17
  const Database = require('./database');
18
+ const { ObjectId, valuesEqual, arrayIncludesValue, mapKey } = require('./objectid');
17
19
 
18
20
  const OP_MSG = 2013;
19
21
  const OP_COMPRESSED = 2012;
@@ -73,6 +75,11 @@ function bsonDocument(obj) {
73
75
  body = Buffer.concat([body, Buffer.from([0x09]), name, Buffer.from([0]), b]);
74
76
  continue;
75
77
  }
78
+ if (v instanceof ObjectId) {
79
+ // 必须在通用 object 分支之前:ObjectId 落回 0x03 会丢类型
80
+ body = Buffer.concat([body, Buffer.from([0x07]), name, Buffer.from([0]), v.bytes]);
81
+ continue;
82
+ }
76
83
  if (Array.isArray(v)) {
77
84
  const arrObj = {};
78
85
  v.forEach((x, i) => { arrObj[String(i)] = x; });
@@ -129,7 +136,7 @@ function bsonReadValue(buf, pos, type, end) {
129
136
  return { value: arr, pos: r.pos };
130
137
  }
131
138
  case 0x05: { const len = buf.readInt32LE(pos); return { value: buf.slice(pos + 5, pos + 5 + len), pos: pos + 5 + len }; }
132
- case 0x07: { return { value: buf.slice(pos, pos + 12).toString('hex'), pos: pos + 12 }; }
139
+ case 0x07: { return { value: ObjectId.fromBytes(buf.slice(pos, pos + 12)), pos: pos + 12 }; }
133
140
  case 0x08: { return { value: buf[pos] !== 0, pos: pos + 1 }; }
134
141
  case 0x09: { return { value: new Date(Number(buf.readBigInt64LE(pos))), pos: pos + 8 }; }
135
142
  case 0x0A: { return { value: null, pos }; }
@@ -171,7 +178,15 @@ class MongoServer {
171
178
 
172
179
  _createEngine(db) {
173
180
  if (this.dataDir && this.dataDir !== ':memory:') {
174
- return new Database(path.join(this.dataDir, db || 'default'), { autoSave: true });
181
+ // 与 multiserver 的共享引擎保持一致:目录走 hybrid 模式(每表 .jsql 增量刷盘),
182
+ // 否则 legacy 单文件模式在 insert 路径上从不落盘,数据重启即丢。
183
+ // 兼容旧版单文件库:已存在同名文件则继续用 legacy 模式。
184
+ const dbPath = path.join(this.dataDir, db || 'default');
185
+ let stat = null;
186
+ try { stat = fs.statSync(dbPath); } catch (e) { /* not created yet */ }
187
+ return stat && stat.isFile()
188
+ ? new Database(dbPath, { autoSave: true })
189
+ : new Database(dbPath, { mode: 'hybrid' });
175
190
  }
176
191
  return new Database(':memory:', { autoSave: false });
177
192
  }
@@ -427,24 +442,43 @@ class MongoServer {
427
442
  const engine = await this._ensureCollection(coll, this._dbOf(doc));
428
443
  const docs = doc.documents || [];
429
444
  const ids = [];
430
- for (const d of docs) {
431
- const doc2 = { ...d };
445
+ const writeErrors = [];
446
+ for (let i = 0; i < docs.length; i++) {
447
+ const doc2 = { ...docs[i] };
432
448
  // 检查 _id 唯一性
433
449
  // Issue #44:索引查找是严格相等的,空结果不能直接当「不存在」——
434
450
  // 查询值与已存值的类型不一致时会漏判。这里再加一道按 schema 归一的直接扫描。
451
+ // 相等判断走 valuesEqual:同字节 ObjectId 与同 hex String 是两个不同的键。
435
452
  if (doc2._id !== undefined) {
453
+ let dup = false;
436
454
  const existing = await engine.find(coll, { _id: doc2._id });
437
- if (existing.length > 0) continue; // 跳过重复 _id
438
- const table = typeof engine._ensureTable === 'function' ? engine._ensureTable(coll) : null;
439
- if (table && Array.isArray(table._rows) && typeof table._coerceQueryValue === 'function') {
440
- const idKey = table._coerceQueryValue('_id', doc2._id);
441
- if (table._rows.some((r) => r && !r._deleted && r._id === idKey)) continue;
455
+ if (existing.length > 0) dup = true;
456
+ if (!dup) {
457
+ const table = typeof engine._ensureTable === 'function' ? engine._ensureTable(coll) : null;
458
+ if (table && Array.isArray(table._rows) && typeof table._coerceQueryValue === 'function') {
459
+ const idKey = table._coerceQueryValue('_id', doc2._id);
460
+ if (table._rows.some((r) => r && !r._deleted && valuesEqual(r._id, idKey))) dup = true;
461
+ }
462
+ }
463
+ if (dup) {
464
+ // 真重复必须可见:ordered:false 下 MongoDB 逐条报 E11000 writeErrors,
465
+ // 此前静默丢弃导致计数对不上也无从发现(同 hex 异类型 _id 误判为重复)
466
+ writeErrors.push({
467
+ index: i,
468
+ code: 11000,
469
+ errmsg: `E11000 duplicate key error collection: ${this._dbOf(doc)}.${coll} index: _id_ dup key: { _id: ${doc2._id instanceof ObjectId ? doc2._id.toString() : JSON.stringify(doc2._id)} }`,
470
+ keyPattern: { _id: 1 },
471
+ keyValue: { _id: doc2._id },
472
+ });
473
+ continue;
442
474
  }
443
475
  }
444
476
  await engine.insert(coll, doc2);
445
477
  ids.push(doc2._id);
446
478
  }
447
- return { ok: 1, n: ids.length };
479
+ const reply = { ok: 1, n: ids.length };
480
+ if (writeErrors.length > 0) reply.writeErrors = writeErrors;
481
+ return reply;
448
482
  }
449
483
  case 'findAndModify': {
450
484
  const coll = String(doc.findAndModify);
@@ -479,7 +513,9 @@ class MongoServer {
479
513
  const values = [];
480
514
  for (const r of rows) {
481
515
  const v = r[key];
482
- if (!seen.has(JSON.stringify(v))) { seen.add(JSON.stringify(v)); values.push(v); }
516
+ // ObjectId 与同 hex String 是不同的值:\0 前缀不会与 JSON.stringify 结果冲突
517
+ const dk = v instanceof ObjectId ? '\0oid:' + v.toString() : JSON.stringify(v);
518
+ if (!seen.has(dk)) { seen.add(dk); values.push(v); }
483
519
  }
484
520
  return { ok: 1, values };
485
521
  }
@@ -574,7 +610,9 @@ class MongoServer {
574
610
  rows = [...rows].sort((a, b) => {
575
611
  for (const [k, dir] of sortKeys) {
576
612
  const av = a[k]; const bv = b[k];
577
- if (av === bv) continue;
613
+ // valuesEqual:同字节 ObjectId 不 ===,缺这一道相等短路时
614
+ // 相等键会破坏排序稳定性(sort+skip/limit 分页会丢/重文档)
615
+ if (av === bv || valuesEqual(av, bv)) continue;
578
616
  const desc = Number(dir) < 0;
579
617
  // Issue #47:NULL 的位置随排序方向走(升序在前、降序在后),
580
618
  // 与 MongoDB 一致;此前固定返回 1/-1,升序时 null 恒排最后。
@@ -629,13 +667,15 @@ class MongoServer {
629
667
  // not a numeric auto-generated one (auto-ids start at 1,2,...N)
630
668
  gk = row._id;
631
669
  }
632
- if (!groups.has(gk)) groups.set(gk, []);
633
- groups.get(gk).push(row);
670
+ // 规范键:同字节 ObjectId 归并同组(\0 前缀不可能与真实 BSON 字符串冲突)
671
+ if (!groups.has(mapKey(gk))) groups.set(mapKey(gk), { v: gk, rows: [] });
672
+ groups.get(mapKey(gk)).rows.push(row);
634
673
  }
635
674
  // Pass 2: compute accumulators per group
636
675
  const out = [];
637
- for (const [gk, grow] of groups) {
638
- const doc = { _id: gk };
676
+ for (const [, g] of groups) {
677
+ const grow = g.rows;
678
+ const doc = { _id: g.v };
639
679
  for (const [k, v] of Object.entries(groupDef)) {
640
680
  if (k === '_id' || v == null) continue;
641
681
  if (typeof v === 'object') {
@@ -784,30 +824,32 @@ class MongoServer {
784
824
  if (this._match(row, cond)) return false;
785
825
  continue;
786
826
  }
787
- if (cond && typeof cond === 'object' && !Array.isArray(cond)) {
827
+ // ObjectId 是值不是操作符对象:typeof 'object' 但无枚举键,会 vacuous 匹配全表
828
+ if (cond && typeof cond === 'object' && !Array.isArray(cond) && !(cond instanceof ObjectId)) {
788
829
  for (const [op, v] of Object.entries(cond)) {
789
830
  const rv = row[k];
790
- if (op === '$eq' && rv !== v) return false;
831
+ if (op === '$eq' && !valuesEqual(rv, v)) return false;
791
832
  if (op === '$gt' && !(rv > v)) return false;
792
833
  if (op === '$gte' && !(rv >= v)) return false;
793
834
  if (op === '$lt' && !(rv < v)) return false;
794
835
  if (op === '$lte' && !(rv <= v)) return false;
795
- if (op === '$ne' && !(rv !== v)) return false;
796
- if (op === '$in' && !(v.includes(rv))) return false;
797
- if (op === '$nin' && v.includes(rv)) return false;
836
+ if (op === '$ne' && valuesEqual(rv, v)) return false;
837
+ if (op === '$in' && !arrayIncludesValue(v, rv)) return false;
838
+ if (op === '$nin' && arrayIncludesValue(v, rv)) return false;
798
839
  if (op === '$exists' && (v ? (rv === undefined) : (rv !== undefined))) return false;
799
840
  if (op === '$regex') {
800
841
  const flags = String(cond.$options || '').includes('i') ? 'i' : '';
801
842
  if (typeof rv !== 'string' || !new RegExp(String(v), flags).test(rv)) return false;
802
843
  }
803
844
  if (op === '$type') {
845
+ if (v === 'objectId') { if (!(rv instanceof ObjectId)) return false; continue; }
804
846
  const t = v === 'string' ? 'string' : v === 'int' || v === 'long' || v === 'double' || v === 'number' ? 'number' : v === 'bool' ? 'boolean' : v === 'null' ? 'null' : v === 'array' ? 'array' : typeof rv;
805
847
  if (typeof rv !== t) return false;
806
848
  }
807
849
  if (op === '$size' && !(Array.isArray(rv) && rv.length === v)) return false;
808
850
  if (op === '$elemMatch' && !(Array.isArray(rv) && rv.some((el) => this._match(el, v)))) return false;
809
851
  }
810
- } else if (row[k] !== cond) {
852
+ } else if (!valuesEqual(row[k], cond)) {
811
853
  return false;
812
854
  }
813
855
  }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * BSON ObjectId — 一等 JS 值。
3
+ *
4
+ * 此前 BSON 解码把 0x07 直接转成 hex 字符串,类型信息在协议边界就丢了:
5
+ * 同一 24-hex 的 ObjectId 与 String 在真实 MongoDB 里是两个不同的键,
6
+ * 这里却会碰撞,insert 时第二篇文档被静默丢弃(insertMany ordered:false
7
+ * 也不报 writeErrors)。
8
+ *
9
+ * 全库的相等判断都是严格 ===(table._matchRow / _matchOperator /
10
+ * mongo_server._match / _id 查重扫描),所以跨实例的同字节 ObjectId
11
+ * 必须经 valuesEqual() 比较;两个相同字节的实例永远不该用 === 判等。
12
+ * 排序比较(< >)走 Symbol.toPrimitive → hex 字符串,字典序即字节序。
13
+ */
14
+
15
+ const HEX_RE = /^[0-9a-f]{24}$/;
16
+
17
+ class ObjectId {
18
+ constructor(input) {
19
+ if (typeof input === 'string') {
20
+ const hex = input.toLowerCase();
21
+ if (!HEX_RE.test(hex)) throw new Error(`Invalid ObjectId string: '${input}'`);
22
+ this._bytes = Buffer.from(hex, 'hex');
23
+ } else if (Buffer.isBuffer(input)) {
24
+ if (input.length !== 12) throw new Error(`Invalid ObjectId byte length: ${input.length}`);
25
+ this._bytes = Buffer.from(input);
26
+ } else if (input instanceof ObjectId) {
27
+ this._bytes = Buffer.from(input._bytes);
28
+ } else {
29
+ throw new Error('ObjectId expects a 24-char hex string or 12-byte Buffer');
30
+ }
31
+ this._hex = null;
32
+ }
33
+
34
+ get bytes() {
35
+ return this._bytes;
36
+ }
37
+
38
+ toString() {
39
+ if (this._hex === null) this._hex = this._bytes.toString('hex');
40
+ return this._hex;
41
+ }
42
+
43
+ equals(other) {
44
+ return other instanceof ObjectId && this.toString() === other.toString();
45
+ }
46
+
47
+ // legacy 单文件 JSON 落盘 / 日志输出时保住值本身(hex),类型信息不保证
48
+ toJSON() {
49
+ return this.toString();
50
+ }
51
+
52
+ [Symbol.toPrimitive](hint) {
53
+ return this.toString();
54
+ }
55
+
56
+ static fromBytes(buf) {
57
+ return new ObjectId(buf);
58
+ }
59
+
60
+ static fromHex(hex) {
61
+ return new ObjectId(hex);
62
+ }
63
+ }
64
+
65
+ /**
66
+ * 严格 === 语义的 ObjectId 扩展:
67
+ * 同字节 ObjectId 相等;ObjectId 与 String 永不相等(这正是本修复点);
68
+ * 其余保持 === 。热路径先走 ===,零开销。
69
+ */
70
+ function valuesEqual(a, b) {
71
+ if (a === b) return true;
72
+ if (a instanceof ObjectId && b instanceof ObjectId) return a.equals(b);
73
+ return false;
74
+ }
75
+
76
+ /** $in/$nin:普通值用 includes 快路径,仅当查询值是 ObjectId 时才逐项比较。 */
77
+ function arrayIncludesValue(arr, v) {
78
+ if (arr.includes(v)) return true;
79
+ if (v instanceof ObjectId) {
80
+ for (const t of arr) if (t instanceof ObjectId && t.equals(v)) return true;
81
+ }
82
+ return false;
83
+ }
84
+
85
+ /**
86
+ * Map/Set 的规范键:同字节 ObjectId 归并为同一键,且不与任何真实 BSON
87
+ * 字符串冲突 —— BSON 的 cstring/string 以 \0 结尾,wire 上不可能出现含
88
+ * \0 的字符串,'\0oid:' 前缀因此对 String 值是安全命名空间。
89
+ */
90
+ function mapKey(v) {
91
+ return v instanceof ObjectId ? '\0oid:' + v.toString() : v;
92
+ }
93
+
94
+ module.exports = { ObjectId, valuesEqual, arrayIncludesValue, mapKey };
@@ -0,0 +1,215 @@
1
+ // © Vexify 2026 All Rights Reserved.
2
+ /**
3
+ * 行级懒加载缓存(hybrid / disk 目录模式)
4
+ *
5
+ * 目标:大表不再整表常驻内存。`Table._rows` 仍是「类数组」,但元素来自
6
+ * 磁盘上的 `{block, off}` 定位符 —— 只有真正被访问的行才 decode 进内存,
7
+ * 内存紧张时由 Database 按 LRU 逐行回退成定位符。
8
+ *
9
+ * 设计要点:
10
+ * • 用 Proxy 包住一个真实数组,数字下标命中定位符时才读盘;
11
+ * • 数组方法(filter/map/find/push/pop/splice…)都以 proxy 为 this,
12
+ * 逐元素走 get/set,语义与普通数组一致;
13
+ * • 脏行(尚未刷盘)永远 pin 在内存里,避免「改了但被淘汰」丢数据;
14
+ * • 淘汰只由 Database 在两次同步操作之间触发。同步操作内部不会发生
15
+ * 淘汰,因此 `_rows.indexOf(row)` 这类依赖对象标识的逻辑仍然成立。
16
+ */
17
+
18
+ const INDEX_RE = /^(?:0|[1-9]\d*)$/;
19
+
20
+ function toIndex(prop) {
21
+ return INDEX_RE.test(prop) ? Number(prop) : -1;
22
+ }
23
+
24
+ function isLocator(v) {
25
+ return v !== null && typeof v === 'object' && v.__loc === true;
26
+ }
27
+
28
+ function makeLocator(loc) {
29
+ return { __loc: true, block: loc.block, off: loc.off };
30
+ }
31
+
32
+ /**
33
+ * @param {object} table - 所属 Table(用于查询脏行、判断 pin)
34
+ * @param {Array<{block:number, off:number}>} locators - 有效行的物理位置
35
+ * @param {(block:number, off:number) => object} loader - 单行读取函数
36
+ * @param {Function} [onClose] - 缓存被丢弃时关闭底层句柄
37
+ */
38
+ function createRowCache(table, locators, loader, onClose) {
39
+ const target = new Array(locators.length);
40
+ const locs = new Array(locators.length); // 下标 -> 磁盘位置(null = 无磁盘来源)
41
+ let rowIndex = new WeakMap(); // 行对象 -> 下标
42
+ const lru = new Map(); // 下标 -> true(Map 保持访问顺序)
43
+
44
+ for (let i = 0; i < locators.length; i++) {
45
+ const loc = locators[i];
46
+ target[i] = makeLocator(loc);
47
+ locs[i] = { block: loc.block, off: loc.off };
48
+ }
49
+
50
+ function touch(i) {
51
+ lru.delete(i);
52
+ lru.set(i, true);
53
+ }
54
+
55
+ function untouch(i) {
56
+ lru.delete(i);
57
+ }
58
+
59
+ function dropMappings(i, value) {
60
+ if (value && typeof value === 'object' && !isLocator(value)) rowIndex.delete(value);
61
+ untouch(i);
62
+ }
63
+
64
+ function load(i) {
65
+ const loc = locs[i];
66
+ if (!loc) return undefined;
67
+ const row = loader(loc.block, loc.off);
68
+ if (row && typeof row === 'object') {
69
+ target[i] = row;
70
+ rowIndex.set(row, i);
71
+ touch(i);
72
+ }
73
+ return row;
74
+ }
75
+
76
+ const handler = {
77
+ get(t, prop, receiver) {
78
+ if (typeof prop === 'string') {
79
+ const i = toIndex(prop);
80
+ if (i >= 0) {
81
+ const v = t[i];
82
+ if (isLocator(v)) return load(i);
83
+ if (v !== undefined) touch(i);
84
+ return v;
85
+ }
86
+ }
87
+ return Reflect.get(t, prop, receiver);
88
+ },
89
+
90
+ set(t, prop, value) {
91
+ if (typeof prop === 'string') {
92
+ const i = toIndex(prop);
93
+ if (i >= 0) {
94
+ const old = t[i];
95
+ if (old !== value) {
96
+ if (value && typeof value === 'object' && !isLocator(value)) {
97
+ const src = rowIndex.get(value);
98
+ if (src !== undefined) {
99
+ // 删除时「用尾行填补空位」:locator 跟着行一起搬
100
+ if (src !== i) {
101
+ locs[i] = locs[src];
102
+ locs[src] = null;
103
+ untouch(src);
104
+ }
105
+ } else {
106
+ locs[i] = null; // 新插入的行,没有磁盘位置
107
+ }
108
+ } else {
109
+ locs[i] = null;
110
+ }
111
+ dropMappings(i, old);
112
+ }
113
+ t[i] = value;
114
+ if (value && typeof value === 'object' && !isLocator(value)) {
115
+ rowIndex.set(value, i);
116
+ touch(i);
117
+ }
118
+ return true;
119
+ }
120
+ if (prop === 'length') {
121
+ const n = value >>> 0;
122
+ const oldLen = t.length;
123
+ if (n < oldLen) {
124
+ for (let j = n; j < oldLen; j++) dropMappings(j, t[j]);
125
+ }
126
+ t.length = n;
127
+ locs.length = n;
128
+ return true;
129
+ }
130
+ }
131
+ return Reflect.set(t, prop, value);
132
+ },
133
+
134
+ deleteProperty(t, prop) {
135
+ const i = toIndex(prop);
136
+ if (i >= 0) {
137
+ dropMappings(i, t[i]);
138
+ locs[i] = null;
139
+ delete t[i];
140
+ return true;
141
+ }
142
+ return Reflect.deleteProperty(t, prop);
143
+ }
144
+ };
145
+
146
+ const rows = new Proxy(target, handler);
147
+
148
+ /** 顺序扫描全部磁盘行,逐行回调;扫描结果不留在缓存里。 */
149
+ function scan(fn) {
150
+ for (let i = 0; i < locs.length; i++) {
151
+ const cur = target[i];
152
+ let row;
153
+ if (!isLocator(cur) && cur !== undefined) row = cur;
154
+ else if (locs[i]) row = loader(locs[i].block, locs[i].off);
155
+ if (row !== undefined && row !== null) fn(row, i);
156
+ }
157
+ }
158
+
159
+ /** 按 LRU 顺序把最多 max 行回退成定位符;脏行始终保留。 */
160
+ function evict(max) {
161
+ if (max <= 0) return 0;
162
+ let removed = 0;
163
+ const keys = [...lru.keys()];
164
+ for (const i of keys) {
165
+ if (removed >= max) break;
166
+ const v = target[i];
167
+ if (!v || isLocator(v) || typeof v !== 'object') { untouch(i); continue; }
168
+ if (table && table._dirtyUpserts && table._dirtyUpserts.has(v)) continue;
169
+ const loc = locs[i];
170
+ if (!loc) continue; // 新插入、尚未落盘的行无法回退
171
+ rowIndex.delete(v);
172
+ target[i] = makeLocator(loc);
173
+ untouch(i);
174
+ removed++;
175
+ }
176
+ return removed;
177
+ }
178
+
179
+ /** 整表重写/刷新后重置全部定位符(行顺序必须与原来一致)。 */
180
+ function reset(newLocs) {
181
+ target.length = 0;
182
+ locs.length = 0;
183
+ lru.clear();
184
+ rowIndex = new WeakMap();
185
+ for (let i = 0; i < newLocs.length; i++) {
186
+ target[i] = makeLocator(newLocs[i]);
187
+ locs[i] = { block: newLocs[i].block, off: newLocs[i].off };
188
+ }
189
+ }
190
+
191
+ /** 刷盘后更新个别已落盘行的定位符。 */
192
+ function applyLocators(rowList, newLocs) {
193
+ if (!rowList || !newLocs) return;
194
+ const n = Math.min(rowList.length, newLocs.length);
195
+ for (let k = 0; k < n; k++) {
196
+ const row = rowList[k];
197
+ const i = rowIndex.get(row);
198
+ if (i === undefined || target[i] !== row) continue;
199
+ locs[i] = { block: newLocs[k].block, off: newLocs[k].off };
200
+ touch(i);
201
+ }
202
+ }
203
+
204
+ function size() { return lru.size; }
205
+
206
+ function close() {
207
+ if (typeof onClose === 'function') {
208
+ try { onClose(); } catch (e) { /* 关闭句柄失败不影响数据 */ }
209
+ }
210
+ }
211
+
212
+ return { rows, scan, evict, reset, applyLocators, size, close };
213
+ }
214
+
215
+ module.exports = { createRowCache };