jsql-neo 6.8.1 → 6.8.3
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 +4 -3
- package/index.d.ts +4 -1
- package/index.js +1 -1
- package/lib/cache.js +38 -11
- package/lib/client.js +1 -1
- package/lib/database.js +21 -2
- package/lib/mongo_server.js +177 -87
- package/lib/native_client.js +26 -0
- package/lib/nedb_compat.js +29 -3
- package/lib/sql.js +229 -38
- package/lib/sqlite_compat.js +12 -1
- package/lib/table.js +58 -1
- package/native/jsql-neo-native.node +0 -0
- package/nativesrc/jsql-neo-core/src/engine/hybrid.rs +7 -0
- package/nativesrc/jsql-neo-core/src/engine/memory.rs +5 -0
- package/nativesrc/jsql-neo-core/src/engine/mod.rs +2 -0
- package/nativesrc/jsql-neo-core/src/engine/table.rs +36 -0
- package/nativesrc/jsql-neo-native/src/lib.rs +5 -0
- package/nativesrc/jsql-neo-wasm/src/lib.rs +8 -0
- package/package.json +3 -3
- package/postinstall.js +27 -32
- package/test/issue-118-136.test.js +86 -0
- package/test/issue-127.test.js +38 -0
- package/test/issue-138-156.test.js +140 -0
- package/test/issue-86-99.test.js +2 -2
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.3** — 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
|

