jsql-neo 6.7.6 → 6.8.0
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 +2 -2
- package/index.js +1 -1
- package/lib/database.js +2 -1
- package/lib/jsql_format.js +26 -4
- package/lib/mongo_server.js +64 -22
- package/lib/objectid.js +94 -0
- package/lib/sql.js +50 -6
- package/lib/table.js +7 -6
- package/package.json +3 -3
- package/test/issue-116.test.js +82 -0
- package/test/issue-117.test.js +102 -0
- package/test/mongo-objectid.test.js +162 -0
- package/test/mongo-persistence.test.js +132 -0
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.
|
|
6
|
+
> **v6.8.0** — 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
|

|
|
9
9
|

|
|
@@ -167,7 +167,7 @@ await db.start();
|
|
|
167
167
|
|---|---|---|
|
|
168
168
|
| Memory | `new Database(':memory:')` | Testing, caching |
|
|
169
169
|
| Disk | `new Database('./data/app')` | Production persistence |
|
|
170
|
-
| Hybrid | `new Database('./data', {
|
|
170
|
+
| Hybrid | `new Database('./data', { mode: 'hybrid', flushInterval: 3000 })` | Performance + durability |
|
|
171
171
|
|
|
172
172
|
File mode (`new Database('./data/db.json')`) is **not** an in-memory store that only
|
|
173
173
|
writes on exit. Every `insert` / `insertMany` / `update` / `updateById` / `remove` /
|
package/index.js
CHANGED
package/lib/database.js
CHANGED
|
@@ -28,6 +28,7 @@ function errorWithHint(codeKey, hint) {
|
|
|
28
28
|
return new JSQL_Error(t.code, msg, { codeKey });
|
|
29
29
|
}
|
|
30
30
|
const JSQLFormat = require('./jsql_format');
|
|
31
|
+
const { valuesEqual } = require('./objectid');
|
|
31
32
|
const {
|
|
32
33
|
createHookRegistry, applyPlugin, buildPluginContext, registerHook,
|
|
33
34
|
runHooks, getPluginApis
|
|
@@ -2052,7 +2053,7 @@ class Database {
|
|
|
2052
2053
|
// 做法:逐行比对所有字段值是否相等;是数字时当 1-based 行号。
|
|
2053
2054
|
if (id && typeof id === 'object') {
|
|
2054
2055
|
const keys = Object.keys(id);
|
|
2055
|
-
return table._rows.find(r => keys.every(k => r[k]
|
|
2056
|
+
return table._rows.find(r => keys.every(k => valuesEqual(r[k], id[k]))) || null;
|
|
2056
2057
|
}
|
|
2057
2058
|
const idx = Number(id);
|
|
2058
2059
|
if (!isNaN(idx)) return table._rows[idx - 1] || null;
|
package/lib/jsql_format.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const zlib = require('zlib');
|
|
2
2
|
const crypto = require('crypto');
|
|
3
3
|
const fs = require('fs');
|
|
4
|
+
const { ObjectId } = require('./objectid');
|
|
4
5
|
|
|
5
6
|
|
|
6
7
|
const SZ = {
|
|
@@ -12,7 +13,7 @@ const SZ = {
|
|
|
12
13
|
|
|
13
14
|
const BT = { FREE: 0, DATA: 1, IDX: 2 };
|
|
14
15
|
|
|
15
|
-
const TYPE = { NUL:0, BOL:1, I32:2, F64:3, STR:4, BUF:5, ARR:6, OBJ:7, I64:8 };
|
|
16
|
+
const TYPE = { NUL:0, BOL:1, I32:2, F64:3, STR:4, BUF:5, ARR:6, OBJ:7, I64:8, DATE:9, OID:10 };
|
|
16
17
|
|
|
17
18
|
function tag(v) {
|
|
18
19
|
if (v===null||v===undefined) return TYPE.NUL;
|
|
@@ -26,8 +27,12 @@ function tag(v) {
|
|
|
26
27
|
return TYPE.F64;
|
|
27
28
|
}
|
|
28
29
|
if (typeof v==='bigint') return TYPE.I64;
|
|
30
|
+
// Date 必须在通用对象分支之前识别:Object.keys(date) 为空,否则会存成 {}
|
|
31
|
+
if (v instanceof Date) return TYPE.DATE;
|
|
29
32
|
if (typeof v==='string') return TYPE.STR;
|
|
30
33
|
if (v instanceof Buffer) return TYPE.BUF;
|
|
34
|
+
// ObjectId 必须在通用对象分支之前识别,否则会退化成普通对象
|
|
35
|
+
if (v instanceof ObjectId) return TYPE.OID;
|
|
31
36
|
return Array.isArray(v)?TYPE.ARR:TYPE.OBJ;
|
|
32
37
|
}
|
|
33
38
|
|
|
@@ -39,6 +44,8 @@ function enc(v) {
|
|
|
39
44
|
case TYPE.I32: { const b=Buffer.alloc(5); b[0]=t; b.writeInt32LE(v,1); return b; }
|
|
40
45
|
case TYPE.I64: { const b=Buffer.alloc(9); b[0]=t; b.writeBigInt64LE(BigInt(v),1); return b; }
|
|
41
46
|
case TYPE.F64: { const b=Buffer.alloc(9); b[0]=t; b.writeDoubleLE(v,1); return b; }
|
|
47
|
+
case TYPE.DATE: { const b=Buffer.alloc(9); b[0]=t; b.writeBigInt64LE(BigInt(v.getTime()),1); return b; }
|
|
48
|
+
case TYPE.OID: { const b=Buffer.alloc(13); b[0]=t; v.bytes.copy(b,1); return b; }
|
|
42
49
|
case TYPE.STR: { const s=Buffer.from(v,'utf8'); const b=Buffer.alloc(5+s.length); b[0]=t; b.writeUInt32LE(s.length,1); s.copy(b,5); return b; }
|
|
43
50
|
case TYPE.BUF: { const b=Buffer.alloc(5+v.length); b[0]=t; b.writeUInt32LE(v.length,1); v.copy(b,5); return b; }
|
|
44
51
|
case TYPE.ARR: { const p=[Buffer.from([t]),enc(v.length)]; for(const i of v) p.push(enc(i)); return Buffer.concat(p); }
|
|
@@ -59,6 +66,8 @@ function dec(buf, off) {
|
|
|
59
66
|
return {v: safe ? Number(b) : b, off:off+8};
|
|
60
67
|
}
|
|
61
68
|
case TYPE.F64: return {v:buf.readDoubleLE(off),off:off+8};
|
|
69
|
+
case TYPE.DATE: return {v:new Date(Number(buf.readBigInt64LE(off))),off:off+8};
|
|
70
|
+
case TYPE.OID: return {v:new ObjectId(buf.subarray(off,off+12)),off:off+12};
|
|
62
71
|
case TYPE.STR: { const l=buf.readUInt32LE(off);off+=4; return {v:buf.toString('utf8',off,off+l),off:off+l}; }
|
|
63
72
|
case TYPE.BUF: { const l=buf.readUInt32LE(off);off+=4; return {v:Buffer.from(buf.subarray(off,off+l)),off:off+l}; }
|
|
64
73
|
case TYPE.ARR: { let r=dec(buf,off);off=r.off; const l=r.v,a=new Array(l); for(let i=0;i<l;i++){r=dec(buf,off);a[i]=r.v;off=r.off;} return {v:a,off}; }
|
|
@@ -111,8 +120,21 @@ function encRowInPlace(row, encoders, scratch, offStart) {
|
|
|
111
120
|
}
|
|
112
121
|
|
|
113
122
|
// Build reusable field encoders from schema
|
|
114
|
-
|
|
115
|
-
|
|
123
|
+
// 无 schema 的表(如 Mongo collection 以 {} 建表):字段从行数据本身取并集。
|
|
124
|
+
// 否则 0 个编码器会把每一行刷成 4 字节空桩,重载时一行都读不回来。
|
|
125
|
+
// shortcut: 某行缺的字段重载后变 null(不区分「缺字段」和「值为 null」),需要严格区分时再升级
|
|
126
|
+
function buildEncoders(schema, rows) {
|
|
127
|
+
const skip = f => f !== '_softDelete'; // _softDelete 是 schema 配置键,不会是数据字段
|
|
128
|
+
const schemaFields = Object.keys(schema || {}).filter(skip);
|
|
129
|
+
if (schemaFields.length > 0) {
|
|
130
|
+
return schemaFields.map(name => ({ name, nameEnc: enc(name) }));
|
|
131
|
+
}
|
|
132
|
+
const seen = new Set();
|
|
133
|
+
for (const row of rows || []) {
|
|
134
|
+
if (!row) continue;
|
|
135
|
+
for (const f of Object.keys(row)) if (skip(f)) seen.add(f);
|
|
136
|
+
}
|
|
137
|
+
return [...seen].map(name => ({ name, nameEnc: enc(name) }));
|
|
116
138
|
}
|
|
117
139
|
|
|
118
140
|
const encRow = encRowInPlace;
|
|
@@ -353,7 +375,7 @@ class JSQLFormat {
|
|
|
353
375
|
mkHeader(BT.DATA, curBlock, tableId).copy(buf);
|
|
354
376
|
|
|
355
377
|
// Pre-build field encoders once per table
|
|
356
|
-
const encoders = buildEncoders(schema);
|
|
378
|
+
const encoders = buildEncoders(schema, rows);
|
|
357
379
|
// Scratch buffer for row encoding (max row size fits in one block)
|
|
358
380
|
const scratch = Buffer.allocUnsafe(SZ.DATA);
|
|
359
381
|
|
package/lib/mongo_server.js
CHANGED
|
@@ -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)
|
|
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
|
-
|
|
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
|
-
|
|
431
|
-
|
|
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)
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
633
|
-
groups.
|
|
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 [
|
|
638
|
-
const
|
|
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
|
-
|
|
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
|
|
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' &&
|
|
796
|
-
if (op === '$in' && !(v
|
|
797
|
-
if (op === '$nin' && v
|
|
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]
|
|
852
|
+
} else if (!valuesEqual(row[k], cond)) {
|
|
811
853
|
return false;
|
|
812
854
|
}
|
|
813
855
|
}
|
package/lib/objectid.js
ADDED
|
@@ -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 };
|
package/lib/sql.js
CHANGED
|
@@ -3459,16 +3459,27 @@ function isBinaryValue(v) { return v instanceof BinaryValue; }
|
|
|
3459
3459
|
* Issue #111:按 Unicode code point 定位子串,返回 1-based 字符位置;
|
|
3460
3460
|
* 未找到返回 0(与 MySQL LOCATE/INSTR 一致)。空子串返回 1。
|
|
3461
3461
|
* 用 Array.from 把代理对拆成单个 code point,避免 emoji 被当成两个字符。
|
|
3462
|
+
*
|
|
3463
|
+
* Issue #116:新增 startPos(1-based,含起点),从该位置开始向右扫描,
|
|
3464
|
+
* 返回的仍是**绝对**字符位置(不是相对偏移),与 MySQL LOCATE(substr,str,pos) 一致:
|
|
3465
|
+
* LOCATE('bar','foobarbar',5) → 7
|
|
3466
|
+
* LOCATE('b','abcabc',3) → 5
|
|
3467
|
+
* LOCATE('b','abcabc',6) → 0
|
|
3468
|
+
* pos < 1 按 1 处理;pos 超出串长时只有空子串还可能命中(pos === len+1)。
|
|
3462
3469
|
*/
|
|
3463
|
-
function codePointIndexOf(needle, haystack) {
|
|
3470
|
+
function codePointIndexOf(needle, haystack, startPos = 1) {
|
|
3464
3471
|
const hay = Array.from(String(haystack));
|
|
3465
3472
|
const pat = Array.from(String(needle));
|
|
3466
|
-
|
|
3467
|
-
|
|
3473
|
+
let pos = Math.trunc(Number(startPos));
|
|
3474
|
+
if (!Number.isFinite(pos) || pos < 1) pos = 1;
|
|
3475
|
+
if (pat.length === 0) return pos <= hay.length + 1 ? pos : 0;
|
|
3476
|
+
if (pos > hay.length) return 0;
|
|
3477
|
+
for (let i = pos - 1; i + pat.length <= hay.length; i++) {
|
|
3478
|
+
let hit = true;
|
|
3468
3479
|
for (let j = 0; j < pat.length; j++) {
|
|
3469
|
-
if (hay[i + j] !== pat[j])
|
|
3480
|
+
if (hay[i + j] !== pat[j]) { hit = false; break; }
|
|
3470
3481
|
}
|
|
3471
|
-
return i + 1;
|
|
3482
|
+
if (hit) return i + 1;
|
|
3472
3483
|
}
|
|
3473
3484
|
return 0;
|
|
3474
3485
|
}
|
|
@@ -4732,6 +4743,34 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4732
4743
|
case 'MOD': return (args[0] == null || args[1] === 0) ? null : args[0] % args[1];
|
|
4733
4744
|
case 'POWER': case 'POW': return (args[0] == null || args[1] == null) ? null : finiteOrNull(Math.pow(args[0], args[1]));
|
|
4734
4745
|
case 'SQRT': return args[0] == null ? null : finiteOrNull(Math.sqrt(args[0]));
|
|
4746
|
+
// #117:这些函数在 MATH_SCALAR_FNS 里声明了,却没有 case 分支,落到
|
|
4747
|
+
// default 静默返回 NULL。定义域外(LOG(0)、ASIN(2)、COT(0)…)按 MySQL
|
|
4748
|
+
// 返回 NULL,统一走 finiteOrNull。
|
|
4749
|
+
case 'LOG': { // LOG(X) = ln(X);LOG(B, X) = 以 B 为底
|
|
4750
|
+
if (args[0] == null) return null;
|
|
4751
|
+
if (args.length < 2) return finiteOrNull(Math.log(args[0]));
|
|
4752
|
+
if (args[1] == null) return null;
|
|
4753
|
+
if (args[0] <= 0 || args[0] === 1 || args[1] <= 0) return null;
|
|
4754
|
+
return finiteOrNull(Math.log(args[1]) / Math.log(args[0]));
|
|
4755
|
+
}
|
|
4756
|
+
case 'LN': return args[0] == null ? null : finiteOrNull(Math.log(args[0]));
|
|
4757
|
+
case 'LOG10': return args[0] == null ? null : finiteOrNull(Math.log10(args[0]));
|
|
4758
|
+
case 'LOG2': return args[0] == null ? null : finiteOrNull(Math.log2(args[0]));
|
|
4759
|
+
case 'EXP': return args[0] == null ? null : finiteOrNull(Math.exp(args[0]));
|
|
4760
|
+
case 'SIN': return args[0] == null ? null : finiteOrNull(Math.sin(args[0]));
|
|
4761
|
+
case 'COS': return args[0] == null ? null : finiteOrNull(Math.cos(args[0]));
|
|
4762
|
+
case 'TAN': return args[0] == null ? null : finiteOrNull(Math.tan(args[0]));
|
|
4763
|
+
case 'COT': return args[0] == null ? null : finiteOrNull(1 / Math.tan(args[0]));
|
|
4764
|
+
case 'ASIN': return args[0] == null ? null : finiteOrNull(Math.asin(args[0]));
|
|
4765
|
+
case 'ACOS': return args[0] == null ? null : finiteOrNull(Math.acos(args[0]));
|
|
4766
|
+
case 'ATAN': { // ATAN(X);ATAN(Y, X) 等同 ATAN2(Y, X)
|
|
4767
|
+
if (args[0] == null) return null;
|
|
4768
|
+
if (args.length < 2) return finiteOrNull(Math.atan(args[0]));
|
|
4769
|
+
return args[1] == null ? null : finiteOrNull(Math.atan2(args[0], args[1]));
|
|
4770
|
+
}
|
|
4771
|
+
case 'ATAN2': return (args[0] == null || args[1] == null) ? null : finiteOrNull(Math.atan2(args[0], args[1]));
|
|
4772
|
+
case 'DEGREES': return args[0] == null ? null : finiteOrNull(args[0] * 180 / Math.PI);
|
|
4773
|
+
case 'RADIANS': return args[0] == null ? null : finiteOrNull(args[0] * Math.PI / 180);
|
|
4735
4774
|
case 'IFNULL': case 'NVL': return args[0] != null ? args[0] : args[1];
|
|
4736
4775
|
case 'COALESCE': {
|
|
4737
4776
|
// 不能直接 return find(...):全都取不到值时 find 返回 undefined,
|
|
@@ -4785,8 +4824,13 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4785
4824
|
}
|
|
4786
4825
|
case 'LOCATE': {
|
|
4787
4826
|
if (args[0] == null || args[1] == null) return null;
|
|
4827
|
+
// Issue #116:三参形式 LOCATE(substr, str, pos) 必须从 pos 开始(含 pos)扫描,
|
|
4828
|
+
// 返回绝对 1-based 字符位置;此前 pos 被静默忽略,导致结果错误。
|
|
4829
|
+
// 任一参数为 NULL 时返回 NULL(与 MySQL 一致)。
|
|
4830
|
+
const startPos = args.length > 2 ? args[2] : 1;
|
|
4831
|
+
if (startPos == null) return null;
|
|
4788
4832
|
// Issue #111:按 code point 定位,返回**字符**位置(不是 UTF-16 code unit 下标)
|
|
4789
|
-
return codePointIndexOf(String(args[0]), String(args[1]));
|
|
4833
|
+
return codePointIndexOf(String(args[0]), String(args[1]), startPos);
|
|
4790
4834
|
}
|
|
4791
4835
|
case 'INSTR': {
|
|
4792
4836
|
// INSTR(str, substr):参数顺序与 LOCATE(substr, str) 相反。
|
package/lib/table.js
CHANGED
|
@@ -9,6 +9,7 @@ const BTree = require('./btree');
|
|
|
9
9
|
const { createRowCache } = require('./row_cache');
|
|
10
10
|
const { validateDateType, now } = require('./date-types');
|
|
11
11
|
const { createError, JSQL_Error } = require('./errors');
|
|
12
|
+
const { ObjectId, valuesEqual, arrayIncludesValue } = require('./objectid');
|
|
12
13
|
|
|
13
14
|
// ---------------------------------------------------------------------------
|
|
14
15
|
// DEFAULT 表达式求值(Issue #72)
|
|
@@ -1644,7 +1645,7 @@ class Table {
|
|
|
1644
1645
|
|
|
1645
1646
|
const value = this._resolvePath(row, field);
|
|
1646
1647
|
|
|
1647
|
-
if (condition !== null && typeof condition === 'object' && !Array.isArray(condition) && !(condition instanceof RegExp)) {
|
|
1648
|
+
if (condition !== null && typeof condition === 'object' && !Array.isArray(condition) && !(condition instanceof RegExp) && !(condition instanceof ObjectId)) {
|
|
1648
1649
|
const keys = Object.keys(condition);
|
|
1649
1650
|
const isOperator = keys.every(k => k.startsWith('$'));
|
|
1650
1651
|
if (isOperator && keys.length > 0) {
|
|
@@ -1659,7 +1660,7 @@ class Table {
|
|
|
1659
1660
|
}
|
|
1660
1661
|
}
|
|
1661
1662
|
} else {
|
|
1662
|
-
if (value
|
|
1663
|
+
if (!valuesEqual(value, condition)) return false;
|
|
1663
1664
|
}
|
|
1664
1665
|
}
|
|
1665
1666
|
return true;
|
|
@@ -1667,14 +1668,14 @@ class Table {
|
|
|
1667
1668
|
|
|
1668
1669
|
_matchOperator(value, op, target) {
|
|
1669
1670
|
switch (op) {
|
|
1670
|
-
case '$eq': return value
|
|
1671
|
-
case '$ne': return value
|
|
1671
|
+
case '$eq': return valuesEqual(value, target);
|
|
1672
|
+
case '$ne': return !valuesEqual(value, target);
|
|
1672
1673
|
case '$gt': return value > target;
|
|
1673
1674
|
case '$gte': return value >= target;
|
|
1674
1675
|
case '$lt': return value < target;
|
|
1675
1676
|
case '$lte': return value <= target;
|
|
1676
|
-
case '$in': return Array.isArray(target) && target
|
|
1677
|
-
case '$nin': return Array.isArray(target) && !target
|
|
1677
|
+
case '$in': return Array.isArray(target) && arrayIncludesValue(target, value);
|
|
1678
|
+
case '$nin': return Array.isArray(target) && !arrayIncludesValue(target, value);
|
|
1678
1679
|
case '$like':
|
|
1679
1680
|
if (typeof value !== 'string' || typeof target !== 'string') return false;
|
|
1680
1681
|
{
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jsql-neo",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.8.0",
|
|
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/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",
|
|
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/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/issue-117.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/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",
|
|
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/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/issue-117.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",
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/* ---- Issue #116:LOCATE(substr, str, pos) 必须尊重第 3 个参数 pos ---- */
|
|
2
|
+
/*
|
|
3
|
+
* MySQL 8.0 语义(LOCATE(substr, str, pos)):
|
|
4
|
+
* - 从位置 pos 开始(**含** pos)向右找 substr;
|
|
5
|
+
* - 返回 substr 首次出现的**绝对** 1-based 字符位置(不是相对偏移);
|
|
6
|
+
* - 找不到返回 0;任一参数为 NULL 返回 NULL;
|
|
7
|
+
* - pos < 1 按 1 处理。
|
|
8
|
+
*
|
|
9
|
+
* 此前 `applyScalarFunction` 的 LOCATE 分支只把 args[0]/args[1] 交给
|
|
10
|
+
* codePointIndexOf(needle, haystack),args[2] 从未被读取 —— 三参形式
|
|
11
|
+
* 静默退化成两参形式,返回一个"看起来合理"但错误的位置。
|
|
12
|
+
*
|
|
13
|
+
* 参考值:
|
|
14
|
+
* LOCATE('b','abcabc',1) = 2 LOCATE('bar','foobarbar',5) = 7
|
|
15
|
+
* LOCATE('b','abcabc',3) = 5 LOCATE('b','abcabc',6) = 0
|
|
16
|
+
*
|
|
17
|
+
* node test/issue-116.test.js
|
|
18
|
+
*/
|
|
19
|
+
const path = require('path');
|
|
20
|
+
const ROOT = path.join(__dirname, '..');
|
|
21
|
+
const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
|
|
22
|
+
|
|
23
|
+
let pass = 0, fail = 0;
|
|
24
|
+
function ok(name, cond, got) {
|
|
25
|
+
if (cond) { pass++; console.log('[OK] ' + name); }
|
|
26
|
+
else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
(async () => {
|
|
30
|
+
const db = new Database(':memory:', { autoSave: false });
|
|
31
|
+
const q = async (sql) => {
|
|
32
|
+
const r = await executeSQL(db, sql, { safety: false });
|
|
33
|
+
return r.rows[0][0];
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
// ---------- issue 的差分表:pos 必须生效 ----------
|
|
37
|
+
ok("LOCATE('b','abcabc') = 2", await q("SELECT LOCATE('b','abcabc')") === 2, await q("SELECT LOCATE('b','abcabc')"));
|
|
38
|
+
ok("LOCATE('b','abcabc',1) = 2", await q("SELECT LOCATE('b','abcabc',1)") === 2, await q("SELECT LOCATE('b','abcabc',1)"));
|
|
39
|
+
ok("LOCATE('b','abcabc',3) = 5", await q("SELECT LOCATE('b','abcabc',3)") === 5, await q("SELECT LOCATE('b','abcabc',3)"));
|
|
40
|
+
ok("LOCATE('b','abcabc',5) = 5", await q("SELECT LOCATE('b','abcabc',5)") === 5, await q("SELECT LOCATE('b','abcabc',5)"));
|
|
41
|
+
ok("LOCATE('b','abcabc',6) = 0", await q("SELECT LOCATE('b','abcabc',6)") === 0, await q("SELECT LOCATE('b','abcabc',6)"));
|
|
42
|
+
ok("LOCATE('bar','foobarbar',5) = 7", await q("SELECT LOCATE('bar','foobarbar',5)") === 7, await q("SELECT LOCATE('bar','foobarbar',5)"));
|
|
43
|
+
|
|
44
|
+
// 返回的是绝对位置,不是相对偏移(若实现成相对偏移这里会得到 2/10)
|
|
45
|
+
ok("LOCATE('bar','foobarbar',4) = 4", await q("SELECT LOCATE('bar','foobarbar',4)") === 4, await q("SELECT LOCATE('bar','foobarbar',4)"));
|
|
46
|
+
ok("LOCATE('bar','foobarbar',7) = 7", await q("SELECT LOCATE('bar','foobarbar',7)") === 7, await q("SELECT LOCATE('bar','foobarbar',7)"));
|
|
47
|
+
ok("LOCATE('bar','foobarbar',8) = 0(剩 'ar' 不够长)", await q("SELECT LOCATE('bar','foobarbar',8)") === 0, await q("SELECT LOCATE('bar','foobarbar',8)"));
|
|
48
|
+
|
|
49
|
+
// ---------- 边界 ----------
|
|
50
|
+
ok("LOCATE('b','abcabc',0) = 2(pos<1 按 1)", await q("SELECT LOCATE('b','abcabc',0)") === 2, await q("SELECT LOCATE('b','abcabc',0)"));
|
|
51
|
+
ok("LOCATE('b','abcabc',-5) = 2(pos<1 按 1)", await q("SELECT LOCATE('b','abcabc',-5)") === 2, await q("SELECT LOCATE('b','abcabc',-5)"));
|
|
52
|
+
ok("LOCATE('b','abcabc',7) = 0(pos>len)", await q("SELECT LOCATE('b','abcabc',7)") === 0, await q("SELECT LOCATE('b','abcabc',7)"));
|
|
53
|
+
ok("LOCATE('b','abcabc',99) = 0", await q("SELECT LOCATE('b','abcabc',99)") === 0, await q("SELECT LOCATE('b','abcabc',99)"));
|
|
54
|
+
ok("LOCATE('b','abcabc',3.9) = 5(pos 取整)", await q("SELECT LOCATE('b','abcabc',3.9)") === 5, await q("SELECT LOCATE('b','abcabc',3.9)"));
|
|
55
|
+
|
|
56
|
+
// 空子串:两参形式仍为 1(行为不变);三参形式为 pos(MySQL 同)
|
|
57
|
+
ok("LOCATE('','abc') = 1", await q("SELECT LOCATE('','abc')") === 1, await q("SELECT LOCATE('','abc')"));
|
|
58
|
+
ok("LOCATE('','abc',3) = 3", await q("SELECT LOCATE('','abc',3)") === 3, await q("SELECT LOCATE('','abc',3)"));
|
|
59
|
+
|
|
60
|
+
// ---------- NULL 传播 ----------
|
|
61
|
+
ok("LOCATE(NULL,'abc',2) IS NULL", await q("SELECT LOCATE(NULL,'abc',2)") === null, await q("SELECT LOCATE(NULL,'abc',2)"));
|
|
62
|
+
ok("LOCATE('b',NULL,2) IS NULL", await q("SELECT LOCATE('b',NULL,2)") === null, await q("SELECT LOCATE('b',NULL,2)"));
|
|
63
|
+
ok("LOCATE('b','abcabc',NULL) IS NULL", await q("SELECT LOCATE('b','abcabc',NULL)") === null, await q("SELECT LOCATE('b','abcabc',NULL)"));
|
|
64
|
+
|
|
65
|
+
// ---------- Unicode:pos 与返回值都按 code point 计(Issue #111 语义)----------
|
|
66
|
+
// 'a🚀b🚀' = a 🚀 b 🚀 字符位置:1 2 3 4
|
|
67
|
+
ok("LOCATE('b','a🚀b🚀',1) = 3", await q("SELECT LOCATE('b','a🚀b🚀',1)") === 3, await q("SELECT LOCATE('b','a🚀b🚀',1)"));
|
|
68
|
+
ok("LOCATE('🚀','a🚀b🚀',2) = 2", await q("SELECT LOCATE('🚀','a🚀b🚀',2)") === 2, await q("SELECT LOCATE('🚀','a🚀b🚀',2)"));
|
|
69
|
+
ok("LOCATE('🚀','a🚀b🚀',3) = 4", await q("SELECT LOCATE('🚀','a🚀b🚀',3)") === 4, await q("SELECT LOCATE('🚀','a🚀b🚀',3)"));
|
|
70
|
+
ok("LOCATE('🚀','a🚀b🚀',5) = 0", await q("SELECT LOCATE('🚀','a🚀b🚀',5)") === 0, await q("SELECT LOCATE('🚀','a🚀b🚀',5)"));
|
|
71
|
+
|
|
72
|
+
// ---------- 两参形式与 INSTR 不受影响 ----------
|
|
73
|
+
ok("LOCATE('bar','foobarbar') = 4", await q("SELECT LOCATE('bar','foobarbar')") === 4, await q("SELECT LOCATE('bar','foobarbar')"));
|
|
74
|
+
ok("INSTR('abcabc','b') = 2", await q("SELECT INSTR('abcabc','b')") === 2, await q("SELECT INSTR('abcabc','b')"));
|
|
75
|
+
ok("INSTR('foobarbar','bar') = 4", await q("SELECT INSTR('foobarbar','bar')") === 4, await q("SELECT INSTR('foobarbar','bar')"));
|
|
76
|
+
|
|
77
|
+
console.log(`\n${pass} passed, ${fail} failed`);
|
|
78
|
+
process.exit(fail === 0 ? 0 : 1);
|
|
79
|
+
})().catch(e => {
|
|
80
|
+
console.log('[FAIL] unexpected exception: ' + e.stack.split('\n').slice(0, 3).join('\n'));
|
|
81
|
+
process.exit(1);
|
|
82
|
+
});
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/* ---- Issue #117:MATH_SCALAR_FNS 里声明的 15 个数学函数必须真正求值 ---- */
|
|
2
|
+
/*
|
|
3
|
+
* LOG / LOG10 / LOG2 / LN / EXP / SIN / COS / TAN / ASIN / ACOS / ATAN /
|
|
4
|
+
* ATAN2 / DEGREES / RADIANS / COT 此前在 applyScalarFunction 里没有 case
|
|
5
|
+
* 分支,落到 default 静默返回 NULL。
|
|
6
|
+
*
|
|
7
|
+
* MySQL 8.0 语义:
|
|
8
|
+
* - 任一参数为 NULL → NULL;
|
|
9
|
+
* - 定义域外(LOG(0)、LN(-1)、ASIN(2)、LOG(1, x)…)→ NULL;
|
|
10
|
+
* - LOG(X) 为自然对数,LOG(B, X) 为以 B 为底;ATAN(Y, X) 等同 ATAN2(Y, X)。
|
|
11
|
+
*
|
|
12
|
+
* node test/issue-117.test.js
|
|
13
|
+
*/
|
|
14
|
+
const path = require('path');
|
|
15
|
+
const ROOT = path.join(__dirname, '..');
|
|
16
|
+
const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
|
|
17
|
+
|
|
18
|
+
let pass = 0, fail = 0;
|
|
19
|
+
function ok(name, cond, got) {
|
|
20
|
+
if (cond) { pass++; console.log('[OK] ' + name); }
|
|
21
|
+
else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
|
|
22
|
+
}
|
|
23
|
+
const near = (a, b) => typeof a === 'number' && Math.abs(a - b) < 1e-12;
|
|
24
|
+
|
|
25
|
+
(async () => {
|
|
26
|
+
const db = new Database(':memory:', { autoSave: false });
|
|
27
|
+
const q = async (sql) => {
|
|
28
|
+
const r = await executeSQL(db, sql, { safety: false });
|
|
29
|
+
return r.rows[0][0];
|
|
30
|
+
};
|
|
31
|
+
const eq = async (expr, want) => {
|
|
32
|
+
const got = await q('SELECT ' + expr);
|
|
33
|
+
ok(`${expr} = ${want}`, want === null ? got === null : near(got, want), got);
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
// ---------- issue 里的复现语句 ----------
|
|
37
|
+
{
|
|
38
|
+
const r = await executeSQL(db,
|
|
39
|
+
'SELECT LOG2(8), LOG10(100), LN(1), EXP(0), SIN(0), COS(0), TAN(0), DEGREES(3.141592653589793), RADIANS(180)',
|
|
40
|
+
{ safety: false });
|
|
41
|
+
const want = [3, 2, 0, 1, 0, 1, 0, 180, Math.PI];
|
|
42
|
+
ok('issue 复现语句', r.rows[0].length === want.length && r.rows[0].every((v, i) => near(v, want[i])), r.rows[0]);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ---------- 每个函数的取值 ----------
|
|
46
|
+
await eq('LOG(EXP(1))', 1);
|
|
47
|
+
await eq('LOG(2, 8)', 3);
|
|
48
|
+
await eq('LOG(10, 1000)', 3);
|
|
49
|
+
await eq('LN(EXP(2))', 2);
|
|
50
|
+
await eq('LOG10(1000)', 3);
|
|
51
|
+
await eq('LOG2(1024)', 10);
|
|
52
|
+
await eq('EXP(1)', Math.E);
|
|
53
|
+
await eq('SIN(1.5707963267948966)', 1);
|
|
54
|
+
await eq('COS(3.141592653589793)', -1);
|
|
55
|
+
await eq('TAN(0.7853981633974483)', Math.tan(Math.PI / 4));
|
|
56
|
+
await eq('COT(1)', 1 / Math.tan(1));
|
|
57
|
+
await eq('ASIN(1)', Math.PI / 2);
|
|
58
|
+
await eq('ACOS(1)', 0);
|
|
59
|
+
await eq('ATAN(1)', Math.PI / 4);
|
|
60
|
+
await eq('ATAN(1, 1)', Math.PI / 4);
|
|
61
|
+
await eq('ATAN(-1, -1)', Math.atan2(-1, -1));
|
|
62
|
+
await eq('ATAN2(1, 1)', Math.PI / 4);
|
|
63
|
+
await eq('ATAN2(1, 0)', Math.PI / 2);
|
|
64
|
+
await eq('DEGREES(3.141592653589793)', 180);
|
|
65
|
+
await eq('RADIANS(90)', Math.PI / 2);
|
|
66
|
+
await eq("EXP('0')", 1);
|
|
67
|
+
|
|
68
|
+
// ---------- 定义域外 → NULL(不能漏出 NaN / Infinity)----------
|
|
69
|
+
await eq('LOG(0)', null);
|
|
70
|
+
await eq('LN(-1)', null);
|
|
71
|
+
await eq('LOG10(0)', null);
|
|
72
|
+
await eq('LOG2(-8)', null);
|
|
73
|
+
await eq('LOG(1, 8)', null);
|
|
74
|
+
await eq('LOG(-2, 8)', null);
|
|
75
|
+
await eq('LOG(2, 0)', null);
|
|
76
|
+
await eq('ASIN(2)', null);
|
|
77
|
+
await eq('ACOS(-1.5)', null);
|
|
78
|
+
await eq('COT(0)', null);
|
|
79
|
+
await eq('EXP(1000)', null);
|
|
80
|
+
|
|
81
|
+
// ---------- NULL 传播 ----------
|
|
82
|
+
for (const expr of ['LOG(NULL)', 'LOG(NULL, 8)', 'LOG(2, NULL)', 'LN(NULL)', 'LOG10(NULL)', 'LOG2(NULL)',
|
|
83
|
+
'EXP(NULL)', 'SIN(NULL)', 'COS(NULL)', 'TAN(NULL)', 'COT(NULL)', 'ASIN(NULL)', 'ACOS(NULL)',
|
|
84
|
+
'ATAN(NULL)', 'ATAN(1, NULL)', 'ATAN2(NULL, 1)', 'ATAN2(1, NULL)', 'DEGREES(NULL)', 'RADIANS(NULL)']) {
|
|
85
|
+
await eq(expr, null);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ---------- BigInt 入参降级为 number(issue #38 的路径)----------
|
|
89
|
+
await eq('LOG2(9007199254740993)', 53);
|
|
90
|
+
|
|
91
|
+
// ---------- 用在表数据上 ----------
|
|
92
|
+
await executeSQL(db, 'CREATE TABLE m (id INT, x DOUBLE)', { safety: false });
|
|
93
|
+
await executeSQL(db, 'INSERT INTO m VALUES (1, 100), (2, 0), (3, NULL)', { safety: false });
|
|
94
|
+
const rows = (await executeSQL(db, 'SELECT id, LOG10(x) AS l FROM m ORDER BY id', { safety: false })).rows;
|
|
95
|
+
ok('LOG10 列计算:[2, NULL, NULL]', JSON.stringify(rows.map(r => r[1])) === '[2,null,null]', rows);
|
|
96
|
+
|
|
97
|
+
console.log(`\n${pass} passed, ${fail} failed`);
|
|
98
|
+
process.exit(fail === 0 ? 0 : 1);
|
|
99
|
+
})().catch(e => {
|
|
100
|
+
console.log('[FAIL] unexpected exception: ' + e.stack.split('\n').slice(0, 3).join('\n'));
|
|
101
|
+
process.exit(1);
|
|
102
|
+
});
|
|
@@ -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
|
+
});
|