jsql-neo 6.8.9 → 6.8.10
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 +1 -1
- package/index.js +1 -1
- package/lib/database.js +17 -0
- package/lib/mongo_server.js +46 -4
- package/lib/redis_server.js +27 -1
- package/package.json +3 -3
- package/test/issue-312-320.test.js +232 -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.8.
|
|
6
|
+
> **v6.8.10** — 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
|

|
package/index.js
CHANGED
package/lib/database.js
CHANGED
|
@@ -143,7 +143,24 @@ class Database {
|
|
|
143
143
|
this._autoSaveTimer = null;
|
|
144
144
|
this._loading = false;
|
|
145
145
|
this._transaction = null;
|
|
146
|
+
// #320:encryptKey 的字节长度必须落在 AES 密钥长度集合 {16, 24, 32} 内。
|
|
147
|
+
// 此前构造阶段不校验,写入侧用 padEnd(32).slice(0, 32) 兜底:
|
|
148
|
+
// · 1 字节密钥被空格补齐到 32 字节 → 有效熵只有 1 字节,属可爆破弱密钥
|
|
149
|
+
// · 48 字节密钥被静默截断到 32 字节 → 用户高估密钥熵值
|
|
150
|
+
// 两者都只在事后审计密钥时才发现。这里构造时直接抛错。
|
|
146
151
|
this._encryptKey = options.encryptKey || null;
|
|
152
|
+
if (this._encryptKey !== null && this._encryptKey !== undefined) {
|
|
153
|
+
const keyBytes = Buffer.byteLength(String(this._encryptKey), 'utf8');
|
|
154
|
+
if (keyBytes !== 16 && keyBytes !== 24 && keyBytes !== 32) {
|
|
155
|
+
const err = new Error(
|
|
156
|
+
`Invalid encryptKey length: ${keyBytes} bytes (expected 16, 24 or 32)`
|
|
157
|
+
);
|
|
158
|
+
err.code = 'ER_INVALID_KEY';
|
|
159
|
+
err.errno = 1820;
|
|
160
|
+
err.sqlState = 'HY000';
|
|
161
|
+
throw err;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
147
164
|
this._versioning = options.versioning || false;
|
|
148
165
|
this._versions = {}; // tableName -> [{ rows, timestamp }]
|
|
149
166
|
this._maxVersions = options.maxVersions || 50;
|
package/lib/mongo_server.js
CHANGED
|
@@ -334,6 +334,25 @@ class MongoServer {
|
|
|
334
334
|
return defs;
|
|
335
335
|
}
|
|
336
336
|
|
|
337
|
+
/**
|
|
338
|
+
* 集合是否真实存在(#315)。
|
|
339
|
+
* 判据:engine 侧存在该表,或本进程已登记过该集合。
|
|
340
|
+
* 注意不能调用 _ensureCollection —— 那会把集合「创建」出来。
|
|
341
|
+
*/
|
|
342
|
+
async _collectionExists(name, db = null) {
|
|
343
|
+
const engine = await this._getEngine(db);
|
|
344
|
+
if (!engine) return false;
|
|
345
|
+
const key = (db || 'default') + '.' + name;
|
|
346
|
+
if (this._autoCollections && this._autoCollections.has(key)) return true;
|
|
347
|
+
if (this._dbCollections && this._dbCollections.has(db) && this._dbCollections.get(db).has(name)) return true;
|
|
348
|
+
if (typeof engine.hasTable === 'function') {
|
|
349
|
+
try { if (engine.hasTable(name)) return true; } catch (_) { /* ignore */ }
|
|
350
|
+
}
|
|
351
|
+
if (engine._tables && engine._tables[name]) return true;
|
|
352
|
+
if (engine._meta && engine._meta.tables && engine._meta.tables[name]) return true;
|
|
353
|
+
return false;
|
|
354
|
+
}
|
|
355
|
+
|
|
337
356
|
async _ensureCollection(name, db = null, sample = null) {
|
|
338
357
|
const engine = await this._getEngine(db);
|
|
339
358
|
const key = (db || 'default') + '.' + name;
|
|
@@ -751,7 +770,10 @@ class MongoServer {
|
|
|
751
770
|
const skip = typeof doc.skip === 'number' ? doc.skip : 0;
|
|
752
771
|
if (skip > 0) rows = rows.slice(skip);
|
|
753
772
|
const limit = typeof doc.limit === 'number' ? doc.limit : 0;
|
|
754
|
-
|
|
773
|
+
// #316:MongoDB 的 find 负 limit 表示「取 |limit| 条并单批返回」。
|
|
774
|
+
// 此前只判断 limit > 0,负值落到「不截断」分支,把整批文档全返回了。
|
|
775
|
+
const effLimit = limit < 0 ? -limit : limit;
|
|
776
|
+
if (effLimit > 0) rows = rows.slice(0, effLimit);
|
|
755
777
|
const projection = doc.projection || doc.fields;
|
|
756
778
|
if (projection) rows = rows.map(r => applyProjection(r, projection));
|
|
757
779
|
return { ok: 1, cursor: { id: { $long: 0 }, ns: `${this._dbOf(doc)}.${coll}`, firstBatch: rows } };
|
|
@@ -841,6 +863,12 @@ class MongoServer {
|
|
|
841
863
|
const coll = String(doc.listIndexes);
|
|
842
864
|
const dbName = this._dbOf(doc);
|
|
843
865
|
const key = dbName + '.' + coll;
|
|
866
|
+
// #315:对不存在的集合必须按协议报 nsNotFound(26),
|
|
867
|
+
// 此前兜底塞了一条虚构的 _id_ 索引并回 ok:1,
|
|
868
|
+
// 元数据巡检工具会把不存在的集合误判为「已有 _id_ 索引」。
|
|
869
|
+
if (!this._indexesByColl.has(key) && !(await this._collectionExists(coll, dbName))) {
|
|
870
|
+
return { ok: 0, errmsg: 'ns not found', code: 26 };
|
|
871
|
+
}
|
|
844
872
|
const list = this._indexesByColl.get(key) || [{ name: '_id_', columns: ['_id'], unique: true }];
|
|
845
873
|
const ns = `${dbName}.${coll}`;
|
|
846
874
|
const firstBatch = list.map(i => ({
|
|
@@ -965,8 +993,11 @@ class MongoServer {
|
|
|
965
993
|
for (const [k, v] of Object.entries(groupDef)) {
|
|
966
994
|
if (k === '_id' || v == null) continue;
|
|
967
995
|
if (typeof v === 'object') {
|
|
968
|
-
// $sum, $avg, $min, $max, $first, $last
|
|
969
|
-
|
|
996
|
+
// $sum, $avg, $min, $max, $first, $last, $push, $addToSet
|
|
997
|
+
// #312:$push / $addToSet 此前完全没实现 —— 累加器对象落到
|
|
998
|
+
// 取值链之外,doc[k] 从未被赋值,整个数组列静默缺失。
|
|
999
|
+
const acc = v.$sum ?? v.$avg ?? v.$min ?? v.$max ?? v.$first ?? v.$last
|
|
1000
|
+
?? v.$push ?? v.$addToSet;
|
|
970
1001
|
if (acc !== undefined) {
|
|
971
1002
|
const isNumeric = v.$sum !== undefined || v.$avg !== undefined;
|
|
972
1003
|
if (typeof acc === 'number') {
|
|
@@ -975,7 +1006,18 @@ class MongoServer {
|
|
|
975
1006
|
else if (v.$avg !== undefined) doc[k] = (doc[k] || 0) + acc;
|
|
976
1007
|
} else if (typeof acc === 'string' && acc.startsWith('$')) {
|
|
977
1008
|
const field = acc.slice(1);
|
|
978
|
-
if (v.$
|
|
1009
|
+
if (v.$push !== undefined) {
|
|
1010
|
+
// 数组累加器:按组内文档顺序收集该字段值(MongoDB 语义)
|
|
1011
|
+
doc[k] = grow.map(r => getPath(r, field));
|
|
1012
|
+
} else if (v.$addToSet !== undefined) {
|
|
1013
|
+
// 去重收集:按值深相等去重,保持首次出现顺序
|
|
1014
|
+
const seen = [];
|
|
1015
|
+
for (const r of grow) {
|
|
1016
|
+
const val = getPath(r, field);
|
|
1017
|
+
if (!seen.some(x => deepEqualMongo(x, val))) seen.push(val);
|
|
1018
|
+
}
|
|
1019
|
+
doc[k] = seen;
|
|
1020
|
+
} else if (v.$sum !== undefined) {
|
|
979
1021
|
const sum = grow.reduce((s, r) => s + (Number(getPath(r, field)) || 0), 0);
|
|
980
1022
|
doc[k] = (doc[k] || 0) + sum;
|
|
981
1023
|
} else if (v.$avg !== undefined) {
|
package/lib/redis_server.js
CHANGED
|
@@ -390,7 +390,33 @@ class RedisServer {
|
|
|
390
390
|
if (!v) return 0;
|
|
391
391
|
const secs = parseRedisInt(args[1]);
|
|
392
392
|
if (isNaN(secs)) throw new Error('ERR value is not an integer or out of range');
|
|
393
|
-
|
|
393
|
+
// #313:Redis 7 的 EXPIRE key seconds [NX|XX|GT|LT] 条件选项。
|
|
394
|
+
// 此前 args[2] 起的条件完全不解析:无条件覆盖已有 TTL 并恒返回 1,
|
|
395
|
+
// 拿 XX 做「只刷新已有临时键」的守卫时会给永久键静默加上过期时间。
|
|
396
|
+
// NX:仅当键当前**没有**过期时间时设置
|
|
397
|
+
// XX:仅当键当前**已有**过期时间时设置
|
|
398
|
+
// GT:仅当新 TTL 大于现有 TTL 时设置
|
|
399
|
+
// LT:仅当新 TTL 小于现有 TTL 时设置
|
|
400
|
+
// 条件不满足 → 返回 0 且不改动 TTL。
|
|
401
|
+
let cond = null;
|
|
402
|
+
for (let i = 2; i < args.length; i++) {
|
|
403
|
+
const opt = String(args[i]).toUpperCase();
|
|
404
|
+
if (opt === 'NX' || opt === 'XX' || opt === 'GT' || opt === 'LT') {
|
|
405
|
+
if (cond) throw new Error('ERR syntax error');
|
|
406
|
+
cond = opt;
|
|
407
|
+
} else {
|
|
408
|
+
// 未识别的选项必须报错,不能静默跳过
|
|
409
|
+
throw new Error('ERR syntax error');
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
const now = Date.now();
|
|
413
|
+
const currentTtl = v.ttl ? v.ttl - now : null; // null = 无过期时间
|
|
414
|
+
const newTtl = secs * 1000;
|
|
415
|
+
if (cond === 'NX' && currentTtl !== null) return 0;
|
|
416
|
+
if (cond === 'XX' && currentTtl === null) return 0;
|
|
417
|
+
if (cond === 'GT' && currentTtl !== null && newTtl <= currentTtl) return 0;
|
|
418
|
+
if (cond === 'LT' && currentTtl !== null && newTtl >= currentTtl) return 0;
|
|
419
|
+
v.ttl = now + newTtl;
|
|
394
420
|
this._scheduleSnapshot();
|
|
395
421
|
return 1;
|
|
396
422
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jsql-neo",
|
|
3
|
-
"version": "6.8.
|
|
3
|
+
"version": "6.8.10",
|
|
4
4
|
"description": "JSQL-NEO — Rust-powered embedded database with WASM, REST API, B-Tree indexes, WAL, crash recovery",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
@@ -52,12 +52,12 @@
|
|
|
52
52
|
"build:native": "node scripts/build-native.js",
|
|
53
53
|
"check:release": "node scripts/check-release-metadata.js",
|
|
54
54
|
"release:prep": "node scripts/release.js",
|
|
55
|
-
"test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js",
|
|
55
|
+
"test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js",
|
|
56
56
|
"test:parser": "node test/sql-parser.test.js",
|
|
57
57
|
"test:btree": "node test/btree.test.js",
|
|
58
58
|
"test:native": "node test/native.test.js",
|
|
59
59
|
"test:regress": "node test/regress-5.1.0.js",
|
|
60
|
-
"test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js",
|
|
60
|
+
"test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js",
|
|
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,232 @@
|
|
|
1
|
+
/* ---- 回归:#312 / #313 / #315 / #316 / #320 ---- */
|
|
2
|
+
/*
|
|
3
|
+
* #312 Mongo `$group` 的 `$push` / `$addToSet` 累加器静默无效:累加器对象落到
|
|
4
|
+
* 取值链之外,输出文档缺整列。
|
|
5
|
+
* #313 Redis `EXPIRE` 的 NX/XX/GT/LT 条件选项被静默忽略,无条件覆盖已有 TTL
|
|
6
|
+
* 并恒返回 1。
|
|
7
|
+
* #315 Mongo `listIndexes` 对不存在的集合伪造一条 `_id_` 唯一索引并回 ok:1,
|
|
8
|
+
* 未按协议报 nsNotFound(26)。
|
|
9
|
+
* #316 Mongo `find` 负 limit 被忽略,不按绝对值取单批,而是返回全部文档。
|
|
10
|
+
* #320 `encryptKey` 长度不校验:1 字节密钥被空格补齐到 32、48 字节密钥被静默
|
|
11
|
+
* 截断到 32,与文档承诺的 16/24/32 字节不符。
|
|
12
|
+
*/
|
|
13
|
+
const path = require('path');
|
|
14
|
+
const net = require('net');
|
|
15
|
+
const fs = require('fs');
|
|
16
|
+
const os = require('os');
|
|
17
|
+
const ROOT = path.join(__dirname, '..');
|
|
18
|
+
const { Database } = require(path.join(ROOT, 'index.js'));
|
|
19
|
+
const { createRedisServer } = require(path.join(ROOT, 'lib/redis_server.js'));
|
|
20
|
+
const { createMongoServer, bsonDocument, bsonReadDocument } = require(path.join(ROOT, 'lib/mongo_server.js'));
|
|
21
|
+
|
|
22
|
+
let pass = 0, fail = 0;
|
|
23
|
+
function ok(name, cond, got) {
|
|
24
|
+
if (cond) { pass++; console.log('[OK] ' + name); }
|
|
25
|
+
else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// ---------- Mongo 线协议客户端 ----------
|
|
29
|
+
function mongoOpMsg(doc) {
|
|
30
|
+
const p = bsonDocument(doc);
|
|
31
|
+
const h = Buffer.alloc(16);
|
|
32
|
+
h.writeInt32LE(16 + 4 + 1 + p.length, 0);
|
|
33
|
+
h.writeInt32LE(1, 4); h.writeInt32LE(0, 8); h.writeInt32LE(2013, 12);
|
|
34
|
+
return Buffer.concat([h, Buffer.alloc(4), Buffer.from([0]), p]);
|
|
35
|
+
}
|
|
36
|
+
function mongoCall(srv, doc) {
|
|
37
|
+
return new Promise((resolve, reject) => {
|
|
38
|
+
const sock = net.connect(srv._server.address().port, '127.0.0.1', () => sock.write(mongoOpMsg(doc)));
|
|
39
|
+
const chunks = [];
|
|
40
|
+
sock.on('error', reject);
|
|
41
|
+
sock.on('data', (c) => {
|
|
42
|
+
chunks.push(c);
|
|
43
|
+
const buf = Buffer.concat(chunks);
|
|
44
|
+
if (buf.length >= 16 && buf.length >= buf.readInt32LE(0)) {
|
|
45
|
+
try { resolve(bsonReadDocument(buf.slice(21), 0).value); }
|
|
46
|
+
catch (e) { reject(e); }
|
|
47
|
+
sock.end();
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ---------- Redis RESP 客户端 ----------
|
|
54
|
+
function redisFrame(args) {
|
|
55
|
+
const parts = args.map((a) => { const b = Buffer.from(String(a)); return '$' + b.length + '\r\n' + b + '\r\n'; });
|
|
56
|
+
return Buffer.from('*' + args.length + '\r\n' + parts.join(''));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function main() {
|
|
60
|
+
// ================= #320 encryptKey 长度校验 =================
|
|
61
|
+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-key-'));
|
|
62
|
+
const badKeys = ['x', '0123456789abcdef0123456789abcdef0123456789abcdef', 'short'];
|
|
63
|
+
for (const k of badKeys) {
|
|
64
|
+
let threw = null;
|
|
65
|
+
try {
|
|
66
|
+
const d = new Database(path.join(tmpDir, `db-${k.length}.json`), { encryptKey: k, autoSave: false });
|
|
67
|
+
d.close();
|
|
68
|
+
} catch (e) { threw = e; }
|
|
69
|
+
ok(`encryptKey 长度 ${Buffer.byteLength(k)} 字节被拒绝`, !!threw, threw && threw.message);
|
|
70
|
+
ok(`encryptKey 长度 ${Buffer.byteLength(k)} 字节报 ER_INVALID_KEY`,
|
|
71
|
+
threw && threw.code === 'ER_INVALID_KEY', threw && threw.code);
|
|
72
|
+
}
|
|
73
|
+
// 合法长度必须照常工作
|
|
74
|
+
for (const len of [16, 24, 32]) {
|
|
75
|
+
let db = null, threw = null;
|
|
76
|
+
try {
|
|
77
|
+
db = new Database(path.join(tmpDir, `good-${len}.json`), { encryptKey: 'k'.repeat(len), autoSave: false });
|
|
78
|
+
} catch (e) { threw = e; }
|
|
79
|
+
ok(`encryptKey 长度 ${len} 字节被接受`, !threw, threw && threw.message);
|
|
80
|
+
if (db) db.close();
|
|
81
|
+
}
|
|
82
|
+
// 多字节 UTF-8 按字节计数(不是字符数)
|
|
83
|
+
let utf8Threw = null;
|
|
84
|
+
try {
|
|
85
|
+
const d = new Database(path.join(tmpDir, 'utf8.json'), { encryptKey: '中'.repeat(8), autoSave: false });
|
|
86
|
+
d.close();
|
|
87
|
+
} catch (e) { utf8Threw = e; }
|
|
88
|
+
ok('encryptKey 按字节计数(8 个中文字 = 24 字节)被接受', !utf8Threw, utf8Threw && utf8Threw.message);
|
|
89
|
+
|
|
90
|
+
// ================= #313 Redis EXPIRE 条件选项 =================
|
|
91
|
+
const rsrv = createRedisServer({ port: 0, dataDir: null });
|
|
92
|
+
await new Promise((r) => rsrv.listen(r));
|
|
93
|
+
const rsock = net.connect(rsrv.server.address().port, '127.0.0.1');
|
|
94
|
+
await new Promise((r) => rsock.on('connect', r));
|
|
95
|
+
const rchunks = [];
|
|
96
|
+
rsock.on('data', (c) => rchunks.push(c));
|
|
97
|
+
const rsend = async (args) => {
|
|
98
|
+
rchunks.length = 0;
|
|
99
|
+
rsock.write(redisFrame(args));
|
|
100
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
101
|
+
return Buffer.concat(rchunks).toString('utf8');
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
await rsend(['SET', 'e', 'x']);
|
|
105
|
+
ok('SET 返回 +OK', (await rsend(['SET', 'e', 'x'])) === '+OK\r\n', null);
|
|
106
|
+
|
|
107
|
+
// XX:键无 TTL 时应返回 0 且不设置
|
|
108
|
+
ok('EXPIRE e 100 XX(无 TTL)返回 0', (await rsend(['EXPIRE', 'e', '100', 'XX'])) === ':0\r\n', null);
|
|
109
|
+
ok('EXPIRE e 100 XX 后 TTL 仍为 -1', (await rsend(['TTL', 'e'])) === ':-1\r\n', null);
|
|
110
|
+
|
|
111
|
+
// NX:键无 TTL 时应成功
|
|
112
|
+
ok('EXPIRE e 100 NX(无 TTL)返回 1', (await rsend(['EXPIRE', 'e', '100', 'NX'])) === ':1\r\n', null);
|
|
113
|
+
ok('EXPIRE e 100 NX 后 TTL = 100', (await rsend(['TTL', 'e'])) === ':100\r\n', null);
|
|
114
|
+
|
|
115
|
+
// NX:键已有 TTL 时应返回 0
|
|
116
|
+
ok('EXPIRE e 200 NX(已有 TTL)返回 0', (await rsend(['EXPIRE', 'e', '200', 'NX'])) === ':0\r\n', null);
|
|
117
|
+
ok('EXPIRE e 200 NX 后 TTL 未变', (await rsend(['TTL', 'e'])) === ':100\r\n', null);
|
|
118
|
+
|
|
119
|
+
// XX:键已有 TTL 时应成功
|
|
120
|
+
ok('EXPIRE e 300 XX(已有 TTL)返回 1', (await rsend(['EXPIRE', 'e', '300', 'XX'])) === ':1\r\n', null);
|
|
121
|
+
ok('EXPIRE e 300 XX 后 TTL = 300', (await rsend(['TTL', 'e'])) === ':300\r\n', null);
|
|
122
|
+
|
|
123
|
+
// GT:新 TTL 不大于现有 → 返回 0
|
|
124
|
+
ok('EXPIRE e 100 GT(新 TTL 更小)返回 0', (await rsend(['EXPIRE', 'e', '100', 'GT'])) === ':0\r\n', null);
|
|
125
|
+
ok('EXPIRE e 100 GT 后 TTL 未变', (await rsend(['TTL', 'e'])) === ':300\r\n', null);
|
|
126
|
+
|
|
127
|
+
// GT:新 TTL 大于现有 → 返回 1
|
|
128
|
+
ok('EXPIRE e 400 GT(新 TTL 更大)返回 1', (await rsend(['EXPIRE', 'e', '400', 'GT'])) === ':1\r\n', null);
|
|
129
|
+
ok('EXPIRE e 400 GT 后 TTL = 400', (await rsend(['TTL', 'e'])) === ':400\r\n', null);
|
|
130
|
+
|
|
131
|
+
// LT:新 TTL 不小于现有 → 返回 0
|
|
132
|
+
ok('EXPIRE e 400 LT(相等)返回 0', (await rsend(['EXPIRE', 'e', '400', 'LT'])) === ':0\r\n', null);
|
|
133
|
+
ok('EXPIRE e 100 LT(新 TTL 更小)返回 1', (await rsend(['EXPIRE', 'e', '100', 'LT'])) === ':1\r\n', null);
|
|
134
|
+
|
|
135
|
+
// 无条件 EXPIRE 仍照常工作
|
|
136
|
+
ok('EXPIRE e 100(无条件)返回 1', (await rsend(['EXPIRE', 'e', '100'])) === ':1\r\n', null);
|
|
137
|
+
|
|
138
|
+
// 未知选项必须报语法错误,不能静默忽略
|
|
139
|
+
const badOpt = await rsend(['EXPIRE', 'e', '100', 'ZZ']);
|
|
140
|
+
ok('EXPIRE 未知选项报 ERR syntax error', badOpt.startsWith('-ERR syntax error'), badOpt);
|
|
141
|
+
|
|
142
|
+
// 多个条件选项冲突
|
|
143
|
+
const twoOpt = await rsend(['EXPIRE', 'e', '100', 'NX', 'XX']);
|
|
144
|
+
ok('EXPIRE 同时给 NX/XX 报 ERR syntax error', twoOpt.startsWith('-ERR syntax error'), twoOpt);
|
|
145
|
+
|
|
146
|
+
rsock.destroy();
|
|
147
|
+
rsrv.stop();
|
|
148
|
+
|
|
149
|
+
// ================= Mongo 相关(#312 / #315 / #316)=================
|
|
150
|
+
const msrv = createMongoServer({ dataDir: ':memory:' });
|
|
151
|
+
await new Promise((r) => msrv.listen(r));
|
|
152
|
+
|
|
153
|
+
// #315:listIndexes 对不存在的集合必须报 nsNotFound
|
|
154
|
+
const missing = await mongoCall(msrv, { listIndexes: 'nope_coll', $db: 'test' });
|
|
155
|
+
ok('listIndexes 不存在的集合 ok = 0', missing.ok === 0, missing);
|
|
156
|
+
ok('listIndexes 不存在的集合 code = 26(nsNotFound)', missing.code === 26, missing);
|
|
157
|
+
ok('listIndexes 不存在的集合不含 _id_ 索引',
|
|
158
|
+
!missing.cursor || !(missing.cursor.firstBatch || []).length, missing);
|
|
159
|
+
|
|
160
|
+
// 存在的集合应正常返回 _id_ 索引
|
|
161
|
+
await mongoCall(msrv, { insert: 'nl', documents: [{ n: 1 }, { n: 2 }, { n: 3 }], $db: 'test' });
|
|
162
|
+
const existing = await mongoCall(msrv, { listIndexes: 'nl', $db: 'test' });
|
|
163
|
+
ok('listIndexes 已存在的集合 ok = 1', existing.ok === 1, existing);
|
|
164
|
+
ok('listIndexes 已存在的集合返回 _id_ 索引',
|
|
165
|
+
(existing.cursor.firstBatch || []).some(i => i.name === '_id_'), existing);
|
|
166
|
+
|
|
167
|
+
// #316:负 limit 按绝对值取单批
|
|
168
|
+
const negLimit = await mongoCall(msrv, { find: 'nl', filter: {}, limit: -2, $db: 'test' });
|
|
169
|
+
ok('find limit=-2 只返回 2 条', (negLimit.cursor.firstBatch || []).length === 2, negLimit);
|
|
170
|
+
const negLimit3 = await mongoCall(msrv, { find: 'nl', filter: {}, limit: -3, $db: 'test' });
|
|
171
|
+
ok('find limit=-3 返回 3 条', (negLimit3.cursor.firstBatch || []).length === 3, negLimit3);
|
|
172
|
+
const posLimit = await mongoCall(msrv, { find: 'nl', filter: {}, limit: 1, $db: 'test' });
|
|
173
|
+
ok('find limit=1 返回 1 条(不回归)', (posLimit.cursor.firstBatch || []).length === 1, posLimit);
|
|
174
|
+
const noLimit = await mongoCall(msrv, { find: 'nl', filter: {}, $db: 'test' });
|
|
175
|
+
ok('find 无 limit 返回全部(不回归)', (noLimit.cursor.firstBatch || []).length === 3, noLimit);
|
|
176
|
+
|
|
177
|
+
// #312:$group 的 $push / $addToSet
|
|
178
|
+
await mongoCall(msrv, { insert: 'gp', documents: [{ g: 'x', t: 1 }, { g: 'x', t: 2 }, { g: 'y', t: 5 }], $db: 'test' });
|
|
179
|
+
const push = await mongoCall(msrv, {
|
|
180
|
+
aggregate: 'gp', pipeline: [{ $group: { _id: '$g', vals: { $push: '$t' } } }], $db: 'test'
|
|
181
|
+
});
|
|
182
|
+
const pushRows = push.cursor.firstBatch || [];
|
|
183
|
+
const pushX = pushRows.find(r => r._id === 'x');
|
|
184
|
+
const pushY = pushRows.find(r => r._id === 'y');
|
|
185
|
+
ok('$push 输出文档含 vals 字段', pushX && pushX.vals !== undefined, pushRows);
|
|
186
|
+
ok('$push x 组 = [1,2]', Array.isArray(pushX && pushX.vals) && pushX.vals.length === 2
|
|
187
|
+
&& pushX.vals[0] === 1 && pushX.vals[1] === 2, pushX);
|
|
188
|
+
ok('$push y 组 = [5]', Array.isArray(pushY && pushY.vals) && pushY.vals.length === 1
|
|
189
|
+
&& pushY.vals[0] === 5, pushY);
|
|
190
|
+
|
|
191
|
+
const addToSet = await mongoCall(msrv, {
|
|
192
|
+
aggregate: 'gp', pipeline: [{ $group: { _id: '$g', vals: { $addToSet: '$t' } } }], $db: 'test'
|
|
193
|
+
});
|
|
194
|
+
const atsRows = addToSet.cursor.firstBatch || [];
|
|
195
|
+
const atsX = atsRows.find(r => r._id === 'x');
|
|
196
|
+
ok('$addToSet 输出文档含 vals 字段', atsX && atsX.vals !== undefined, atsRows);
|
|
197
|
+
ok('$addToSet x 组 = [1,2]', Array.isArray(atsX && atsX.vals) && atsX.vals.length === 2, atsX);
|
|
198
|
+
|
|
199
|
+
// 去重:同一组内插入重复值
|
|
200
|
+
await mongoCall(msrv, { insert: 'gp2', documents: [{ g: 'x', t: 1 }, { g: 'x', t: 1 }, { g: 'x', t: 2 }], $db: 'test' });
|
|
201
|
+
const ats2 = await mongoCall(msrv, {
|
|
202
|
+
aggregate: 'gp2', pipeline: [{ $group: { _id: '$g', vals: { $addToSet: '$t' } } }], $db: 'test'
|
|
203
|
+
});
|
|
204
|
+
const ats2X = (ats2.cursor.firstBatch || []).find(r => r._id === 'x');
|
|
205
|
+
ok('$addToSet 去重后只剩 2 个元素',
|
|
206
|
+
Array.isArray(ats2X && ats2X.vals) && ats2X.vals.length === 2, ats2X);
|
|
207
|
+
|
|
208
|
+
// $push 保留全部元素(含重复)
|
|
209
|
+
const push2 = await mongoCall(msrv, {
|
|
210
|
+
aggregate: 'gp2', pipeline: [{ $group: { _id: '$g', vals: { $push: '$t' } } }], $db: 'test'
|
|
211
|
+
});
|
|
212
|
+
const push2X = (push2.cursor.firstBatch || []).find(r => r._id === 'x');
|
|
213
|
+
ok('$push 保留重复元素(3 个)',
|
|
214
|
+
Array.isArray(push2X && push2X.vals) && push2X.vals.length === 3, push2X);
|
|
215
|
+
|
|
216
|
+
// 已有累加器不回归
|
|
217
|
+
const sum = await mongoCall(msrv, {
|
|
218
|
+
aggregate: 'gp', pipeline: [{ $group: { _id: '$g', total: { $sum: '$t' } } }], $db: 'test'
|
|
219
|
+
});
|
|
220
|
+
const sumX = (sum.cursor.firstBatch || []).find(r => r._id === 'x');
|
|
221
|
+
ok('$sum 不回归:x 组 = 3', sumX && sumX.total === 3, sumX);
|
|
222
|
+
|
|
223
|
+
msrv.close();
|
|
224
|
+
|
|
225
|
+
console.log(`\n${pass} passed, ${fail} failed`);
|
|
226
|
+
process.exit(fail === 0 ? 0 : 1);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
main().catch(e => {
|
|
230
|
+
console.log('[FAIL] unexpected exception: ' + (e.stack || e).split('\n').slice(0, 4).join('\n'));
|
|
231
|
+
process.exit(1);
|
|
232
|
+
});
|