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.
@@ -0,0 +1,162 @@
1
+ /*
2
+ * ObjectId 类型回归测试。
3
+ *
4
+ * 复现(v6.7.2 及之前):BSON 解码把 0x07 直接 toString('hex'),ObjectId 的
5
+ * 类型在协议边界就丢了。同一 24-hex 的 ObjectId 与 String 在真实 MongoDB 里
6
+ * 是两个不同的键,这里却判为重复:insert 第二篇文档被静默丢弃,
7
+ * insertMany ordered:false 也不报 writeErrors(实测两批数据分别丢
8
+ * 148/4744 与 164/4824,重载后的行数恰好等于去掉孪生对后的数量)。
9
+ *
10
+ * 修复:ObjectId 成为一等 JS 值(lib/objectid.js),BSON 编解码、
11
+ * .jsql 存储(TYPE.OID)、全库 === 判等点(valuesEqual)、$group/distinct
12
+ * 规范键全部类型感知;真重复以 E11000 writeErrors 显式上报。
13
+ */
14
+ const fs = require('fs');
15
+ const os = require('os');
16
+ const path = require('path');
17
+
18
+ const ROOT = path.join(__dirname, '..');
19
+ const { Database, createMongoServer } = require(path.join(ROOT, 'index.js'));
20
+ const { ObjectId } = require(path.join(ROOT, 'lib', 'objectid.js'));
21
+ const { bsonDocument, bsonReadDocument } = require(path.join(ROOT, 'lib', 'mongo_server.js'));
22
+
23
+ let pass = 0, fail = 0;
24
+ function ok(name, cond, extra) {
25
+ if (cond) { pass++; console.log('[OK] ', name); }
26
+ else { fail++; console.log('[FAIL]', name, extra !== undefined ? '-> ' + String(extra).slice(0, 300) : ''); }
27
+ }
28
+
29
+ (async () => {
30
+ // --- Layer 0: BSON 编解码往返 ---
31
+ {
32
+ const oid = ObjectId.fromHex('507f1f77bcf86cd799439011');
33
+ const doc = { _id: oid, s: 'plain string', twin: '507f1f77bcf86cd799439011', nested: { ref: oid }, arr: [oid, 'x'] };
34
+ const buf = bsonDocument(doc);
35
+ const back = bsonReadDocument(buf, 0).value;
36
+ ok('bson: _id decodes back to ObjectId', back._id instanceof ObjectId && back._id.toString() === '507f1f77bcf86cd799439011', back._id);
37
+ ok('bson: plain string stays a string', back.s === 'plain string');
38
+ ok('bson: same-hex string stays a string (twin distinct)', back.twin === '507f1f77bcf86cd799439011' && !(back.twin instanceof ObjectId));
39
+ ok('bson: nested ObjectId survives', back.nested.ref instanceof ObjectId && back.nested.ref.equals(oid));
40
+ ok('bson: ObjectId in array survives', Array.isArray(back.arr) && back.arr[0] instanceof ObjectId && back.arr[1] === 'x');
41
+ // 类型字节位:0x07 vs 0x02
42
+ const wire = bsonDocument({ _id: oid }).toString('hex');
43
+ ok('bson: ObjectId wire type is 0x07', wire.includes('075f696400'), wire.slice(0, 20));
44
+ }
45
+
46
+ // --- Layer 0.5: .jsql 存储往返 ---
47
+ {
48
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-oid-'));
49
+ const db = new Database(dir, { mode: 'hybrid' });
50
+ await db.createTable('c', {});
51
+ const oid = ObjectId.fromHex('507f1f77bcf86cd799439011');
52
+ await db.insert('c', { _id: oid, ref: ObjectId.fromHex('507f1f77bcf86cd799439011'), s: 'str' });
53
+ await db.stop();
54
+ const db2 = new Database(dir, { mode: 'hybrid' });
55
+ const rows = await db2.find('c', {});
56
+ ok('storage: ObjectId survives flush→reload as ObjectId',
57
+ rows.length === 1 && rows[0]._id instanceof ObjectId && rows[0]._id.toString() === '507f1f77bcf86cd799439011', rows[0] && rows[0]._id);
58
+ ok('storage: reloaded ObjectId equals original', rows[0]._id.equals(oid));
59
+ await db2.stop();
60
+ fs.rmSync(dir, { recursive: true, force: true });
61
+ }
62
+
63
+ // --- Layer 1: e2e —— 用户实际场景(孪生 _id 不再互撞) ---
64
+ {
65
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-oidmongo-'));
66
+ const srv = createMongoServer({ port: 0, noAuth: true, dataDir: dir });
67
+ await new Promise((res) => srv.listen(res));
68
+
69
+ const HEX = '507f1f77bcf86cd799439011';
70
+ const ins = await srv._dispatch('insert', {
71
+ insert: 'docs', $db: 'test',
72
+ documents: [
73
+ { _id: ObjectId.fromHex(HEX), kind: 'oid' },
74
+ { _id: HEX, kind: 'str' }, // 真实 MongoDB 中合法的另一个键
75
+ { _id: 3, kind: 'num' },
76
+ ],
77
+ });
78
+ ok('e2e: twin ObjectId+String _ids both accepted', ins.ok === 1 && ins.n === 3 && !ins.writeErrors, ins);
79
+
80
+ // 真重复必须显式报错而不是静默丢弃
81
+ const dup = await srv._dispatch('insert', {
82
+ insert: 'docs', $db: 'test', ordered: false,
83
+ documents: [{ _id: ObjectId.fromHex(HEX), kind: 'oid-dup' }, { _id: 4, kind: 'ok' }],
84
+ });
85
+ ok('e2e: true duplicate surfaces E11000 writeErrors',
86
+ dup.n === 1 && Array.isArray(dup.writeErrors) && dup.writeErrors.length === 1 && dup.writeErrors[0].code === 11000, dup);
87
+
88
+ await new Promise((res) => srv.close(res));
89
+
90
+ // 重载:两篇孪生文档都必须在
91
+ const srv2 = createMongoServer({ port: 0, noAuth: true, dataDir: dir });
92
+ await new Promise((res) => srv2.listen(res));
93
+ const found = await srv2._dispatch('find', { find: 'docs', filter: {}, $db: 'test' });
94
+ const batch = found.cursor ? found.cursor.firstBatch : [];
95
+ ok('e2e: all rows survive reload (twins intact)', batch.length === 4, batch.length);
96
+
97
+ // 按 ObjectId 查询命中 oid 文档而非孪生 string 文档
98
+ const byOid = await srv2._dispatch('find', { find: 'docs', filter: { _id: ObjectId.fromHex(HEX) }, $db: 'test' });
99
+ const oidRows = byOid.cursor ? byOid.cursor.firstBatch : [];
100
+ ok('e2e: find by ObjectId returns only the oid doc', oidRows.length === 1 && oidRows[0].kind === 'oid', oidRows);
101
+ const byStr = await srv2._dispatch('find', { find: 'docs', filter: { _id: HEX }, $db: 'test' });
102
+ const strRows = byStr.cursor ? byStr.cursor.firstBatch : [];
103
+ ok('e2e: find by String returns only the string doc', strRows.length === 1 && strRows[0].kind === 'str', strRows);
104
+
105
+ // $in / $type
106
+ const inMixed = await srv2._dispatch('find', { find: 'docs', filter: { _id: { $in: [ObjectId.fromHex(HEX), 3] } }, $db: 'test' });
107
+ const inRows = inMixed.cursor ? inMixed.cursor.firstBatch : [];
108
+ ok('e2e: $in [oid, 3] matches exactly oid+num docs', inRows.length === 2 && ['oid', 'num'].every(k => inRows.some(r => r.kind === k)), inRows);
109
+ const typeQ = await srv2._dispatch('find', { find: 'docs', filter: { _id: { $type: 'objectId' } }, $db: 'test' });
110
+ const typeRows = typeQ.cursor ? typeQ.cursor.firstBatch : [];
111
+ ok('e2e: $type objectId matches only oid doc', typeRows.length === 1 && typeRows[0].kind === 'oid', typeRows);
112
+
113
+ // $group:同字节 ObjectId 不拆组;ObjectId 与 String 仍分组
114
+ const agg = await srv2._dispatch('aggregate', {
115
+ aggregate: 'docs', $db: 'test',
116
+ pipeline: [{ $group: { _id: '$_id', n: { $sum: 1 } } }],
117
+ });
118
+ const groups = agg.cursor ? agg.cursor.firstBatch : [];
119
+ const oidGroup = groups.find(g => g._id instanceof ObjectId && g._id.toString() === HEX);
120
+ ok('e2e: $group keeps oid and string twins in separate groups', groups.length === 4, groups.map(g => String(g._id)));
121
+ ok('e2e: $group oid group has exactly 1 member', oidGroup && oidGroup.n === 1, oidGroup);
122
+
123
+ // $sort:重复 ObjectId 值(外键场景)不能让比较器失序(同字节不 ===)
124
+ await srv2._dispatch('insert', {
125
+ insert: 'refs', $db: 'test',
126
+ documents: [
127
+ { _id: 1, ref: ObjectId.fromHex(HEX), tag: 'a' },
128
+ { _id: 2, ref: ObjectId.fromHex(HEX), tag: 'b' },
129
+ { _id: 3, ref: ObjectId.fromHex('507f1f77bcf86cd799439022'), tag: 'c' },
130
+ ],
131
+ });
132
+ const sorted = await srv2._dispatch('aggregate', {
133
+ aggregate: 'refs', $db: 'test',
134
+ pipeline: [{ $sort: { ref: 1 } }],
135
+ });
136
+ const srows = sorted.cursor ? sorted.cursor.firstBatch : [];
137
+ ok('e2e: $sort by ObjectId field orders by bytes',
138
+ srows.length === 3 && srows.map(r => r.tag).join(',') === 'a,b,c', srows.map(r => r.tag));
139
+
140
+ // distinct:两种类型都作为独立值返回
141
+ const d = await srv2._dispatch('distinct', { distinct: 'docs', key: '_id', query: {}, $db: 'test' });
142
+ ok('e2e: distinct returns both twin values', d.values.length === 4, d.values.map(String));
143
+
144
+ // update/delete 按 ObjectId 精确命中
145
+ const upd = await srv2._dispatch('update', { update: 'docs', updates: [{ q: { _id: ObjectId.fromHex(HEX) }, u: { $set: { kind: 'oid-updated' } } }], $db: 'test' });
146
+ ok('e2e: update by ObjectId touches only the oid doc', upd.n === 1, upd);
147
+ const del = await srv2._dispatch('delete', { delete: 'docs', deletes: [{ q: { _id: ObjectId.fromHex(HEX) }, limit: 1 }], $db: 'test' });
148
+ ok('e2e: delete by ObjectId removes only the oid doc', del.n === 1, del);
149
+ const after = await srv2._dispatch('find', { find: 'docs', filter: {}, $db: 'test' });
150
+ const remain = after.cursor ? after.cursor.firstBatch : [];
151
+ ok('e2e: string twin still present after oid delete', remain.length === 3 && remain.some(r => r._id === HEX), remain.map(r => r._id));
152
+
153
+ await new Promise((res) => srv2.close(res));
154
+ fs.rmSync(dir, { recursive: true, force: true });
155
+ }
156
+
157
+ console.log(fail === 0 ? `\nALL ${pass} TESTS PASSED` : `\n${fail} FAILURES (${pass} passed)`);
158
+ process.exit(fail === 0 ? 0 : 1);
159
+ })().catch(e => {
160
+ console.error('FATAL:', e.message, e.stack);
161
+ process.exit(1);
162
+ });
@@ -0,0 +1,132 @@
1
+ /*
2
+ * 无 schema 表(Mongo collection 以 {} 建表)的持久化回归测试。
3
+ *
4
+ * 复现(v6.5.32–v6.6.4):
5
+ * buildEncoders(schema) 对空 schema 返回 0 个编码器 → 每行刷成 4 字节空桩
6
+ * → readTableSync 把首个 0 长行当块尾 → 重载后 0 行(数据全丢)。
7
+ *
8
+ * 修复:schema 为空时编码器改由行数据的字段并集生成;BSON Date 增加 TYPE.DATE
9
+ * 一等编码(此前会落进 OBJ 分支存成 {})。
10
+ */
11
+ const fs = require('fs');
12
+ const os = require('os');
13
+ const path = require('path');
14
+
15
+ const ROOT = path.join(__dirname, '..');
16
+ const { Database, createMongoServer } = require(path.join(ROOT, 'index.js'));
17
+
18
+ let pass = 0, fail = 0;
19
+ function ok(name, cond, extra) {
20
+ if (cond) { pass++; console.log('[OK] ', name); }
21
+ else { fail++; console.log('[FAIL]', name, extra !== undefined ? '-> ' + JSON.stringify(extra, (k, v) => typeof v === 'bigint' ? v + 'n' : v).slice(0, 300) : ''); }
22
+ }
23
+
24
+ (async () => {
25
+ // --- Layer 1: Database 级 —— schemaless 表 flush → 重启 → 数据完整 ---
26
+ {
27
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-persist-'));
28
+ const db = new Database(dir, { mode: 'hybrid' }); // 与 multiserver 共享引擎一致
29
+ await db.createTable('c', {});
30
+ await db.insert('c', [
31
+ { _id: 1, name: 'alice', nested: { k: 'v', deep: [1, 'x', null] } },
32
+ { _id: 2, name: 'bob', when: new Date(1700000000123), buf: Buffer.from([1, 2, 3]), big: 9007199254740993n, tags: [{ n: 1 }, { n: 2 }] },
33
+ { _id: 3 }, // 稀疏行:只有 _id
34
+ ]);
35
+ await db.stop(); // flush + 关闭
36
+
37
+ const db2 = new Database(dir, { mode: 'hybrid' });
38
+ const rows = await db2.find('c', {});
39
+ const byId = {};
40
+ for (const r of rows) byId[r._id] = r;
41
+
42
+ ok('schemaless: 3 rows survive reload', rows.length === 3, rows.length);
43
+ ok('schemaless: nested obj/array deep-equal',
44
+ JSON.stringify(byId[1].nested) === JSON.stringify({ k: 'v', deep: [1, 'x', null] }), byId[1]);
45
+ ok('schemaless: Date round-trips as Date with same ms',
46
+ byId[2].when instanceof Date && byId[2].when.getTime() === 1700000000123, byId[2].when);
47
+ ok('schemaless: Buffer round-trips',
48
+ Buffer.isBuffer(byId[2].buf) && byId[2].buf.equals(Buffer.from([1, 2, 3])), byId[2].buf);
49
+ ok('schemaless: >MAX_SAFE integer stays BigInt', typeof byId[2].big === 'bigint' && byId[2].big === 9007199254740993n, byId[2].big);
50
+ ok('schemaless: array of objects round-trips',
51
+ JSON.stringify(byId[2].tags) === JSON.stringify([{ n: 1 }, { n: 2 }]), byId[2].tags);
52
+ ok('schemaless: sparse row keeps _id', byId[3] && byId[3]._id === 3, byId[3]);
53
+ ok('schemaless: field missing in a row reloads as null (documented shortcut)', byId[3].name === null, byId[3].name);
54
+
55
+ // 重载后再写入再重载 —— 修复后第二轮回写不得破坏数据
56
+ await db2.insert('c', { _id: 4, extra: true });
57
+ await db2.stop();
58
+ const db3 = new Database(dir, { mode: 'hybrid' });
59
+ const rows3 = await db3.find('c', {});
60
+ ok('schemaless: second write→reload cycle keeps all rows', rows3.length === 4 && rows3.some(r => r._id === 4 && r.extra === true), rows3.length);
61
+ await db3.stop();
62
+ fs.rmSync(dir, { recursive: true, force: true });
63
+ }
64
+
65
+ // --- Layer 2: Mongo 服务器级 e2e —— 用户实际场景 ---
66
+ {
67
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-mongo-'));
68
+ const srv = createMongoServer({ port: 0, noAuth: true, dataDir: dir });
69
+ await new Promise((res) => srv.listen(res));
70
+
71
+ const ins = await srv._dispatch('insert', {
72
+ insert: 'docs', $db: 'test',
73
+ documents: [
74
+ { _id: 'a1', x: 1, nested: { k: 'v' } },
75
+ { _id: 'a2', x: 2, createdAt: new Date(1699999999999), list: [1, 2, { y: null }] },
76
+ ],
77
+ });
78
+ ok('mongo e2e: insert ok', ins.ok === 1 && ins.n === 2, ins);
79
+
80
+ await new Promise((res) => srv.close(res)); // close → engine.stop() → flush
81
+
82
+ const srv2 = createMongoServer({ port: 0, noAuth: true, dataDir: dir });
83
+ await new Promise((res) => srv2.listen(res));
84
+ const found = await srv2._dispatch('find', { find: 'docs', filter: {}, $db: 'test' });
85
+ const batch = found.cursor ? found.cursor.firstBatch : [];
86
+ const byId = {};
87
+ for (const r of batch) byId[r._id] = r;
88
+
89
+ ok('mongo e2e: docs survive server restart', batch.length === 2, batch);
90
+ ok('mongo e2e: nested field intact', byId.a1 && byId.a1.nested && byId.a1.nested.k === 'v', byId.a1);
91
+ ok('mongo e2e: Date field survives restart',
92
+ byId.a2 && byId.a2.createdAt instanceof Date && byId.a2.createdAt.getTime() === 1699999999999, byId.a2 && byId.a2.createdAt);
93
+ ok('mongo e2e: mixed array survives restart',
94
+ byId.a2 && JSON.stringify(byId.a2.list) === JSON.stringify([1, 2, { y: null }]), byId.a2 && byId.a2.list);
95
+
96
+ // 重启后 _id 唯一性检查仍工作(重载行参与查重)
97
+ const dup = await srv2._dispatch('insert', { insert: 'docs', $db: 'test', documents: [{ _id: 'a1', x: 9 }] });
98
+ ok('mongo e2e: duplicate _id rejected after reload', dup.n === 0, dup);
99
+ await new Promise((res) => srv2.close(res));
100
+ fs.rmSync(dir, { recursive: true, force: true });
101
+ }
102
+
103
+ // --- Layer 3: 兼容旧版单文件库 —— dataDir 下已有同名文件时必须走 legacy 模式 ---
104
+ {
105
+ // 旧版直接 Database 用法(mode 缺省 = 单文件模式)落一个库文件;
106
+ // 该模式下 stop() 不落盘,必须显式 save()。
107
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-legacy-'));
108
+ const legacy = new Database(path.join(dir, 'test'), { autoSave: true });
109
+ await legacy.createTable('legacy_t', { id: 'int', name: 'string' });
110
+ await legacy.insert('legacy_t', { id: 1, name: 'old' });
111
+ legacy.save();
112
+ await legacy.stop();
113
+ ok('legacy: single-file db written to disk', fs.statSync(path.join(dir, 'test')).isFile());
114
+
115
+ // 回归点:_createEngine 用 fs.statSync 探测旧文件,但模块没有 require('fs') 时
116
+ // ReferenceError 被空 catch 吞掉 → 恒走 hybrid → mkdirSync 对已存在文件抛 EEXIST,
117
+ // 旧库彻底不可访问。修复后应走 legacy 模式并正常读到数据。
118
+ const srv = createMongoServer({ port: 0, noAuth: true, dataDir: dir });
119
+ await new Promise((res) => srv.listen(res));
120
+ const found = await srv._dispatch('find', { find: 'legacy_t', filter: {}, $db: 'test' });
121
+ const batch = found.cursor ? found.cursor.firstBatch : [];
122
+ ok('legacy: mongo server reads legacy single-file db', batch.length === 1 && batch[0].name === 'old', batch);
123
+ await new Promise((res) => srv.close(res));
124
+ fs.rmSync(dir, { recursive: true, force: true });
125
+ }
126
+
127
+ console.log(fail === 0 ? `\nALL ${pass} TESTS PASSED` : `\n${fail} FAILURES (${pass} passed)`);
128
+ process.exit(fail === 0 ? 0 : 1);
129
+ })().catch(e => {
130
+ console.error('FATAL:', e.message, e.stack);
131
+ process.exit(1);
132
+ });