jsql-neo 6.8.2 → 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 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.2** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
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
  ![Engines](https://img.shields.io/badge/engines-Native%20%7C%20WASM%20%7C%20Pure%20JS-7ee787)
9
9
  ![MySQL](https://img.shields.io/badge/protocol-MySQL%20compatible-1f6feb)
@@ -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 **this project's** documented semantics
222
- (lowercase type names, flat object depth 1), not MySQL's. See the SQL reference.
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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.8.2 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.8.3 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
package/lib/cache.js CHANGED
@@ -36,8 +36,26 @@ class Cache {
36
36
  return count;
37
37
  }
38
38
  keys(pattern = '*') {
39
- const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.');
40
- const regex = new RegExp('^' + escaped + '$');
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
- this._getExpires().set(k, Date.now() + seconds * 1000);
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
- const val = (cur !== undefined ? Number(cur) : 0) + delta;
79
- if (!Number.isFinite(val)) throw new Error('value is not an integer or out of range');
80
- this._getData().set(k, String(val));
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 = Math.min(stop, list.length - 1);
190
- // #89:stop 越界到负数也要钳到 0(与 Redis 一致)。
191
- // 此前 stop 只有上限钳制,负数越界后 start > stop → 错误返回 []。
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
  }
@@ -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[k]; const bv = b[k];
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 proj = stage.$project;
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, v] of Object.entries(proj)) {
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 field = String(stage.$unwind).replace(/^\$/, '');
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[field];
662
- if (!Array.isArray(arr) || arr.length === 0) { out.push({ ...r, [field]: null }); continue; }
663
- for (const item of arr) out.push({ ...r, [field]: item });
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[groupDef._id.slice(1)];
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[field]) || 0), 0);
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[field])
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[field]).filter(v => v != null);
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[field]).filter(v => v != null);
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][field] : null;
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][field] : null;
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][field] : null;
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 operators = ['$inc', '$unset', '$push', '$set'];
774
- const hasOperators = operators.some(op => updateDoc[op] !== undefined);
775
-
776
- if (!hasOperators) {
777
- // 没有操作符,直接 set
778
- for (const r of rows) {
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
- for (const [op, v] of Object.entries(cond)) {
856
- const rv = row[k];
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
  }
@@ -155,8 +155,15 @@ function match(doc, query) {
155
155
  return true;
156
156
  }
157
157
 
158
- function applyModifier(doc, update) {
159
- for (const [op, payload] of Object.entries(update)) {
158
+ function applyModifier(doc, update, opts = {}) {
159
+ const allowed = new Set(['$set', '$unset', '$inc', '$mul', '$min', '$max',
160
+ '$push', '$addToSet', '$pop', '$pull', '$rename', '$currentDate', '$bit']);
161
+ for (const [op, payload] of Object.entries(update || {})) {
162
+ if (!op.startsWith('$')) continue;
163
+ if (!allowed.has(op)) {
164
+ if (opts.strict) throw new Error(`unknown modifier: ${op}`);
165
+ continue;
166
+ }
160
167
  if (op === '$set') {
161
168
  for (const [k, v] of Object.entries(payload)) setPath(doc, k, v);
162
169
  } else if (op === '$unset') {
@@ -214,6 +221,25 @@ function applyModifier(doc, update) {
214
221
  // 对象元素按字段匹配。这里用 elementMatch 统一处理,真正把匹配元素移除。
215
222
  if (Array.isArray(arr)) setPath(doc, k, arr.filter(el => !elementMatch(el, v)));
216
223
  }
224
+ } else if (op === '$rename') {
225
+ for (const [from, to] of Object.entries(payload)) {
226
+ const v = getPath(doc, from);
227
+ if (v !== undefined) { setPath(doc, to, v); unsetPath(doc, from); }
228
+ }
229
+ } else if (op === '$currentDate') {
230
+ const now = new Date().toISOString();
231
+ for (const [k, v] of Object.entries(payload)) {
232
+ if (v === true || (v && typeof v === 'object') || v === '$type') setPath(doc, k, now);
233
+ }
234
+ } else if (op === '$bit') {
235
+ for (const [k, bits] of Object.entries(payload)) {
236
+ const cur = Number(getPath(doc, k)) || 0;
237
+ let v = cur;
238
+ if (bits && bits.and !== undefined) v = v & Number(bits.and);
239
+ if (bits && bits.or !== undefined) v = v | Number(bits.or);
240
+ if (bits && bits.xor !== undefined) v = v ^ Number(bits.xor);
241
+ setPath(doc, k, v);
242
+ }
217
243
  }
218
244
  }
219
245
  return doc;
@@ -525,4 +551,4 @@ function rowId(row, all) {
525
551
  return idx === -1 ? undefined : idx + 1;
526
552
  }
527
553
 
528
- module.exports = { Datastore, Cursor };
554
+ module.exports = { Datastore, Cursor, getPath, setPath, unsetPath, applyModifier };
package/lib/sql.js CHANGED
@@ -210,6 +210,29 @@ function jsonPathGet(data, path, notFound) {
210
210
  return current === undefined ? miss : current;
211
211
  }
212
212
 
213
+ /**
214
+ * 解析 JSONPath,返回 { parent, key } 供 JSON_ARRAY_APPEND / JSON_ARRAY_INSERT 就地修改。
215
+ * 支持 $.a.b 与 $.a[1](末尾带下标时 parent 就是数组、key 是数值下标)。
216
+ */
217
+ function jsonPathParent(data, path) {
218
+ const p = String(path == null ? '' : path).replace(/^\$\.?/, '');
219
+ if (!p) return null;
220
+ const arr = p.match(/^(.*)\[(\d+)\]$/);
221
+ if (arr) {
222
+ const base = arr[1].replace(/\.$/, '');
223
+ const owner = base ? jsonPathGet(data, '$.' + base) : data;
224
+ return (owner && typeof owner === 'object') ? { parent: owner, key: parseInt(arr[2], 10) } : null;
225
+ }
226
+ const segs = p.split('.');
227
+ const key = segs.pop();
228
+ let parent = data;
229
+ for (const s of segs) {
230
+ if (parent == null || typeof parent !== 'object') return null;
231
+ parent = parent[s];
232
+ }
233
+ return (parent && typeof parent === 'object') ? { parent, key } : null;
234
+ }
235
+
213
236
  /**
214
237
  * 16 进制整数字面量(0x?? / X'??')的精确解析(Issue #38)。
215
238
  *
@@ -503,7 +526,8 @@ function tokenize(sql) {
503
526
  // 聚合函数集合:这些必须走 aggregate 节点,否则会被当成逐行标量函数(返回 null 且不折叠行)
504
527
  const AGG_FUNCS = new Set(['SUM', 'AVG', 'MIN', 'MAX', 'COUNT',
505
528
  'GROUP_CONCAT', 'STDDEV', 'STD', 'STDDEV_POP', 'STDDEV_SAMP',
506
- 'VARIANCE', 'VAR_POP', 'VAR_SAMP', 'FIRST', 'LAST']);
529
+ 'VARIANCE', 'VAR_POP', 'VAR_SAMP', 'FIRST', 'LAST',
530
+ 'BIT_AND', 'BIT_OR', 'BIT_XOR']);
507
531
 
508
532
  // 方差/标准差族(Issue #114):MySQL 里无后缀的 VARIANCE / STDDEV / STD
509
533
  // 都是**总体**口径(= VAR_POP / STDDEV_POP),不是样本。
@@ -1318,10 +1342,12 @@ class Parser {
1318
1342
  const ops = ['+', '-', '*', '/', '%', '<<', '>>', '&', '|', '^'];
1319
1343
  for (;;) {
1320
1344
  const opTok = this.peek();
1321
- if (opTok.type !== 'op' || !ops.includes(opTok.value)) break;
1345
+ // MySQL 允许中缀 MOD(SELECT 5 MOD 2),与 % 同一优先级/语义
1346
+ const isModWord = this.isWord('MOD');
1347
+ if (!isModWord && (opTok.type !== 'op' || !ops.includes(opTok.value))) break;
1322
1348
  this.next();
1323
1349
  const right = this.parseValueAtom();
1324
- left = { type: 'binary', op: opTok.value, left, right };
1350
+ left = { type: 'binary', op: isModWord ? '%' : opTok.value, left, right };
1325
1351
  }
1326
1352
  return left;
1327
1353
  }
@@ -3072,6 +3098,13 @@ class Parser {
3072
3098
  node = { type: 'arith', op: 'DIV', left: node, right };
3073
3099
  continue;
3074
3100
  }
3101
+ // MySQL 中缀取模:5 MOD 2(与 % 同优先级,复用 % 的求值路径)
3102
+ if (this.isWord('MOD')) {
3103
+ this.next();
3104
+ const right = this.parsePostfix(this.parseOperand());
3105
+ node = { type: 'arith', op: '%', left: node, right };
3106
+ continue;
3107
+ }
3075
3108
  break;
3076
3109
  }
3077
3110
  return node;
@@ -4035,7 +4068,7 @@ function strftime(d, fmt) {
4035
4068
  '%M': MONTH_NAMES[d.getUTCMonth()], '%b': MONTH_NAMES[d.getUTCMonth()].slice(0, 3),
4036
4069
  '%W': DAY_NAMES[d.getUTCDay()], '%a': DAY_NAMES[d.getUTCDay()].slice(0, 3),
4037
4070
  '%w': String(d.getUTCDay()),
4038
- '%j': String(Math.round((d - Date.UTC(d.getUTCFullYear(), 0, 0)) / 86400000)),
4071
+ '%j': String(Math.round((d - Date.UTC(d.getUTCFullYear(), 0, 0)) / 86400000)).padStart(3, '0'),
4039
4072
  '%%': '%',
4040
4073
  };
4041
4074
  return String(fmt).replace(/%[A-Za-z%]/g, (m) => (m in map ? map[m] : m));
@@ -4401,8 +4434,16 @@ function applyScalarFunction(fnNode, row, ctx) {
4401
4434
  const base = parseSqlDate(args[0]);
4402
4435
  if (!base) return null;
4403
4436
  const iv = args[1];
4404
- if (!iv || !iv.__interval) return fmtSqlDate(String(args[0]).length <= 10, base);
4405
4437
  const isDateOnly = String(args[0]).trim().length <= 10;
4438
+ // MySQL 两参数形式:ADDDATE(date, N) = DATE_ADD(date, INTERVAL N DAY)
4439
+ if (iv && !iv.__interval && typeof iv !== 'object') {
4440
+ const days = Number(iv);
4441
+ if (!Number.isFinite(days)) return null;
4442
+ const d = new Date(base.getTime());
4443
+ d.setUTCDate(d.getUTCDate() + sign * Math.trunc(days));
4444
+ return fmtSqlDate(isDateOnly, d);
4445
+ }
4446
+ if (!iv || !iv.__interval) return fmtSqlDate(isDateOnly, base);
4406
4447
  const d = new Date(base.getTime());
4407
4448
  const n = sign * Number(iv.value || 0);
4408
4449
  switch (String(iv.unit || '').toUpperCase()) {
@@ -4718,6 +4759,40 @@ function applyScalarFunction(fnNode, row, ctx) {
4718
4759
  if (p < 1 || p > str.length + 1 || l < 0) return str;
4719
4760
  return str.slice(0, p - 1) + String(ins) + str.slice(p - 1 + l);
4720
4761
  }
4762
+ case 'STRCMP': {
4763
+ if (args[0] == null || args[1] == null) return null;
4764
+ const a = String(args[0]), b = String(args[1]);
4765
+ return a < b ? -1 : (a > b ? 1 : 0);
4766
+ }
4767
+ case 'JSON_ARRAY_APPEND': {
4768
+ // JSON_ARRAY_APPEND(json, path, val, ...):把值追加到 path 指向的数组
4769
+ if (args[0] == null) return null;
4770
+ let data = args[0];
4771
+ if (typeof data === 'string') { try { data = JSON.parse(data); } catch (e) { return null; } }
4772
+ data = JSON.parse(JSON.stringify(data));
4773
+ for (let i = 1; i + 1 < args.length; i += 2) {
4774
+ const loc = jsonPathParent(data, args[i]);
4775
+ if (!loc) continue;
4776
+ const cur = loc.parent[loc.key];
4777
+ const arr = Array.isArray(cur) ? cur : [];
4778
+ arr.push(args[i + 1]);
4779
+ loc.parent[loc.key] = arr;
4780
+ }
4781
+ return data;
4782
+ }
4783
+ case 'JSON_ARRAY_INSERT': {
4784
+ // JSON_ARRAY_INSERT(json, path, val, ...):在 path 的数值下标处插入
4785
+ if (args[0] == null) return null;
4786
+ let data = args[0];
4787
+ if (typeof data === 'string') { try { data = JSON.parse(data); } catch (e) { return null; } }
4788
+ data = JSON.parse(JSON.stringify(data));
4789
+ for (let i = 1; i + 1 < args.length; i += 2) {
4790
+ const loc = jsonPathParent(data, args[i]);
4791
+ if (!loc || !Number.isInteger(loc.key) || !Array.isArray(loc.parent)) continue;
4792
+ loc.parent.splice(Math.max(0, loc.key), 0, args[i + 1]);
4793
+ }
4794
+ return data;
4795
+ }
4721
4796
  case 'INET_ATON': {
4722
4797
  if (args[0] == null) return null;
4723
4798
  const m = String(args[0]).match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
@@ -4728,7 +4803,9 @@ function applyScalarFunction(fnNode, row, ctx) {
4728
4803
  }
4729
4804
  case 'INET_NTOA': {
4730
4805
  if (args[0] == null) return null;
4731
- const n = Number(args[0]) >>> 0;
4806
+ const n = Number(args[0]);
4807
+ // MySQL:越界(负数 / > 2^32-1 / 非整数)返回 NULL,`>>> 0` 的静默截断会伪造合法 IP
4808
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0 || n > 4294967295) return null;
4732
4809
  return [(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255].join('.');
4733
4810
  }
4734
4811
  case 'FORMAT': {
@@ -6734,8 +6811,8 @@ class SQLExecutor {
6734
6811
  } else if (typeof this.engine._ensureTable === 'function') {
6735
6812
  const tbl = this.engine._ensureTable(tName) || (this.engine._tables && this.engine._tables[tName]);
6736
6813
  if (tbl && typeof tbl.createIndex === 'function') {
6737
- // Table.createIndex 目前是单字段接口,复合索引按逐列建
6738
- for (const col of statement.columns) tbl.createIndex(col);
6814
+ // 把 UNIQUE 与复合列一起传给 Table,使其注册唯一约束(不只是加速索引)
6815
+ tbl.createIndex(statement.columns.slice(), { unique: !!statement.unique, name: statement.name });
6739
6816
  handled = true;
6740
6817
  }
6741
6818
  }
@@ -7857,6 +7934,21 @@ class SQLExecutor {
7857
7934
  }
7858
7935
  return best;
7859
7936
  }
7937
+ if (fn === 'BIT_AND' || fn === 'BIT_OR' || fn === 'BIT_XOR') {
7938
+ // MySQL:64 位无符号按位聚合;空集 BIT_AND 为全 1,BIT_OR/BIT_XOR 为 0
7939
+ let acc = fn === 'BIT_AND' ? (1n << 64n) - 1n : 0n;
7940
+ for (const v of values) {
7941
+ let n;
7942
+ if (typeof v === 'bigint') n = v;
7943
+ else if (typeof v === 'number' && Number.isFinite(v)) n = BigInt(Math.trunc(v));
7944
+ else if (typeof v === 'string' && /^[-+]?\d+$/.test(v.trim())) n = BigInt(v.trim());
7945
+ else continue;
7946
+ if (fn === 'BIT_AND') acc &= n;
7947
+ else if (fn === 'BIT_OR') acc |= n;
7948
+ else acc ^= n;
7949
+ }
7950
+ return (acc >= SAFE_MIN && acc <= SAFE_MAX) ? Number(acc) : acc;
7951
+ }
7860
7952
  if (fn === 'FIRST') return values.length ? values[0] : null;
7861
7953
  if (fn === 'LAST') return values.length ? values[values.length - 1] : null;
7862
7954
  if (fn === 'GROUP_CONCAT') {
@@ -290,8 +290,19 @@ class Statement {
290
290
  return { changes: r && typeof r.changes === 'number' ? parseInt(r.changes, 10) : 0, lastInsertRowid: r && (r.lastInsertRowid !== undefined && r.lastInsertRowid !== null) ? r.lastInsertRowid : 0, _stmt: this };
291
291
  }
292
292
 
293
+ // better-sqlite3 的 raw()/pluck() 对 get/all/iterate 一致生效
294
+ _shapeOne(row) {
295
+ if (row == null) return row;
296
+ if (this._rawMode && typeof row === 'object' && !Array.isArray(row)) row = Object.values(row);
297
+ if (this._pluck) {
298
+ if (Array.isArray(row)) return row[0];
299
+ if (typeof row === 'object') { const k = Object.keys(row)[0]; return k === undefined ? undefined : row[k]; }
300
+ }
301
+ return row;
302
+ }
303
+
293
304
  get(...params) {
294
- return this._call('get', params.length > 0 ? params : undefined);
305
+ return this._shapeOne(this._call('get', params.length > 0 ? params : undefined));
295
306
  }
296
307
 
297
308
  all(...params) {
package/lib/table.js CHANGED
@@ -208,6 +208,7 @@ class Table {
208
208
  this.__rows = [];
209
209
  this._indexes = {}; // 旧版 hash 索引(兼容)
210
210
  this._btrees = {}; // B-Tree 索引 { fieldName: BTree }
211
+ this._uniqueIndexes = []; // CREATE UNIQUE INDEX 注册的(复合)唯一索引
211
212
  this._autoIncrement = 0;
212
213
  this._dirty = false;
213
214
  this._hooks = {
@@ -537,6 +538,7 @@ class Table {
537
538
  if (row[field] !== undefined && row[field] !== null) uniqueTracker[field].add(row[field]);
538
539
  }
539
540
  }
541
+ const compositeUniqueSets = this._compositeUniqueSets();
540
542
  const autoIncField = this._autoIncrementField;
541
543
  const defaults = this._defaults;
542
544
  const computedFields = this._computedFields;
@@ -594,6 +596,7 @@ class Table {
594
596
  }
595
597
  // CHECK 约束统一在列循环外整体校验(支持跨列/表级约束)
596
598
  this._enforceChecks(data);
599
+ this._checkCompositeUnique(data, -1, compositeUniqueSets);
597
600
  // 主键唯一性检查(主键可能不在 _cachedUniqueFields 中)
598
601
  if (this._primaryKey && data[this._primaryKey] !== undefined && data[this._primaryKey] !== null) {
599
602
  const pkVal = data[this._primaryKey];
@@ -1209,7 +1212,24 @@ class Table {
1209
1212
  // 索引
1210
1213
  // ============================================================
1211
1214
 
1212
- createIndex(field) {
1215
+ createIndex(field, opts) {
1216
+ // CREATE [UNIQUE] INDEX:支持复合列与唯一约束注册
1217
+ if (Array.isArray(field) || (opts && (opts.unique || opts.name))) {
1218
+ const columns = Array.isArray(field) ? field.slice() : [field];
1219
+ if (opts && opts.unique) {
1220
+ const key = columns.join('\u001f');
1221
+ if (!this._uniqueIndexes.some(u => u.key === key)) {
1222
+ this._uniqueIndexes.push({ name: opts.name, columns, key });
1223
+ }
1224
+ // 单列唯一索引复用 schema.unique 的成熟校验路径(insert/update 全覆盖)
1225
+ if (columns.length === 1 && this._schema[columns[0]]) {
1226
+ this._schema[columns[0]].unique = true;
1227
+ if (!this._cachedUniqueFields.includes(columns[0])) this._cachedUniqueFields.push(columns[0]);
1228
+ }
1229
+ }
1230
+ for (const col of columns) if (!this._indexes[col]) this.createIndex(col);
1231
+ return this._uniqueIndexes;
1232
+ }
1213
1233
  this._indexes[field] = new Map();
1214
1234
  for (let i = 0; i < this._rows.length; i++) {
1215
1235
  const value = this._rows[i][field];
@@ -1223,6 +1243,41 @@ class Table {
1223
1243
  return this._indexes[field];
1224
1244
  }
1225
1245
 
1246
+ // 复合唯一索引校验:NULL 不参与唯一性;excludeIndex 供 UPDATE 跳过自身
1247
+ _checkCompositeUnique(data, excludeIndex, existingSets) {
1248
+ const uniques = this._uniqueIndexes || [];
1249
+ for (let j = 0; j < uniques.length; j++) {
1250
+ const u = uniques[j];
1251
+ if (u.columns.length < 2) continue;
1252
+ if (u.columns.some(c => data[c] === undefined || data[c] === null)) continue;
1253
+ const k = u.columns.map(c => String(data[c])).join('\u001f');
1254
+ if (existingSets) {
1255
+ if (existingSets[j].has(k)) throw createError('ER_DUP_ENTRY', k, u.columns.join(','));
1256
+ existingSets[j].add(k);
1257
+ } else {
1258
+ for (let i = 0; i < this._rows.length; i++) {
1259
+ if (i === excludeIndex) continue;
1260
+ const row = this._rows[i];
1261
+ if (u.columns.some(c => row[c] === undefined || row[c] === null)) continue;
1262
+ if (u.columns.map(c => String(row[c])).join('\u001f') === k) {
1263
+ throw createError('ER_DUP_ENTRY', k, u.columns.join(','));
1264
+ }
1265
+ }
1266
+ }
1267
+ }
1268
+ }
1269
+
1270
+ _compositeUniqueSets() {
1271
+ return (this._uniqueIndexes || []).map(u => {
1272
+ const set = new Set();
1273
+ for (const row of this._rows) {
1274
+ if (u.columns.some(c => row[c] === undefined || row[c] === null)) continue;
1275
+ set.add(u.columns.map(c => String(row[c])).join('\u001f'));
1276
+ }
1277
+ return set;
1278
+ });
1279
+ }
1280
+
1226
1281
  dropIndex(field) {
1227
1282
  delete this._indexes[field];
1228
1283
  delete this._btrees[field];
@@ -1889,6 +1944,8 @@ class Table {
1889
1944
  }
1890
1945
  }
1891
1946
 
1947
+ // 复合唯一索引校验(NULL 不参与唯一性)
1948
+ this._checkCompositeUnique(data, excludeIndex);
1892
1949
  // FOREIGN KEY 校验
1893
1950
  // skipForeignKeys:父表主键 CASCADE 传播时,子表的新值尚未在父表生效,
1894
1951
  // 此时跳过本表 FK 复查(否则合法的 CASCADE 会被自己拦住)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.8.2",
3
+ "version": "6.8.3",
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/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",
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/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",
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/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",
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/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",
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,140 @@
1
+ /* 回归测试:issue #138-#156 */
2
+ const path = require('path');
3
+ const ROOT = path.join(__dirname, '..');
4
+ const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
5
+ const Cache = require(path.join(ROOT, 'lib', 'cache.js'));
6
+ const SqliteDb = require(path.join(ROOT, 'lib', 'sqlite_compat.js'));
7
+ const { createMongoServer } = require(path.join(ROOT, 'lib', 'mongo_server.js'));
8
+
9
+ let pass = 0, fail = 0;
10
+ function ok(name, cond, got) {
11
+ if (cond) { pass++; console.log('[OK] ' + name); }
12
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
13
+ }
14
+
15
+ async function main() {
16
+ const stub = { hasTable: () => true, truncate: async () => {}, flush: async () => {}, find: async () => [], getTableSchema: async () => ({}) };
17
+ const q = async (sql) => (await executeSQL(stub, sql, { safety: false })).rows[0][0];
18
+
19
+ // ---------- SQL ----------
20
+ ok('#140 %j 补零', await q("SELECT DATE_FORMAT('2024-03-05','%j')") === '065');
21
+ ok('#140 %j 闰年', await q("SELECT DATE_FORMAT('2024-12-31','%j')") === '366');
22
+ ok('#139 JSON_TYPE 大写', await q("SELECT JSON_TYPE('{\"a\":1}')") === 'OBJECT');
23
+ ok('#139 JSON_DEPTH 扁平为 2', await q("SELECT JSON_DEPTH('{\"a\":1}')") === 2);
24
+ ok('#148 INET_NTOA 负数 NULL', await q('SELECT INET_NTOA(-1)') === null);
25
+ ok('#148 INET_NTOA 越界 NULL', await q('SELECT INET_NTOA(4294967296)') === null);
26
+ ok('#148 INET_NTOA 合法', await q('SELECT INET_NTOA(2130706433)') === '127.0.0.1');
27
+ ok('#149 ADDDATE(date,N)', await q("SELECT ADDDATE('2024-01-15',10)") === '2024-01-25');
28
+ ok('#149 SUBDATE(date,N)', await q("SELECT SUBDATE('2024-01-15',10)") === '2024-01-05');
29
+ ok('#141 STRCMP', await q("SELECT STRCMP('a','b')") === -1 && await q("SELECT STRCMP('a','a')") === 0);
30
+ ok('#141 JSON_ARRAY_APPEND', JSON.stringify(await q("SELECT JSON_ARRAY_APPEND('{\"a\":[1]}','$.a',2)")) === '{"a":[1,2]}');
31
+ ok('#141 JSON_ARRAY_INSERT', JSON.stringify(await q("SELECT JSON_ARRAY_INSERT('{\"a\":[1,3]}','$.a[1]',2)")) === '{"a":[1,2,3]}');
32
+ ok('#142 中缀 MOD', await q('SELECT 5 MOD 2') === 1 && await q('SELECT 5 MOD 2 * 3') === 3);
33
+
34
+ const db = new Database(':memory:');
35
+ await executeSQL(db, 'CREATE TABLE t (id INT PRIMARY KEY, v TEXT, a INT, b INT)', { safety: false });
36
+ await executeSQL(db, 'CREATE UNIQUE INDEX uv ON t(v)', { safety: false });
37
+ await executeSQL(db, "INSERT INTO t (id,v) VALUES (1,'a')", { safety: false });
38
+ let dup = null;
39
+ try { await executeSQL(db, "INSERT INTO t (id,v) VALUES (2,'a')", { safety: false }); } catch (e) { dup = e; }
40
+ ok('#138 唯一索引插入重复报错', !!dup && /DUP_ENTRY/.test(dup.message));
41
+ await executeSQL(db, "INSERT INTO t (id,v) VALUES (2,'b')", { safety: false });
42
+ let updErr = null;
43
+ try { await executeSQL(db, "UPDATE t SET v='b' WHERE id=1", { safety: false }); } catch (e) { updErr = e; }
44
+ ok('#138 唯一索引更新到重复报错', !!updErr && /Duplicate entry/.test(updErr.message), updErr && updErr.message);
45
+ await executeSQL(db, 'CREATE UNIQUE INDEX uab ON t(a,b)', { safety: false });
46
+ await executeSQL(db, 'INSERT INTO t (id,a,b) VALUES (3,1,1)', { safety: false });
47
+ let cdup = null;
48
+ try { await executeSQL(db, 'INSERT INTO t (id,a,b) VALUES (4,1,1)', { safety: false }); } catch (e) { cdup = e; }
49
+ ok('#138 复合唯一索引重复报错', !!cdup);
50
+ const db2 = new Database(':memory:');
51
+ await executeSQL(db2, 'CREATE TABLE n (x INT)', { safety: false });
52
+ await executeSQL(db2, 'INSERT INTO n VALUES (7),(3)', { safety: false });
53
+ const bits = (await executeSQL(db2, 'SELECT BIT_AND(x) a, BIT_OR(x) o, BIT_XOR(x) x FROM n', { safety: false })).rows[0];
54
+ ok('#141 BIT_AND/OR/XOR', bits[0] === 3 && bits[1] === 7 && bits[2] === 4, bits);
55
+
56
+ // ---------- Redis ----------
57
+ const c = new Cache();
58
+ let err = null;
59
+ try { c.incrby('x', 1.5); } catch (e) { err = e; }
60
+ ok('#143 INCRBY 小数报错', !!err && /not an integer/.test(err.message));
61
+ c.set('z', '3.5');
62
+ err = null;
63
+ try { c.incr('z'); } catch (e) { err = e; }
64
+ ok('#143 INCR 小数值报错', !!err);
65
+ c.set('big', '9223372036854775807');
66
+ err = null;
67
+ try { c.incrby('big', 1); } catch (e) { err = e; }
68
+ ok('#143 溢出报错', !!err && /overflow/.test(err.message));
69
+ ok('#143 正常整数递增', c.incr('n') === 1 && c.incrby('n', 5) === 6 && c.decrby('n', 2) === 4);
70
+ c.set('e', 'v');
71
+ err = null;
72
+ try { c.expire('e', 1.5); } catch (e) { err = e; }
73
+ ok('#144 EXPIRE 小数报错', !!err);
74
+ const l = new Cache();
75
+ l.rpush('l', 'a', 'b', 'c');
76
+ ok('#145 LRANGE 双越界负索引', JSON.stringify(l.lrange('l', -100, -50)) === '[]');
77
+ ok('#145 LRANGE 正常负索引', JSON.stringify(l.lrange('l', 0, -1)) === '["a","b","c"]');
78
+ const k = new Cache();
79
+ ['a1', 'aX1', 'a[1]', 'a3', 'ab'].forEach(x => k.set(x, 'v'));
80
+ ok('#146 KEYS [abc]', JSON.stringify(k.keys('a[13]').sort()) === '["a1","a3"]');
81
+ ok('#146 KEYS [!abc]', JSON.stringify(k.keys('a[!1]').sort()) === '["a3","ab"]');
82
+ c.close();
83
+ l.close();
84
+ k.close();
85
+
86
+ // ---------- SQLite ----------
87
+ const sq = new SqliteDb(':memory:', { engine: 'native' });
88
+ sq.exec('CREATE TABLE t (a INTEGER, b TEXT)');
89
+ sq.exec("INSERT INTO t VALUES (1,'x')");
90
+ ok('#147 pluck get', sq.prepare('SELECT a,b FROM t').pluck(true).get() === 1);
91
+ ok('#147 raw get', JSON.stringify(sq.prepare('SELECT a,b FROM t').raw(true).get()) === '[1,"x"]');
92
+ sq.close();
93
+
94
+ // ---------- MongoDB ----------
95
+ const srv = createMongoServer({ port: 0, noAuth: true, dataDir: ':memory:' });
96
+ const d = (cmd, payload) => srv._dispatch(cmd, { ...payload, $db: 'test' });
97
+ const engine = await srv._getEngine('test');
98
+ await engine.createTable('u', {});
99
+ await engine.createTable('o', {});
100
+ await d('insert', { insert: 'u', documents: [
101
+ { _id: 1, name: 'a', age: 20, tags: ['x', 'y'], addr: { city: 'NY' } },
102
+ { _id: 2, name: 'b', age: 30, tags: ['y'], addr: { city: 'LA' } },
103
+ { _id: 3, name: 'c', age: 20, tags: [], addr: { city: 'NY' } },
104
+ ] });
105
+ await d('insert', { insert: 'o', documents: [{ _id: 101, uid: 1 }, { _id: 102, uid: 1 }, { _id: 103, uid: 2 }] });
106
+ const find = async (filter, extra = {}) => (await d('find', { find: 'u', filter, ...extra })).cursor.firstBatch;
107
+ const agg = async (pipeline) => (await d('aggregate', { aggregate: 'u', pipeline })).cursor.firstBatch;
108
+ const ids = (rows) => rows.map(r => r._id).sort();
109
+
110
+ ok('#151 点路径 filter', JSON.stringify(ids(await find({ 'addr.city': 'NY' }))) === '[1,3]');
111
+ ok('#151 点路径 sort', JSON.stringify((await agg([{ $sort: { 'addr.city': 1 } }])).map(r => r._id)) === '[2,1,3]');
112
+ ok('#151 点路径 group', JSON.stringify(await agg([{ $group: { _id: '$addr.city', n: { $sum: 1 } } }])) === '[{"_id":"NY","n":2},{"_id":"LA","n":1}]');
113
+ ok('#151 $set 点路径', await d('update', { update: 'u', updates: [{ q: { _id: 1 }, u: { $set: { 'addr.city': 'LA' } } }] }).then(() => find({ _id: 1 })).then(r => r[0].addr.city) === 'LA');
114
+ ok('#151 $unset 点路径', await d('update', { update: 'u', updates: [{ q: { _id: 1 }, u: { $unset: { 'addr.city': '' } } }] }).then(() => find({ _id: 1 })).then(r => JSON.stringify(r[0].addr)) === '{}');
115
+ ok('#155 $not $gt', JSON.stringify(ids(await find({ age: { $not: { $gt: 20 } } }))) === '[1,3]');
116
+ ok('#155 $not $eq', JSON.stringify(ids(await find({ age: { $not: { $eq: 20 } } }))) === '[2]');
117
+ ok('#152 projection include', JSON.stringify(await find({ _id: 1 }, { projection: { _id: 0, name: 1 } })) === '[{"name":"a"}]');
118
+ ok('#152 projection exclude', !(await find({ _id: 1 }, { fields: { addr: 0 } }))[0].addr);
119
+ ok('#156 $project 排除式', !(await agg([{ $project: { addr: 0 } }]))[0].addr);
120
+ const expr = (await agg([{ $project: { name: 1, upper: { $toUpper: '$name' }, plus: { $add: ['$age', 1] } } }]))[0];
121
+ ok('#156 $project 表达式', expr.upper === 'A' && expr.plus === 21, expr);
122
+ ok('#154 $unwind 默认丢弃空数组', JSON.stringify(ids(await agg([{ $unwind: '$tags' }]))) === '[1,1,2]');
123
+ ok('#154 $unwind preserve=true', JSON.stringify(ids(await agg([{ $unwind: { path: '$tags', preserveNullAndEmptyArrays: true } }]))) === '[1,1,2,3]');
124
+ const lookup = (await agg([{ $match: { _id: 1 } }, { $lookup: { from: 'o', localField: '_id', foreignField: 'uid', as: 'orders' } }]))[0];
125
+ ok('#153 $lookup', Array.isArray(lookup.orders) && lookup.orders.length === 2, lookup);
126
+ await d('update', { update: 'u', updates: [{ q: { _id: 1 }, u: { $mul: { age: 2 } } }] });
127
+ ok('#150 $mul', (await find({ _id: 1 }))[0].age === 40);
128
+ await d('update', { update: 'u', updates: [{ q: { _id: 1 }, u: { $addToSet: { tags: 'q' } } }] });
129
+ ok('#150 $addToSet', JSON.stringify((await find({ _id: 1 }))[0].tags) === '["x","y","q"]');
130
+ await d('update', { update: 'u', updates: [{ q: { _id: 1 }, u: { $pull: { tags: 'y' } } }] });
131
+ ok('#150 $pull', JSON.stringify((await find({ _id: 1 }))[0].tags) === '["x","q"]');
132
+ const unknown = await d('update', { update: 'u', updates: [{ q: { _id: 1 }, u: { $bogus: { x: 1 } } }] });
133
+ ok('#150 未知运算符报错', unknown.ok === 0 && /unknown modifier/.test(unknown.errmsg), unknown);
134
+ srv.close();
135
+
136
+ console.log(`\n${pass} passed, ${fail} failed`);
137
+ process.exitCode = fail ? 1 : 0;
138
+ }
139
+
140
+ main().catch(e => { console.error(e); process.exitCode = 1; });
@@ -45,12 +45,12 @@ function ok(name, cond, extra) {
45
45
  ok('#88 $regex ^al 只返回 alice', r.length === 1, r.length);
46
46
  }
47
47
 
48
- // #89 lrange 负索引越界
48
+ // #89 / #145 lrange 负索引越界:Redis 在 start > end 时返回空数组
49
49
  {
50
50
  const c = new Cache();
51
51
  c.rpush('k', 'a', 'b', 'c');
52
52
  const out = c.lrange('k', 0, -5);
53
- ok('#89 lrange(0,-5) → ["a"]', out.join(',') === 'a', out);
53
+ ok('#145 lrange(0,-5) → []', out.length === 0, out);
54
54
  }
55
55
 
56
56
  // #90 updater 版本比较