|
|
@@ -218,8 +218,9 @@ Full reference: [doc/sql-reference.md](doc/sql-reference.md).
|
|
|
218
218
|
| Base / utility | `BIN`, `OCT`, `HEX`, `UNHEX`, `CONV`, `BIT_LENGTH`, `CRC32`, `QUOTE`, `FIND_IN_SET`, `INSERT`, `FORMAT`, `INET_ATON` / `INET_NTOA`, `MAKE_SET`, `EXPORT_SET`, `SOUNDEX` |
|
|
219
219
|
| Exact integers | Values above `2^53` stay exact via BigInt; integer-math functions use exact paths, floating-point ones return DOUBLE |
|
|
220
220
|
|
|
221
|
-
`JSON_TYPE` / `JSON_DEPTH` follow **
|
|
222
|
-
(
|
|
221
|
+
`JSON_TYPE` / `JSON_DEPTH` follow **MySQL semantics**: `JSON_TYPE` returns uppercase
|
|
222
|
+
names (`OBJECT`, `ARRAY`, `STRING`, `INTEGER`, …), and `JSON_DEPTH` returns 1 for a
|
|
223
|
+
scalar or empty container, 2 for a non-empty object/array of scalars. See the SQL reference.
|
|
223
224
|
|
|
224
225
|
## Columnar storage (one-shot convert)
|
|
225
226
|
|
package/index.d.ts
CHANGED
|
@@ -140,7 +140,10 @@ declare namespace JSQLNeo {
|
|
|
140
140
|
run(...params: unknown[]): Promise<any>;
|
|
141
141
|
}
|
|
142
142
|
|
|
143
|
-
export class NativeJSQL extends JSQL {
|
|
143
|
+
export class NativeJSQL extends JSQL {
|
|
144
|
+
/** #126:Rust 侧列式聚合,返回 SUM/AVG/MIN/MAX 的 JSON 数值(旧二进制返回 null)。 */
|
|
145
|
+
aggregate(table: string, op: 'SUM' | 'AVG' | 'MIN' | 'MAX' | 'COUNT', field: string): Promise<number | null>;
|
|
146
|
+
}
|
|
144
147
|
|
|
145
148
|
export interface MysqlServerOptions {
|
|
146
149
|
port?: number;
|
package/index.js
CHANGED
package/lib/cache.js
CHANGED
|
@@ -36,8 +36,26 @@ class Cache {
|
|
|
36
36
|
return count;
|
|
37
37
|
}
|
|
38
38
|
keys(pattern = '*') {
|
|
39
|
-
|
|
40
|
-
|
|
39
|
+
// Redis glob:* / ? / [abc]、[!abc]、[a-c];其余正则元字符按字面转义
|
|
40
|
+
let src = '^';
|
|
41
|
+
const p = String(pattern);
|
|
42
|
+
for (let i = 0; i < p.length; i++) {
|
|
43
|
+
const c = p[i];
|
|
44
|
+
if (c === '*') { src += '.*'; continue; }
|
|
45
|
+
if (c === '?') { src += '.'; continue; }
|
|
46
|
+
if (c === '[') {
|
|
47
|
+
const close = p.indexOf(']', i + 1);
|
|
48
|
+
if (close > i + 1) {
|
|
49
|
+
let body = p.slice(i + 1, close).replace(/\\/g, '\\\\');
|
|
50
|
+
if (body[0] === '!' || body[0] === '^') body = '^' + body.slice(1);
|
|
51
|
+
src += '[' + body + ']';
|
|
52
|
+
i = close;
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
src += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
57
|
+
}
|
|
58
|
+
const regex = new RegExp(src + '$');
|
|
41
59
|
const result = [];
|
|
42
60
|
for (const key of this._getData().keys()) { if (!this._isExpired(key) && regex.test(key)) result.push(key); }
|
|
43
61
|
return result;
|
|
@@ -56,7 +74,9 @@ class Cache {
|
|
|
56
74
|
expire(key, seconds) {
|
|
57
75
|
const k = String(key);
|
|
58
76
|
if (!this._getData().has(k)) return 0;
|
|
59
|
-
|
|
77
|
+
const s = typeof seconds === 'bigint' ? seconds.toString() : String(seconds);
|
|
78
|
+
if (!/^[-+]?\d+$/.test(s.trim())) throw new Error('value is not an integer or out of range');
|
|
79
|
+
this._getExpires().set(k, Date.now() + Number(s) * 1000);
|
|
60
80
|
return 1;
|
|
61
81
|
}
|
|
62
82
|
ttl(key) {
|
|
@@ -74,12 +94,20 @@ class Cache {
|
|
|
74
94
|
decrby(key, decrement) { return this._incrby(key, -decrement); }
|
|
75
95
|
_incrby(key, delta) {
|
|
76
96
|
const k = String(key);
|
|
97
|
+
const isInt = (v) => typeof v === 'bigint'
|
|
98
|
+
|| (typeof v === 'number' && Number.isSafeInteger(v))
|
|
99
|
+
|| (typeof v === 'string' && /^[-+]?\d+$/.test(v.trim()));
|
|
100
|
+
if (!isInt(delta)) throw new Error('value is not an integer or out of range');
|
|
77
101
|
const cur = this._getData().get(k);
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
102
|
+
if (cur !== undefined && !isInt(cur)) throw new Error('value is not an integer or out of range');
|
|
103
|
+
const d = typeof delta === 'bigint' ? delta : BigInt(String(delta).trim());
|
|
104
|
+
const val = (cur === undefined ? 0n : BigInt(String(cur).trim())) + d;
|
|
105
|
+
if (val > 9223372036854775807n || val < -9223372036854775808n) {
|
|
106
|
+
throw new Error('increment or decrement would overflow');
|
|
107
|
+
}
|
|
108
|
+
this._getData().set(k, val.toString());
|
|
81
109
|
this._dirty = true;
|
|
82
|
-
return val;
|
|
110
|
+
return (val >= BigInt(Number.MIN_SAFE_INTEGER) && val <= BigInt(Number.MAX_SAFE_INTEGER)) ? Number(val) : val;
|
|
83
111
|
}
|
|
84
112
|
|
|
85
113
|
hset(key, field, value) {
|
|
@@ -186,10 +214,9 @@ class Cache {
|
|
|
186
214
|
if (!list || !Array.isArray(list) || list._type === 'hash') return [];
|
|
187
215
|
if (start < 0) start = Math.max(list.length + start, 0);
|
|
188
216
|
if (stop < 0) stop = list.length + stop;
|
|
189
|
-
stop
|
|
190
|
-
//
|
|
191
|
-
|
|
192
|
-
stop = Math.max(stop, 0);
|
|
217
|
+
// #145:stop 负数越界要保留负值,让 start > stop 生效返回 [];
|
|
218
|
+
// 只有非负 stop 才做列表长度上限钳制。
|
|
219
|
+
if (stop >= 0) stop = Math.min(stop, list.length - 1);
|
|
193
220
|
if (start > stop) return [];
|
|
194
221
|
return list.slice(start, stop + 1);
|
|
195
222
|
}
|
package/lib/client.js
CHANGED
|
@@ -26,7 +26,7 @@ class JSQL {
|
|
|
26
26
|
if (this._process) return;
|
|
27
27
|
const bp = binPath();
|
|
28
28
|
if (!fs.existsSync(bp)) {
|
|
29
|
-
throw new Error(`jsql-neo-server binary not found at ${bp}.
|
|
29
|
+
throw new Error(`jsql-neo-server binary not found at ${bp}. The HTTP client needs an external jsql-neo-server; use NativeJSQL for the embedded engine.`);
|
|
30
30
|
}
|
|
31
31
|
const args = [];
|
|
32
32
|
if (this.dataDir) {
|
package/lib/database.js
CHANGED
|
@@ -28,6 +28,10 @@ function errorWithHint(codeKey, hint) {
|
|
|
28
28
|
return new JSQL_Error(t.code, msg, { codeKey });
|
|
29
29
|
}
|
|
30
30
|
const JSQLFormat = require('./jsql_format');
|
|
31
|
+
|
|
32
|
+
// live 表达到该行数后也挂上行级 LRU:此前只有从磁盘 reload 的表才有
|
|
33
|
+
// rowCache,运行时新建的大表一直整表常驻,最终被整表驱逐或 OOM(#127)。
|
|
34
|
+
const ROW_CACHE_MIN_ROWS = 1000;
|
|
31
35
|
const { valuesEqual } = require('./objectid');
|
|
32
36
|
const {
|
|
33
37
|
createHookRegistry, applyPlugin, buildPluginContext, registerHook,
|
|
@@ -364,6 +368,12 @@ class Database {
|
|
|
364
368
|
_flushTableDelta(name) {
|
|
365
369
|
const table = this._tables[name];
|
|
366
370
|
if (!table) return;
|
|
371
|
+
// live 大表首次达到阈值时走一次全量写,借机挂上行级 rowCache;
|
|
372
|
+
// 之后 delta 写入会照常更新行定位符。
|
|
373
|
+
if (this._dirMode && !table._rowCache && table._rows.length >= ROW_CACHE_MIN_ROWS) {
|
|
374
|
+
this._flushTable(name);
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
367
377
|
const dirty = typeof table._peekDirtyRows === 'function'
|
|
368
378
|
? table._peekDirtyRows()
|
|
369
379
|
: { all: true, upserts: [], deletes: [] };
|
|
@@ -410,17 +420,26 @@ class Database {
|
|
|
410
420
|
const meta = this._meta.tables[name];
|
|
411
421
|
let file = meta && meta.file ? meta.file : encodeURIComponent(name) + '.jsql';
|
|
412
422
|
const fmt = new JSQLFormat(path.join(this._filePath, file));
|
|
423
|
+
let keepHandleOpen = false;
|
|
413
424
|
try {
|
|
414
425
|
const pkField = Object.keys(table._schema).find(f => table._schema[f].primaryKey) || null;
|
|
415
426
|
fmt.writeTable(name, table._schema, table._rows, pkField);
|
|
416
427
|
this._meta.tables[name] = { file, schema: table._schema };
|
|
428
|
+
// live 大表首次全量写完后挂上行级 LRU,让后续内存淘汰按行回退。
|
|
429
|
+
if (this._dirMode && !table._rowCache && table._rows.length >= ROW_CACHE_MIN_ROWS) {
|
|
430
|
+
const locators = fmt.scanLocators(name);
|
|
431
|
+
if (locators.length > 0) {
|
|
432
|
+
table._loadRowRefs(locators, (block, off) => fmt.readRowAt(block, off), fmt);
|
|
433
|
+
keepHandleOpen = true;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
417
436
|
// 整表重写改变了每一行的物理位置,用新文件的定位符重置缓存
|
|
418
|
-
if (typeof table._resetRowLocators === 'function') {
|
|
437
|
+
if (!keepHandleOpen && typeof table._resetRowLocators === 'function') {
|
|
419
438
|
table._resetRowLocators(fmt.scanLocators(name));
|
|
420
439
|
}
|
|
421
440
|
if (typeof table._clearDirtyRows === 'function') table._clearDirtyRows();
|
|
422
441
|
} finally {
|
|
423
|
-
fmt._close();
|
|
442
|
+
if (!keepHandleOpen) fmt._close();
|
|
424
443
|
}
|
|
425
444
|
}
|
|
426
445
|
|
package/lib/mongo_server.js
CHANGED
|
@@ -16,6 +16,7 @@ const path = require('path');
|
|
|
16
16
|
const zlib = require('zlib');
|
|
17
17
|
const Database = require('./database');
|
|
18
18
|
const { ObjectId, valuesEqual, arrayIncludesValue, mapKey, orAnyElement, anyElementRange } = require('./objectid');
|
|
19
|
+
const { getPath, setPath, unsetPath, applyModifier } = require('./nedb_compat');
|
|
19
20
|
|
|
20
21
|
const OP_MSG = 2013;
|
|
21
22
|
const OP_COMPRESSED = 2012;
|
|
@@ -148,6 +149,74 @@ function bsonReadValue(buf, pos, type, end) {
|
|
|
148
149
|
}
|
|
149
150
|
}
|
|
150
151
|
|
|
152
|
+
function cloneDoc(v) {
|
|
153
|
+
if (v instanceof ObjectId) return v;
|
|
154
|
+
if (Array.isArray(v)) return v.map(cloneDoc);
|
|
155
|
+
if (v && typeof v === 'object') {
|
|
156
|
+
const out = {};
|
|
157
|
+
for (const k of Object.keys(v)) out[k] = cloneDoc(v[k]);
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
return v;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function applyProjection(doc, spec) {
|
|
164
|
+
if (!spec || typeof spec !== 'object') return doc;
|
|
165
|
+
const entries = Object.entries(spec);
|
|
166
|
+
const inclusion = entries.filter(([k, v]) => k !== '_id' && !!v);
|
|
167
|
+
const exclusion = entries.filter(([k, v]) => k !== '_id' && !v);
|
|
168
|
+
if (inclusion.length && exclusion.length) {
|
|
169
|
+
throw new Error('Cannot do inclusion and exclusion in the same projection (except _id)');
|
|
170
|
+
}
|
|
171
|
+
if (inclusion.length) {
|
|
172
|
+
const out = {};
|
|
173
|
+
if (spec._id === undefined || !!spec._id) {
|
|
174
|
+
const id = getPath(doc, '_id');
|
|
175
|
+
if (id !== undefined) setPath(out, '_id', id);
|
|
176
|
+
}
|
|
177
|
+
for (const [k] of inclusion) {
|
|
178
|
+
const v = getPath(doc, k);
|
|
179
|
+
if (v !== undefined) setPath(out, k, cloneDoc(v));
|
|
180
|
+
}
|
|
181
|
+
return out;
|
|
182
|
+
}
|
|
183
|
+
const out = cloneDoc(doc);
|
|
184
|
+
for (const [k] of exclusion) unsetPath(out, k);
|
|
185
|
+
if (spec._id === 0 || spec._id === false) unsetPath(out, '_id');
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/* ------------------------------------------------------------------ */
|
|
190
|
+
/* 聚合表达式求值($project 派生字段) */
|
|
191
|
+
/* ------------------------------------------------------------------ */
|
|
192
|
+
|
|
193
|
+
function evalMongoExpr(expr, doc) {
|
|
194
|
+
if (expr === null || typeof expr !== 'object') {
|
|
195
|
+
if (typeof expr === 'string' && expr.startsWith('$')) return getPath(doc, expr.slice(1));
|
|
196
|
+
return expr;
|
|
197
|
+
}
|
|
198
|
+
if (Array.isArray(expr)) return expr.map(x => evalMongoExpr(x, doc));
|
|
199
|
+
const args = (v) => (Array.isArray(v) ? v : [v]);
|
|
200
|
+
let result = expr;
|
|
201
|
+
for (const [op, arg] of Object.entries(expr)) {
|
|
202
|
+
switch (op) {
|
|
203
|
+
case '$literal': result = arg; break;
|
|
204
|
+
case '$toUpper': result = String(evalMongoExpr(arg, doc)).toUpperCase(); break;
|
|
205
|
+
case '$toLower': result = String(evalMongoExpr(arg, doc)).toLowerCase(); break;
|
|
206
|
+
case '$add': result = args(arg).reduce((s, x) => s + (Number(evalMongoExpr(x, doc)) || 0), 0); break;
|
|
207
|
+
case '$subtract': { const a = args(arg); result = (Number(evalMongoExpr(a[0], doc)) || 0) - (Number(evalMongoExpr(a[1], doc)) || 0); break; }
|
|
208
|
+
case '$multiply': result = args(arg).reduce((s, x) => s * (Number(evalMongoExpr(x, doc)) || 0), 1); break;
|
|
209
|
+
case '$divide': { const a = args(arg); result = (Number(evalMongoExpr(a[0], doc)) || 0) / (Number(evalMongoExpr(a[1], doc)) || 1); break; }
|
|
210
|
+
case '$concat': result = args(arg).map(x => String(evalMongoExpr(x, doc))).join(''); break;
|
|
211
|
+
case '$abs': result = Math.abs(Number(evalMongoExpr(arg, doc)) || 0); break;
|
|
212
|
+
case '$cond': { const c = args(arg); result = evalMongoExpr(c[0], doc) ? evalMongoExpr(c[1], doc) : evalMongoExpr(c[2], doc); break; }
|
|
213
|
+
case '$ifNull': { const c = args(arg); const v = evalMongoExpr(c[0], doc); result = v === null || v === undefined ? evalMongoExpr(c[1], doc) : v; break; }
|
|
214
|
+
default: return expr;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return result;
|
|
218
|
+
}
|
|
219
|
+
|
|
151
220
|
/* ------------------------------------------------------------------ */
|
|
152
221
|
/* 排序(find 与 aggregate $sort 共用) */
|
|
153
222
|
/* ------------------------------------------------------------------ */
|
|
@@ -156,7 +225,7 @@ function sortRows(rows, sortSpec) {
|
|
|
156
225
|
const sortKeys = Object.entries(sortSpec);
|
|
157
226
|
return [...rows].sort((a, b) => {
|
|
158
227
|
for (const [k, dir] of sortKeys) {
|
|
159
|
-
const av = a
|
|
228
|
+
const av = getPath(a, k); const bv = getPath(b, k);
|
|
160
229
|
// valuesEqual:同字节 ObjectId 不 ===,缺这一道相等短路时
|
|
161
230
|
// 相等键会破坏排序稳定性(sort+skip/limit 分页会丢/重文档)
|
|
162
231
|
if (av === bv || valuesEqual(av, bv)) continue;
|
|
@@ -570,6 +639,8 @@ class MongoServer {
|
|
|
570
639
|
if (skip > 0) rows = rows.slice(skip);
|
|
571
640
|
const limit = typeof doc.limit === 'number' ? doc.limit : 0;
|
|
572
641
|
if (limit > 0) rows = rows.slice(0, limit);
|
|
642
|
+
const projection = doc.projection || doc.fields;
|
|
643
|
+
if (projection) rows = rows.map(r => applyProjection(r, projection));
|
|
573
644
|
return { ok: 1, cursor: { id: { $long: 0 }, ns: `${this._dbOf(doc)}.${coll}`, firstBatch: rows } };
|
|
574
645
|
}
|
|
575
646
|
case 'getMore':
|
|
@@ -579,6 +650,7 @@ class MongoServer {
|
|
|
579
650
|
const engine = await this._ensureCollection(coll, this._dbOf(doc));
|
|
580
651
|
let n = 0;
|
|
581
652
|
const updates = doc.updates || [];
|
|
653
|
+
try {
|
|
582
654
|
for (const u of updates) {
|
|
583
655
|
const q = u.q || {};
|
|
584
656
|
const set = u.u && u.u.$set ? u.u.$set : (u.u || {});
|
|
@@ -605,6 +677,9 @@ class MongoServer {
|
|
|
605
677
|
}
|
|
606
678
|
}
|
|
607
679
|
}
|
|
680
|
+
} catch (e) {
|
|
681
|
+
return { ok: 0, errmsg: e.message, code: 9, n, nModified: 0 };
|
|
682
|
+
}
|
|
608
683
|
return { ok: 1, n, nModified: n };
|
|
609
684
|
}
|
|
610
685
|
case 'delete': {
|
|
@@ -640,30 +715,60 @@ class MongoServer {
|
|
|
640
715
|
rows = sortRows(rows, stage.$sort);
|
|
641
716
|
}
|
|
642
717
|
else if (stage.$project) {
|
|
643
|
-
const
|
|
718
|
+
const plain = {};
|
|
719
|
+
const exprFields = {};
|
|
720
|
+
for (const [k, v] of Object.entries(stage.$project)) {
|
|
721
|
+
if (v && typeof v === 'object' && !Array.isArray(v) && !(v instanceof ObjectId)) exprFields[k] = v;
|
|
722
|
+
else plain[k] = v;
|
|
723
|
+
}
|
|
644
724
|
rows = rows.map((r) => {
|
|
645
|
-
const out =
|
|
646
|
-
for (const [k,
|
|
647
|
-
if (k === '_id' && v === 0) continue;
|
|
648
|
-
if (v === 0) continue;
|
|
649
|
-
if (typeof v === 'string' && v.startsWith('$')) out[k] = r[v.slice(1)];
|
|
650
|
-
else if (v === 1) out[k] = r[k];
|
|
651
|
-
else if (v === 0) { /* exclude */ }
|
|
652
|
-
else out[k] = v;
|
|
653
|
-
}
|
|
725
|
+
const out = applyProjection(r, plain);
|
|
726
|
+
for (const [k, e] of Object.entries(exprFields)) setPath(out, k, evalMongoExpr(e, r));
|
|
654
727
|
return out;
|
|
655
728
|
});
|
|
656
729
|
}
|
|
657
730
|
else if (stage.$unwind) {
|
|
658
|
-
const
|
|
731
|
+
const cfg = typeof stage.$unwind === 'string'
|
|
732
|
+
? { path: stage.$unwind }
|
|
733
|
+
: (stage.$unwind || {});
|
|
734
|
+
const field = String(cfg.path || '').replace(/^\$/, '');
|
|
735
|
+
const preserve = cfg.preserveNullAndEmptyArrays === true;
|
|
659
736
|
const out = [];
|
|
660
737
|
for (const r of rows) {
|
|
661
|
-
const arr = r
|
|
662
|
-
if (!Array.isArray(arr) || arr.length === 0) {
|
|
663
|
-
|
|
738
|
+
const arr = getPath(r, field);
|
|
739
|
+
if (!Array.isArray(arr) || arr.length === 0) {
|
|
740
|
+
if (preserve) out.push(cloneDoc(r));
|
|
741
|
+
continue;
|
|
742
|
+
}
|
|
743
|
+
for (const item of arr) {
|
|
744
|
+
const nr = cloneDoc(r);
|
|
745
|
+
setPath(nr, field, cloneDoc(item));
|
|
746
|
+
out.push(nr);
|
|
747
|
+
}
|
|
664
748
|
}
|
|
665
749
|
rows = out;
|
|
666
750
|
}
|
|
751
|
+
else if (stage.$lookup) {
|
|
752
|
+
const cfg = stage.$lookup || {};
|
|
753
|
+
const from = String(cfg.from || '');
|
|
754
|
+
const localField = String(cfg.localField || '');
|
|
755
|
+
const foreignField = String(cfg.foreignField || '');
|
|
756
|
+
const as = String(cfg.as || '');
|
|
757
|
+
if (!from || !localField || !foreignField || !as) {
|
|
758
|
+
throw new Error('$lookup requires from, localField, foreignField and as');
|
|
759
|
+
}
|
|
760
|
+
const foreignEngine = await this._ensureCollection(from, this._dbOf(doc));
|
|
761
|
+
const foreignRows = await foreignEngine.find(from, {});
|
|
762
|
+
rows = rows.map((r) => {
|
|
763
|
+
const lv = getPath(r, localField);
|
|
764
|
+
const locals = Array.isArray(lv) ? lv : [lv];
|
|
765
|
+
const matched = foreignRows.filter(fr =>
|
|
766
|
+
orAnyElement(getPath(fr, foreignField), el => locals.some(l => valuesEqual(l, el))));
|
|
767
|
+
const nr = cloneDoc(r);
|
|
768
|
+
setPath(nr, as, matched.map(fr => cloneDoc(fr)));
|
|
769
|
+
return nr;
|
|
770
|
+
});
|
|
771
|
+
}
|
|
667
772
|
else if (stage.$group) {
|
|
668
773
|
const groups = new Map();
|
|
669
774
|
const groupDef = stage.$group;
|
|
@@ -673,7 +778,7 @@ class MongoServer {
|
|
|
673
778
|
if (groupDef._id !== undefined) {
|
|
674
779
|
// explicit _id expression
|
|
675
780
|
if (typeof groupDef._id === 'string' && groupDef._id.startsWith('$')) {
|
|
676
|
-
gk = row
|
|
781
|
+
gk = getPath(row, groupDef._id.slice(1));
|
|
677
782
|
} else {
|
|
678
783
|
gk = groupDef._id;
|
|
679
784
|
}
|
|
@@ -705,38 +810,38 @@ class MongoServer {
|
|
|
705
810
|
} else if (typeof acc === 'string' && acc.startsWith('$')) {
|
|
706
811
|
const field = acc.slice(1);
|
|
707
812
|
if (v.$sum !== undefined) {
|
|
708
|
-
const sum = grow.reduce((s, r) => s + (Number(r
|
|
813
|
+
const sum = grow.reduce((s, r) => s + (Number(getPath(r, field)) || 0), 0);
|
|
709
814
|
doc[k] = (doc[k] || 0) + sum;
|
|
710
815
|
} else if (v.$avg !== undefined) {
|
|
711
816
|
// Issue #45:null/undefined 不计入分子的同时也不计入分母;
|
|
712
817
|
// 全空组返回 null(MongoDB 语义),而不是 0。
|
|
713
818
|
const vals = grow
|
|
714
|
-
.map(r => r
|
|
819
|
+
.map(r => getPath(r, field))
|
|
715
820
|
.filter(x => x !== null && x !== undefined)
|
|
716
821
|
.map(Number)
|
|
717
822
|
.filter(x => !Number.isNaN(x));
|
|
718
823
|
doc[k] = vals.length ? vals.reduce((a, b) => a + b, 0) / vals.length : null;
|
|
719
824
|
} else if (v.$min !== undefined) {
|
|
720
|
-
const vals = grow.map(r => r
|
|
825
|
+
const vals = grow.map(r => getPath(r, field)).filter(v => v != null);
|
|
721
826
|
let best = null;
|
|
722
827
|
for (const x of vals) if (best === null || x < best) best = x;
|
|
723
828
|
doc[k] = best;
|
|
724
829
|
} else if (v.$max !== undefined) {
|
|
725
|
-
const vals = grow.map(r => r
|
|
830
|
+
const vals = grow.map(r => getPath(r, field)).filter(v => v != null);
|
|
726
831
|
let best = null;
|
|
727
832
|
for (const x of vals) if (best === null || x > best) best = x;
|
|
728
833
|
doc[k] = best;
|
|
729
834
|
} else if (v.$first !== undefined) {
|
|
730
|
-
doc[k] = grow[0] ? grow[0]
|
|
835
|
+
doc[k] = grow[0] ? getPath(grow[0], field) : null;
|
|
731
836
|
} else if (v.$last !== undefined) {
|
|
732
|
-
doc[k] = grow[grow.length - 1] ? grow[grow.length - 1]
|
|
837
|
+
doc[k] = grow[grow.length - 1] ? getPath(grow[grow.length - 1], field) : null;
|
|
733
838
|
}
|
|
734
839
|
}
|
|
735
840
|
}
|
|
736
841
|
} else if (typeof v === 'string' && v.startsWith('$')) {
|
|
737
842
|
// direct field reference as accumulator value
|
|
738
843
|
const field = v.slice(1);
|
|
739
|
-
if (!doc.hasOwnProperty(k)) doc[k] = grow[0] ? grow[0]
|
|
844
|
+
if (!doc.hasOwnProperty(k)) doc[k] = grow[0] ? getPath(grow[0], field) : null;
|
|
740
845
|
}
|
|
741
846
|
}
|
|
742
847
|
out.push(doc);
|
|
@@ -769,43 +874,20 @@ class MongoServer {
|
|
|
769
874
|
|
|
770
875
|
async _patchRows(engine, coll, rows, updateDoc) {
|
|
771
876
|
const entries = [];
|
|
772
|
-
|
|
773
|
-
const
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
const key = this._rowKey(engine, coll, r);
|
|
780
|
-
if (key !== undefined) entries.push([key, { ...updateDoc }]);
|
|
781
|
-
}
|
|
782
|
-
} else {
|
|
783
|
-
// 有操作符,需要特殊处理
|
|
784
|
-
for (const r of rows) {
|
|
785
|
-
const key = this._rowKey(engine, coll, r);
|
|
786
|
-
if (key === undefined) continue;
|
|
787
|
-
const update = {};
|
|
788
|
-
if (updateDoc.$set) Object.assign(update, updateDoc.$set);
|
|
789
|
-
if (updateDoc.$inc) {
|
|
790
|
-
for (const [field, delta] of Object.entries(updateDoc.$inc)) {
|
|
791
|
-
update[field] = (r[field] || 0) + delta;
|
|
792
|
-
}
|
|
793
|
-
}
|
|
794
|
-
if (updateDoc.$push) {
|
|
795
|
-
for (const [field, val] of Object.entries(updateDoc.$push)) {
|
|
796
|
-
const arr = Array.isArray(r[field]) ? [...r[field]] : [];
|
|
797
|
-
arr.push(val);
|
|
798
|
-
update[field] = arr;
|
|
799
|
-
}
|
|
800
|
-
}
|
|
801
|
-
// $unset 设为 null(简化处理)
|
|
802
|
-
if (updateDoc.$unset) {
|
|
803
|
-
for (const field of Object.keys(updateDoc.$unset)) {
|
|
804
|
-
update[field] = null;
|
|
805
|
-
}
|
|
806
|
-
}
|
|
807
|
-
if (Object.keys(update).length > 0) entries.push([key, update]);
|
|
877
|
+
const hasModifier = Object.keys(updateDoc || {}).some(k => k.startsWith('$'));
|
|
878
|
+
for (const r of rows) {
|
|
879
|
+
const key = this._rowKey(engine, coll, r);
|
|
880
|
+
if (key === undefined) continue;
|
|
881
|
+
if (!hasModifier) {
|
|
882
|
+
entries.push([key, { ...updateDoc }]);
|
|
883
|
+
continue;
|
|
808
884
|
}
|
|
885
|
+
// 完整深拷贝后应用运算符,避免嵌套对象被原地污染;未知运算符显式报错
|
|
886
|
+
const doc = cloneDoc(r);
|
|
887
|
+
applyModifier(doc, updateDoc, { strict: true });
|
|
888
|
+
// updateByIds 是 Object.assign 合并:被 $unset 删除的顶层字段需显式置 undefined
|
|
889
|
+
for (const k of Object.keys(r)) if (!(k in doc)) doc[k] = undefined;
|
|
890
|
+
entries.push([key, doc]);
|
|
809
891
|
}
|
|
810
892
|
if (entries.length > 0) await engine.updateByIds(coll, entries);
|
|
811
893
|
}
|
|
@@ -832,6 +914,39 @@ class MongoServer {
|
|
|
832
914
|
&& this._match({ _val: el }, { _val: cond });
|
|
833
915
|
}
|
|
834
916
|
|
|
917
|
+
// 单个字段值的操作符求值;$not 递归取反。返回 false 表示不匹配。
|
|
918
|
+
_fieldMatch(rv, cond) {
|
|
919
|
+
for (const [op, v] of Object.entries(cond)) {
|
|
920
|
+
if (op === '$not') { if (this._fieldMatch(rv, v)) return false; continue; }
|
|
921
|
+
if (op === '$options') continue;
|
|
922
|
+
// 等值/$in/$regex 家族带 Mongo 数组语义(任一元素命中即匹配),
|
|
923
|
+
// $ne/$nin 是取反;范围操作符 null/缺失永不命中,数组只按元素比。
|
|
924
|
+
if (op === '$eq' && !orAnyElement(rv, el => valuesEqual(el, v))) return false;
|
|
925
|
+
if (op === '$ne' && orAnyElement(rv, el => valuesEqual(el, v))) return false;
|
|
926
|
+
if (op === '$gt' && !anyElementRange(rv, el => el > v)) return false;
|
|
927
|
+
if (op === '$gte' && !anyElementRange(rv, el => el >= v)) return false;
|
|
928
|
+
if (op === '$lt' && !anyElementRange(rv, el => el < v)) return false;
|
|
929
|
+
if (op === '$lte' && !anyElementRange(rv, el => el <= v)) return false;
|
|
930
|
+
if (op === '$in' && !(Array.isArray(v) && orAnyElement(rv, el => arrayIncludesValue(v, el)))) return false;
|
|
931
|
+
if (op === '$nin' && !(Array.isArray(v) && !orAnyElement(rv, el => arrayIncludesValue(v, el)))) return false;
|
|
932
|
+
if (op === '$exists' && (v ? (rv === undefined) : (rv !== undefined))) return false;
|
|
933
|
+
if (op === '$all' && !(Array.isArray(v) && v.every(t => orAnyElement(rv, el => valuesEqual(el, t))))) return false;
|
|
934
|
+
if (op === '$regex') {
|
|
935
|
+
const flags = String(cond.$options || '').includes('i') ? 'i' : '';
|
|
936
|
+
const re = new RegExp(String(v), flags);
|
|
937
|
+
if (!orAnyElement(rv, el => typeof el === 'string' && re.test(el))) return false;
|
|
938
|
+
}
|
|
939
|
+
if (op === '$type') {
|
|
940
|
+
if (v === 'objectId') { if (!(rv instanceof ObjectId)) return false; continue; }
|
|
941
|
+
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;
|
|
942
|
+
if (typeof rv !== t) return false;
|
|
943
|
+
}
|
|
944
|
+
if (op === '$size' && !(Array.isArray(rv) && rv.length === v)) return false;
|
|
945
|
+
if (op === '$elemMatch' && !(Array.isArray(rv) && rv.some((el) => this._elemMatches(el, v)))) return false;
|
|
946
|
+
}
|
|
947
|
+
return true;
|
|
948
|
+
}
|
|
949
|
+
|
|
835
950
|
_match(row, filter) {
|
|
836
951
|
for (const [k, cond] of Object.entries(filter || {})) {
|
|
837
952
|
if (k === '$or') {
|
|
@@ -850,36 +965,11 @@ class MongoServer {
|
|
|
850
965
|
if (this._match(row, cond)) return false;
|
|
851
966
|
continue;
|
|
852
967
|
}
|
|
968
|
+
const rv = getPath(row, k);
|
|
853
969
|
// ObjectId 是值不是操作符对象:typeof 'object' 但无枚举键,会 vacuous 匹配全表
|
|
854
970
|
if (cond && typeof cond === 'object' && !Array.isArray(cond) && !(cond instanceof ObjectId)) {
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
// 等值/$in/$regex 家族带 Mongo 数组语义(任一元素命中即匹配),
|
|
858
|
-
// $ne/$nin 是取反;范围操作符 null/缺失永不命中,数组只按元素比。
|
|
859
|
-
if (op === '$eq' && !orAnyElement(rv, el => valuesEqual(el, v))) return false;
|
|
860
|
-
if (op === '$ne' && orAnyElement(rv, el => valuesEqual(el, v))) return false;
|
|
861
|
-
if (op === '$gt' && !anyElementRange(rv, el => el > v)) return false;
|
|
862
|
-
if (op === '$gte' && !anyElementRange(rv, el => el >= v)) return false;
|
|
863
|
-
if (op === '$lt' && !anyElementRange(rv, el => el < v)) return false;
|
|
864
|
-
if (op === '$lte' && !anyElementRange(rv, el => el <= v)) return false;
|
|
865
|
-
if (op === '$in' && !(Array.isArray(v) && orAnyElement(rv, el => arrayIncludesValue(v, el)))) return false;
|
|
866
|
-
if (op === '$nin' && !(Array.isArray(v) && !orAnyElement(rv, el => arrayIncludesValue(v, el)))) return false;
|
|
867
|
-
if (op === '$exists' && (v ? (rv === undefined) : (rv !== undefined))) return false;
|
|
868
|
-
if (op === '$all' && !(Array.isArray(v) && v.every(t => orAnyElement(rv, el => valuesEqual(el, t))))) return false;
|
|
869
|
-
if (op === '$regex') {
|
|
870
|
-
const flags = String(cond.$options || '').includes('i') ? 'i' : '';
|
|
871
|
-
const re = new RegExp(String(v), flags);
|
|
872
|
-
if (!orAnyElement(rv, el => typeof el === 'string' && re.test(el))) return false;
|
|
873
|
-
}
|
|
874
|
-
if (op === '$type') {
|
|
875
|
-
if (v === 'objectId') { if (!(rv instanceof ObjectId)) return false; continue; }
|
|
876
|
-
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;
|
|
877
|
-
if (typeof rv !== t) return false;
|
|
878
|
-
}
|
|
879
|
-
if (op === '$size' && !(Array.isArray(rv) && rv.length === v)) return false;
|
|
880
|
-
if (op === '$elemMatch' && !(Array.isArray(rv) && rv.some((el) => this._elemMatches(el, v)))) return false;
|
|
881
|
-
}
|
|
882
|
-
} else if (!orAnyElement(row[k], (el) => valuesEqual(el, cond))) {
|
|
971
|
+
if (!this._fieldMatch(rv, cond)) return false;
|
|
972
|
+
} else if (!orAnyElement(rv, (el) => valuesEqual(el, cond))) {
|
|
883
973
|
return false;
|
|
884
974
|
}
|
|
885
975
|
}
|
package/lib/native_client.js
CHANGED
|
@@ -244,7 +244,18 @@ function parseShorthandSchema(str) {
|
|
|
244
244
|
def.type = next || def.type;
|
|
245
245
|
};
|
|
246
246
|
if (/\bprimary\s+key\b/i.test(def.type)) { def.primaryKey = true; strip(/\bprimary\s+key\b/gi); }
|
|
247
|
+
let explicitNoAuto = false;
|
|
248
|
+
if (/\b(auto_?increment\s*=\s*false|not\s+auto_?increment)\b/i.test(def.type)) {
|
|
249
|
+
explicitNoAuto = true;
|
|
250
|
+
strip(/\b(auto_?increment\s*=\s*false|not\s+auto_?increment)\b/gi);
|
|
251
|
+
}
|
|
247
252
|
if (/\bauto_?increment\b/i.test(def.type)) { def.autoIncrement = true; strip(/\bauto_?increment\b/gi); }
|
|
253
|
+
// MySQL 的整型 PRIMARY KEY 等价于 ROWID:内部行 id 与主键值一致。
|
|
254
|
+
// 默认推断为自增,让 findById 走 O(1) 的 jsqlFindById,而非全表扫描(#123)。
|
|
255
|
+
if (def.primaryKey && !explicitNoAuto && def.autoIncrement === undefined
|
|
256
|
+
&& /^(big)?int(eger)?$/i.test(def.type.trim())) {
|
|
257
|
+
def.autoIncrement = true;
|
|
258
|
+
}
|
|
248
259
|
if (/\bnot\s+null\b/i.test(def.type)) { def.required = true; strip(/\bnot\s+null\b/gi); }
|
|
249
260
|
if (/\bunique\b/i.test(def.type)) { def.unique = true; strip(/\bunique\b/gi); }
|
|
250
261
|
if (/\bdefault\s+(\S+)/i.test(def.type)) {
|
|
@@ -947,6 +958,21 @@ class JSQL {
|
|
|
947
958
|
return n;
|
|
948
959
|
}
|
|
949
960
|
|
|
961
|
+
/**
|
|
962
|
+
* #126:SUM/AVG/MIN/MAX 直接走 Rust 列式聚合,避免整表拉回 JS。
|
|
963
|
+
* 旧版二进制没有导出时返回 null,调用方可回退到 SQL 聚合路径。
|
|
964
|
+
*/
|
|
965
|
+
async aggregate(table, op, field) {
|
|
966
|
+
this._flushOpsNow();
|
|
967
|
+
const has = this._multiInstance && this._handle !== null
|
|
968
|
+
? typeof native.jsqlAggregateH === 'function'
|
|
969
|
+
: typeof native.jsqlAggregate === 'function';
|
|
970
|
+
if (!has) return null;
|
|
971
|
+
const r = safeParse(this._n('jsqlAggregate', table, String(op).toUpperCase(), String(field)));
|
|
972
|
+
if (r && r.error) throw new Error(r.error);
|
|
973
|
+
return r;
|
|
974
|
+
}
|
|
975
|
+
|
|
950
976
|
async updateByIds(table, entries) {
|
|
951
977
|
const schema = this._schemas[table];
|
|
952
978
|
const pairs = [];
|