jsql-neo 6.7.7 → 6.8.1

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.7.7** — 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.1** — 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)
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.7.7 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.8.1 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
@@ -15,7 +15,7 @@ const fs = require('fs');
15
15
  const path = require('path');
16
16
  const zlib = require('zlib');
17
17
  const Database = require('./database');
18
- const { ObjectId, valuesEqual, arrayIncludesValue, mapKey } = require('./objectid');
18
+ const { ObjectId, valuesEqual, arrayIncludesValue, mapKey, orAnyElement, anyElementRange } = require('./objectid');
19
19
 
20
20
  const OP_MSG = 2013;
21
21
  const OP_COMPRESSED = 2012;
@@ -148,6 +148,30 @@ function bsonReadValue(buf, pos, type, end) {
148
148
  }
149
149
  }
150
150
 
151
+ /* ------------------------------------------------------------------ */
152
+ /* 排序(find 与 aggregate $sort 共用) */
153
+ /* ------------------------------------------------------------------ */
154
+
155
+ function sortRows(rows, sortSpec) {
156
+ const sortKeys = Object.entries(sortSpec);
157
+ return [...rows].sort((a, b) => {
158
+ for (const [k, dir] of sortKeys) {
159
+ const av = a[k]; const bv = b[k];
160
+ // valuesEqual:同字节 ObjectId 不 ===,缺这一道相等短路时
161
+ // 相等键会破坏排序稳定性(sort+skip/limit 分页会丢/重文档)
162
+ if (av === bv || valuesEqual(av, bv)) continue;
163
+ const desc = Number(dir) < 0;
164
+ // Issue #47:NULL 的位置随排序方向走(升序在前、降序在后),
165
+ // 与 MongoDB 一致;此前固定返回 1/-1,升序时 null 恒排最后。
166
+ if (av == null) return desc ? 1 : -1;
167
+ if (bv == null) return desc ? -1 : 1;
168
+ const cmp = av < bv ? -1 : 1;
169
+ return desc ? -cmp : cmp;
170
+ }
171
+ return 0;
172
+ });
173
+ }
174
+
151
175
  /* ------------------------------------------------------------------ */
152
176
  /* Server */
153
177
  /* ------------------------------------------------------------------ */
@@ -484,7 +508,10 @@ class MongoServer {
484
508
  const coll = String(doc.findAndModify);
485
509
  const engine = await this._ensureCollection(coll, this._dbOf(doc));
486
510
  const q = doc.query || {};
487
- const rows = await this._matching(engine, coll, q);
511
+ let rows = await this._matching(engine, coll, q);
512
+ if (doc.sort && typeof doc.sort === 'object' && !Array.isArray(doc.sort)) {
513
+ rows = sortRows(rows, doc.sort);
514
+ }
488
515
  const found = rows[0] || null;
489
516
  const set = doc.update && doc.update.$set ? doc.update.$set : (doc.update || {});
490
517
  let value = null;
@@ -535,6 +562,10 @@ class MongoServer {
535
562
  const coll = String(doc.find);
536
563
  const engine = await this._ensureCollection(coll, this._dbOf(doc));
537
564
  let rows = await this._matching(engine, coll, doc.filter);
565
+ // sort 必须先于 skip/limit:否则分页取到的是存储顺序的页
566
+ if (doc.sort && typeof doc.sort === 'object' && !Array.isArray(doc.sort)) {
567
+ rows = sortRows(rows, doc.sort);
568
+ }
538
569
  const skip = typeof doc.skip === 'number' ? doc.skip : 0;
539
570
  if (skip > 0) rows = rows.slice(skip);
540
571
  const limit = typeof doc.limit === 'number' ? doc.limit : 0;
@@ -606,23 +637,7 @@ class MongoServer {
606
637
  else if (stage.$limit) rows = rows.slice(0, stage.$limit);
607
638
  else if (stage.$skip) rows = rows.slice(Number(stage.$skip) || 0);
608
639
  else if (stage.$sort) {
609
- const sortKeys = Object.entries(stage.$sort);
610
- rows = [...rows].sort((a, b) => {
611
- for (const [k, dir] of sortKeys) {
612
- const av = a[k]; const bv = b[k];
613
- // valuesEqual:同字节 ObjectId 不 ===,缺这一道相等短路时
614
- // 相等键会破坏排序稳定性(sort+skip/limit 分页会丢/重文档)
615
- if (av === bv || valuesEqual(av, bv)) continue;
616
- const desc = Number(dir) < 0;
617
- // Issue #47:NULL 的位置随排序方向走(升序在前、降序在后),
618
- // 与 MongoDB 一致;此前固定返回 1/-1,升序时 null 恒排最后。
619
- if (av == null) return desc ? 1 : -1;
620
- if (bv == null) return desc ? -1 : 1;
621
- const cmp = av < bv ? -1 : 1;
622
- return desc ? -cmp : cmp;
623
- }
624
- return 0;
625
- });
640
+ rows = sortRows(rows, stage.$sort);
626
641
  }
627
642
  else if (stage.$project) {
628
643
  const proj = stage.$project;
@@ -806,6 +821,17 @@ class MongoServer {
806
821
  if (ids.length > 0) await engine.removeByIds(coll, ids);
807
822
  }
808
823
 
824
+ /** $elemMatch 单元素求值:对象元素按子文档匹配;标量/数组元素只在操作符条件下可能命中 */
825
+ _elemMatches(el, cond) {
826
+ if (el !== null && typeof el === 'object' && !Array.isArray(el)) return this._match(el, cond);
827
+ // 标量元素:{$elemMatch:{$gt:5}} 这类操作符条件包成 {_val: el} 求值;
828
+ // {$elemMatch:{k:1}} 这类子文档条件对标量元素恒为 false。
829
+ if (!cond || typeof cond !== 'object' || Array.isArray(cond)) return false;
830
+ const keys = Object.keys(cond);
831
+ return keys.length > 0 && keys.every(c => c[0] === '$')
832
+ && this._match({ _val: el }, { _val: cond });
833
+ }
834
+
809
835
  _match(row, filter) {
810
836
  for (const [k, cond] of Object.entries(filter || {})) {
811
837
  if (k === '$or') {
@@ -828,18 +854,22 @@ class MongoServer {
828
854
  if (cond && typeof cond === 'object' && !Array.isArray(cond) && !(cond instanceof ObjectId)) {
829
855
  for (const [op, v] of Object.entries(cond)) {
830
856
  const rv = row[k];
831
- if (op === '$eq' && !valuesEqual(rv, v)) return false;
832
- if (op === '$gt' && !(rv > v)) return false;
833
- if (op === '$gte' && !(rv >= v)) return false;
834
- if (op === '$lt' && !(rv < v)) return false;
835
- if (op === '$lte' && !(rv <= v)) return false;
836
- if (op === '$ne' && valuesEqual(rv, v)) return false;
837
- if (op === '$in' && !arrayIncludesValue(v, rv)) return false;
838
- if (op === '$nin' && arrayIncludesValue(v, rv)) return false;
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;
839
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;
840
869
  if (op === '$regex') {
841
870
  const flags = String(cond.$options || '').includes('i') ? 'i' : '';
842
- if (typeof rv !== 'string' || !new RegExp(String(v), flags).test(rv)) return false;
871
+ const re = new RegExp(String(v), flags);
872
+ if (!orAnyElement(rv, el => typeof el === 'string' && re.test(el))) return false;
843
873
  }
844
874
  if (op === '$type') {
845
875
  if (v === 'objectId') { if (!(rv instanceof ObjectId)) return false; continue; }
@@ -847,9 +877,9 @@ class MongoServer {
847
877
  if (typeof rv !== t) return false;
848
878
  }
849
879
  if (op === '$size' && !(Array.isArray(rv) && rv.length === v)) return false;
850
- if (op === '$elemMatch' && !(Array.isArray(rv) && rv.some((el) => this._match(el, v)))) return false;
880
+ if (op === '$elemMatch' && !(Array.isArray(rv) && rv.some((el) => this._elemMatches(el, v)))) return false;
851
881
  }
852
- } else if (!valuesEqual(row[k], cond)) {
882
+ } else if (!orAnyElement(row[k], (el) => valuesEqual(el, cond))) {
853
883
  return false;
854
884
  }
855
885
  }
package/lib/objectid.js CHANGED
@@ -82,6 +82,27 @@ function arrayIncludesValue(arr, v) {
82
82
  return false;
83
83
  }
84
84
 
85
+ /**
86
+ * Mongo 数组字段语义(table.js / mongo_server.js 共用):
87
+ * 标量条件在字段值本身命中,或数组字段时任一元素命中,都算匹配。
88
+ * {tags: "a"} / {$in} / {$eq} / {$regex} 走这条;$ne/$nin 是它的取反。
89
+ */
90
+ function orAnyElement(value, pred) {
91
+ if (Array.isArray(value)) return pred(value) || value.some(pred);
92
+ return pred(value);
93
+ }
94
+
95
+ /**
96
+ * Mongo 范围语义:null/缺失永不参与比较(JS 的 null > -1 是 true,属
97
+ * 强制转换陷阱);数组字段只按元素比较(数组整体的 >/< 是字符串拼接
98
+ * 后的比较,无意义)。
99
+ */
100
+ function anyElementRange(value, pred) {
101
+ if (value === null || value === undefined) return false;
102
+ if (Array.isArray(value)) return value.some(el => el !== null && el !== undefined && pred(el));
103
+ return pred(value);
104
+ }
105
+
85
106
  /**
86
107
  * Map/Set 的规范键:同字节 ObjectId 归并为同一键,且不与任何真实 BSON
87
108
  * 字符串冲突 —— BSON 的 cstring/string 以 \0 结尾,wire 上不可能出现含
@@ -91,4 +112,4 @@ function mapKey(v) {
91
112
  return v instanceof ObjectId ? '\0oid:' + v.toString() : v;
92
113
  }
93
114
 
94
- module.exports = { ObjectId, valuesEqual, arrayIncludesValue, mapKey };
115
+ module.exports = { ObjectId, valuesEqual, arrayIncludesValue, mapKey, orAnyElement, anyElementRange };
package/lib/sql.js CHANGED
@@ -3459,16 +3459,27 @@ function isBinaryValue(v) { return v instanceof BinaryValue; }
3459
3459
  * Issue #111:按 Unicode code point 定位子串,返回 1-based 字符位置;
3460
3460
  * 未找到返回 0(与 MySQL LOCATE/INSTR 一致)。空子串返回 1。
3461
3461
  * 用 Array.from 把代理对拆成单个 code point,避免 emoji 被当成两个字符。
3462
+ *
3463
+ * Issue #116:新增 startPos(1-based,含起点),从该位置开始向右扫描,
3464
+ * 返回的仍是**绝对**字符位置(不是相对偏移),与 MySQL LOCATE(substr,str,pos) 一致:
3465
+ * LOCATE('bar','foobarbar',5) → 7
3466
+ * LOCATE('b','abcabc',3) → 5
3467
+ * LOCATE('b','abcabc',6) → 0
3468
+ * pos < 1 按 1 处理;pos 超出串长时只有空子串还可能命中(pos === len+1)。
3462
3469
  */
3463
- function codePointIndexOf(needle, haystack) {
3470
+ function codePointIndexOf(needle, haystack, startPos = 1) {
3464
3471
  const hay = Array.from(String(haystack));
3465
3472
  const pat = Array.from(String(needle));
3466
- if (pat.length === 0) return 1;
3467
- outer: for (let i = 0; i + pat.length <= hay.length; i++) {
3473
+ let pos = Math.trunc(Number(startPos));
3474
+ if (!Number.isFinite(pos) || pos < 1) pos = 1;
3475
+ if (pat.length === 0) return pos <= hay.length + 1 ? pos : 0;
3476
+ if (pos > hay.length) return 0;
3477
+ for (let i = pos - 1; i + pat.length <= hay.length; i++) {
3478
+ let hit = true;
3468
3479
  for (let j = 0; j < pat.length; j++) {
3469
- if (hay[i + j] !== pat[j]) continue outer;
3480
+ if (hay[i + j] !== pat[j]) { hit = false; break; }
3470
3481
  }
3471
- return i + 1;
3482
+ if (hit) return i + 1;
3472
3483
  }
3473
3484
  return 0;
3474
3485
  }
@@ -4732,6 +4743,34 @@ function applyScalarFunction(fnNode, row, ctx) {
4732
4743
  case 'MOD': return (args[0] == null || args[1] === 0) ? null : args[0] % args[1];
4733
4744
  case 'POWER': case 'POW': return (args[0] == null || args[1] == null) ? null : finiteOrNull(Math.pow(args[0], args[1]));
4734
4745
  case 'SQRT': return args[0] == null ? null : finiteOrNull(Math.sqrt(args[0]));
4746
+ // #117:这些函数在 MATH_SCALAR_FNS 里声明了,却没有 case 分支,落到
4747
+ // default 静默返回 NULL。定义域外(LOG(0)、ASIN(2)、COT(0)…)按 MySQL
4748
+ // 返回 NULL,统一走 finiteOrNull。
4749
+ case 'LOG': { // LOG(X) = ln(X);LOG(B, X) = 以 B 为底
4750
+ if (args[0] == null) return null;
4751
+ if (args.length < 2) return finiteOrNull(Math.log(args[0]));
4752
+ if (args[1] == null) return null;
4753
+ if (args[0] <= 0 || args[0] === 1 || args[1] <= 0) return null;
4754
+ return finiteOrNull(Math.log(args[1]) / Math.log(args[0]));
4755
+ }
4756
+ case 'LN': return args[0] == null ? null : finiteOrNull(Math.log(args[0]));
4757
+ case 'LOG10': return args[0] == null ? null : finiteOrNull(Math.log10(args[0]));
4758
+ case 'LOG2': return args[0] == null ? null : finiteOrNull(Math.log2(args[0]));
4759
+ case 'EXP': return args[0] == null ? null : finiteOrNull(Math.exp(args[0]));
4760
+ case 'SIN': return args[0] == null ? null : finiteOrNull(Math.sin(args[0]));
4761
+ case 'COS': return args[0] == null ? null : finiteOrNull(Math.cos(args[0]));
4762
+ case 'TAN': return args[0] == null ? null : finiteOrNull(Math.tan(args[0]));
4763
+ case 'COT': return args[0] == null ? null : finiteOrNull(1 / Math.tan(args[0]));
4764
+ case 'ASIN': return args[0] == null ? null : finiteOrNull(Math.asin(args[0]));
4765
+ case 'ACOS': return args[0] == null ? null : finiteOrNull(Math.acos(args[0]));
4766
+ case 'ATAN': { // ATAN(X);ATAN(Y, X) 等同 ATAN2(Y, X)
4767
+ if (args[0] == null) return null;
4768
+ if (args.length < 2) return finiteOrNull(Math.atan(args[0]));
4769
+ return args[1] == null ? null : finiteOrNull(Math.atan2(args[0], args[1]));
4770
+ }
4771
+ case 'ATAN2': return (args[0] == null || args[1] == null) ? null : finiteOrNull(Math.atan2(args[0], args[1]));
4772
+ case 'DEGREES': return args[0] == null ? null : finiteOrNull(args[0] * 180 / Math.PI);
4773
+ case 'RADIANS': return args[0] == null ? null : finiteOrNull(args[0] * Math.PI / 180);
4735
4774
  case 'IFNULL': case 'NVL': return args[0] != null ? args[0] : args[1];
4736
4775
  case 'COALESCE': {
4737
4776
  // 不能直接 return find(...):全都取不到值时 find 返回 undefined,
@@ -4785,8 +4824,13 @@ function applyScalarFunction(fnNode, row, ctx) {
4785
4824
  }
4786
4825
  case 'LOCATE': {
4787
4826
  if (args[0] == null || args[1] == null) return null;
4827
+ // Issue #116:三参形式 LOCATE(substr, str, pos) 必须从 pos 开始(含 pos)扫描,
4828
+ // 返回绝对 1-based 字符位置;此前 pos 被静默忽略,导致结果错误。
4829
+ // 任一参数为 NULL 时返回 NULL(与 MySQL 一致)。
4830
+ const startPos = args.length > 2 ? args[2] : 1;
4831
+ if (startPos == null) return null;
4788
4832
  // Issue #111:按 code point 定位,返回**字符**位置(不是 UTF-16 code unit 下标)
4789
- return codePointIndexOf(String(args[0]), String(args[1]));
4833
+ return codePointIndexOf(String(args[0]), String(args[1]), startPos);
4790
4834
  }
4791
4835
  case 'INSTR': {
4792
4836
  // INSTR(str, substr):参数顺序与 LOCATE(substr, str) 相反。
package/lib/table.js CHANGED
@@ -9,7 +9,7 @@ const BTree = require('./btree');
9
9
  const { createRowCache } = require('./row_cache');
10
10
  const { validateDateType, now } = require('./date-types');
11
11
  const { createError, JSQL_Error } = require('./errors');
12
- const { ObjectId, valuesEqual, arrayIncludesValue } = require('./objectid');
12
+ const { ObjectId, valuesEqual, arrayIncludesValue, orAnyElement, anyElementRange } = require('./objectid');
13
13
 
14
14
  // ---------------------------------------------------------------------------
15
15
  // DEFAULT 表达式求值(Issue #72)
@@ -98,7 +98,7 @@ function normalizeInteger(v, type) {
98
98
  const FAST_MATCH_OPS = new Set([
99
99
  '$eq', '$ne', '$gt', '$gte', '$lt', '$lte',
100
100
  '$in', '$nin', '$between', '$exists', '$isNull',
101
- '$startsWith', '$endsWith', '$contains', '$type', '$size',
101
+ '$startsWith', '$endsWith', '$contains', '$type', '$size', '$all',
102
102
  ]);
103
103
 
104
104
  function isSafeRegex(pattern) {
@@ -1391,11 +1391,28 @@ class Table {
1391
1391
  return copy || condition;
1392
1392
  }
1393
1393
 
1394
+ /**
1395
+ * Issue #44:索引查找前先把查询值归一成列声明类型,避免 '5' 查不到 5
1396
+ *
1397
+ * Mongo 数组语义落地后,还多了一层索引正确性约束:B-Tree / hash 索引的
1398
+ * 键是整字段值(数组只会以整体为键),数组字段的「元素命中」行不会
1399
+ * 出现在索引候选里 —— 索引预过滤会静默丢行。schemaless 字段与
1400
+ * object/array/json 类型列可能存数组,跳过索引快路径走全表过滤;
1401
+ * 标量类型列的写入被 _validateDataTypes 挡住数组,索引仍然安全。
1402
+ */
1403
+ _fieldMayHoldArrays(field) {
1404
+ const def = this._schema[field];
1405
+ if (!def) return true;
1406
+ const t = (typeof def === 'string' ? def : String(def.type || '')).toLowerCase();
1407
+ return t === '' || t === 'object' || t === 'array' || t === 'json' || t === 'jsonb';
1408
+ }
1409
+
1394
1410
  _applyFilterOptimized(rows, query) {
1395
1411
  // Issue #44:索引查找前先把查询值归一成列声明类型,避免 '5' 查不到 5
1396
1412
  const q = this._coerceQuery(query);
1397
1413
  for (const [field, condition] of Object.entries(q)) {
1398
1414
  if (field === '$or' || field === '$and' || field === '$not') continue;
1415
+ if ((this._indexes[field] || this._btrees[field]) && this._fieldMayHoldArrays(field)) continue;
1399
1416
  if (typeof condition !== 'object' || condition === null || Array.isArray(condition) || condition instanceof RegExp) {
1400
1417
  if (this._btrees[field]) {
1401
1418
  const indices = this._btrees[field].search(condition);
@@ -1444,6 +1461,8 @@ class Table {
1444
1461
  } else {
1445
1462
  indices = exclusiveMax ? this._btrees[field].lessThan(max) : this._btrees[field].lessThanEqual(max);
1446
1463
  }
1464
+ // 与等值/$in 路径一致:空命中回落全表过滤,不能当「无数据」
1465
+ if (indices.length === 0) return this._applyFilter(rows, q);
1447
1466
  return this._applyFilter(this._rowsFromIndices(indices), q);
1448
1467
  }
1449
1468
  }
@@ -1486,8 +1505,10 @@ class Table {
1486
1505
  // --- 字段路径:点号路径预先切好,循环里不再 split/includes ---
1487
1506
  const path = (field.indexOf('.') !== -1 && field[0] !== '$') ? field.split('.') : null;
1488
1507
 
1508
+ // ObjectId 是值不是嵌套条件:没有这道守卫时会按 {_bytes,_hex} 结构
1509
+ // 匹配,任一侧被 toString() 缓存过 _hex 后等值静默失效
1489
1510
  const plainObj = condition !== null && typeof condition === 'object'
1490
- && !Array.isArray(condition) && !(condition instanceof RegExp);
1511
+ && !Array.isArray(condition) && !(condition instanceof RegExp) && !(condition instanceof ObjectId);
1491
1512
 
1492
1513
  if (!plainObj) {
1493
1514
  parts.push({ k: 1, path, field, target: condition }); // 等值
@@ -1523,7 +1544,7 @@ class Table {
1523
1544
  }
1524
1545
  }
1525
1546
  if (!ok) { parts.push({ k: 7, q: { [field]: condition } }); continue; }
1526
- parts.push({ k: 2, path, field, ops });
1547
+ parts.push({ k: 2, path, field, ops, cond: condition });
1527
1548
  }
1528
1549
 
1529
1550
  return function match(row) {
@@ -1532,28 +1553,43 @@ class Table {
1532
1553
  switch (p.k) {
1533
1554
  case 1: { // 等值
1534
1555
  const v = p.path ? self._walk(row, p.path) : row[p.field];
1535
- if (v !== p.target) return false;
1556
+ // 数组值走通用匹配器(Mongo 元素语义);标量保持快路径,
1557
+ // 但相等判定补上 valuesEqual(同字节 ObjectId 不 ===)
1558
+ if (Array.isArray(v)) {
1559
+ if (!self._matchRow(row, { [p.field]: p.target })) return false;
1560
+ break;
1561
+ }
1562
+ if (v !== p.target && !valuesEqual(v, p.target)) return false;
1536
1563
  break;
1537
1564
  }
1538
1565
  case 2: { // 操作符
1539
1566
  const v = p.path ? self._walk(row, p.path) : row[p.field];
1567
+ // 数组值整字段退回 _matchRow(元素语义逐操作符生效)
1568
+ if (Array.isArray(v)) {
1569
+ if (!self._matchRow(row, { [p.field]: p.cond })) return false;
1570
+ break;
1571
+ }
1540
1572
  const ops = p.ops;
1541
1573
  for (let j = 0; j < ops.length; j++) {
1542
1574
  const o = ops[j];
1543
1575
  const op = o.op;
1544
- if (op === '$eq') { if (v !== o.target) return false; }
1545
- else if (op === '$ne') { if (v === o.target) return false; }
1546
- else if (op === '$gt') { if (!(v > o.target)) return false; }
1547
- else if (op === '$gte') { if (!(v >= o.target)) return false; }
1548
- else if (op === '$lt') { if (!(v < o.target)) return false; }
1549
- else if (op === '$lte') { if (!(v <= o.target)) return false; }
1550
- else if (op === '$in') { if (!Array.isArray(o.target) || o.target.indexOf(v) === -1) return false; }
1576
+ if (op === '$eq') { if (v !== o.target && !valuesEqual(v, o.target)) return false; }
1577
+ else if (op === '$ne') { if (valuesEqual(v, o.target)) return false; }
1578
+ // 范围操作符 null/缺失永不命中(JS 的 null > -1 === true),
1579
+ // 与 _matchOperator 的 anyElementRange 语义一致
1580
+ else if (op === '$gt') { if (v == null || !(v > o.target)) return false; }
1581
+ else if (op === '$gte') { if (v == null || !(v >= o.target)) return false; }
1582
+ else if (op === '$lt') { if (v == null || !(v < o.target)) return false; }
1583
+ else if (op === '$lte') { if (v == null || !(v <= o.target)) return false; }
1584
+ else if (op === '$in') {
1585
+ if (!Array.isArray(o.target) || !arrayIncludesValue(o.target, v)) return false;
1586
+ }
1551
1587
  else if (op === '$nin') {
1552
1588
  // 非数组 target 时原实现返回 false(不匹配),不能当成通过
1553
- if (!Array.isArray(o.target) || o.target.indexOf(v) !== -1) return false;
1589
+ if (!Array.isArray(o.target) || arrayIncludesValue(o.target, v)) return false;
1554
1590
  }
1555
1591
  else if (op === '$between') {
1556
- if (!Array.isArray(o.target) || o.target.length !== 2
1592
+ if (!Array.isArray(o.target) || o.target.length !== 2 || v == null
1557
1593
  || !(v >= o.target[0]) || !(v <= o.target[1])) return false;
1558
1594
  }
1559
1595
  else if (op === '$exists') { if (o.target ? v === undefined : v !== undefined) return false; }
@@ -1660,7 +1696,8 @@ class Table {
1660
1696
  }
1661
1697
  }
1662
1698
  } else {
1663
- if (!valuesEqual(value, condition)) return false;
1699
+ // Mongo 数组语义:字段是数组时任一元素相等即匹配
1700
+ if (!orAnyElement(value, el => valuesEqual(el, condition))) return false;
1664
1701
  }
1665
1702
  }
1666
1703
  return true;
@@ -1668,14 +1705,16 @@ class Table {
1668
1705
 
1669
1706
  _matchOperator(value, op, target) {
1670
1707
  switch (op) {
1671
- case '$eq': return valuesEqual(value, target);
1672
- case '$ne': return !valuesEqual(value, target);
1673
- case '$gt': return value > target;
1674
- case '$gte': return value >= target;
1675
- case '$lt': return value < target;
1676
- case '$lte': return value <= target;
1677
- case '$in': return Array.isArray(target) && arrayIncludesValue(target, value);
1678
- case '$nin': return Array.isArray(target) && !arrayIncludesValue(target, value);
1708
+ // 等值 / $in / $regex 家族带 Mongo 数组语义:字段是数组时任一
1709
+ // 元素命中即匹配;$ne / $nin 是同一语义的取反。
1710
+ case '$eq': return orAnyElement(value, el => valuesEqual(el, target));
1711
+ case '$ne': return !orAnyElement(value, el => valuesEqual(el, target));
1712
+ case '$gt': return anyElementRange(value, el => el > target);
1713
+ case '$gte': return anyElementRange(value, el => el >= target);
1714
+ case '$lt': return anyElementRange(value, el => el < target);
1715
+ case '$lte': return anyElementRange(value, el => el <= target);
1716
+ case '$in': return Array.isArray(target) && orAnyElement(value, el => arrayIncludesValue(target, el));
1717
+ case '$nin': return Array.isArray(target) && !orAnyElement(value, el => arrayIncludesValue(target, el));
1679
1718
  case '$like':
1680
1719
  if (typeof value !== 'string' || typeof target !== 'string') return false;
1681
1720
  {
@@ -1686,13 +1725,14 @@ class Table {
1686
1725
  return new RegExp('^' + escaped + '$', 'i').test(value);
1687
1726
  }
1688
1727
  case '$regex':
1689
- if (target instanceof RegExp) return target.test(String(value));
1728
+ if (target instanceof RegExp) return orAnyElement(value, el => target.test(String(el)));
1690
1729
  if (!isSafeRegex(target)) throw createError('ER_BAD_REGEX', String(target));
1691
- return new RegExp(target).test(String(value));
1730
+ return orAnyElement(value, el => new RegExp(target).test(String(el)));
1692
1731
  case '$exists':
1693
1732
  return target ? value !== undefined : value === undefined;
1694
1733
  case '$between':
1695
- return Array.isArray(target) && target.length === 2 && value >= target[0] && value <= target[1];
1734
+ return Array.isArray(target) && target.length === 2
1735
+ && anyElementRange(value, el => el >= target[0] && el <= target[1]);
1696
1736
  case '$and':
1697
1737
  return Array.isArray(target) && target.every(sub => this._matchRow({ _val: value }, { _val: sub }));
1698
1738
  case '$or':
@@ -1705,9 +1745,20 @@ class Table {
1705
1745
  return typeof value === target;
1706
1746
  case '$size':
1707
1747
  return Array.isArray(value) && value.length === target;
1748
+ case '$all':
1749
+ // Mongo:数组字段须包含 target 中的每一个值(逐元素相等);
1750
+ // 标量字段上 {$all:[x]} 退化为等值匹配。shortcut: 不支持
1751
+ // $all: [{$elemMatch: ...}] 外键形式,需要时再补。
1752
+ return Array.isArray(target)
1753
+ && target.every(t => orAnyElement(value, el => valuesEqual(el, t)));
1708
1754
  case '$elemMatch':
1755
+ // 对象元素按子文档匹配;标量/数组元素包成 {_val: el} 走
1756
+ // 操作符路径(与上面 $and/$or 的值级匹配同一手法)——此前
1757
+ // 标量元素直接 el === target,操作符条件永远不命中。
1709
1758
  return Array.isArray(value) && value.some(el =>
1710
- typeof el === 'object' ? this._matchRow(el, target) : el === target);
1759
+ (el !== null && typeof el === 'object' && !Array.isArray(el))
1760
+ ? this._matchRow(el, target)
1761
+ : this._matchRow({ _val: el }, { _val: target }));
1711
1762
  case '$isNull':
1712
1763
  return target ? value === null || value === undefined : value !== null && value !== undefined;
1713
1764
  case '$startsWith':
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.7.7",
3
+ "version": "6.8.1",
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,18 +52,18 @@
52
52
  "build:native": "node scripts/build-native.js",
53
53
  "check:release": "node scripts/check-release-metadata.js",
54
54
  "release:prep": "node scripts/release.js",
55
- "test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js",
55
+ "test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/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/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",
60
+ "test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/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",
64
64
  "test:cte": "node test/recursive-cte.test.js",
65
65
  "test:index": "node test/index-ddl.test.js",
66
- "test:mongo": "node test/mongo-group.test.js",
66
+ "test:mongo": "node test/mongo-group.test.js && node test/mongo-arrays.test.js",
67
67
  "test:multi": "node test/multiprotocol.test.js",
68
68
  "test:star": "node test/star-nag.test.js",
69
69
  "test:savepoint": "node test/savepoint.test.js",
@@ -0,0 +1,82 @@
1
+ /* ---- Issue #116:LOCATE(substr, str, pos) 必须尊重第 3 个参数 pos ---- */
2
+ /*
3
+ * MySQL 8.0 语义(LOCATE(substr, str, pos)):
4
+ * - 从位置 pos 开始(**含** pos)向右找 substr;
5
+ * - 返回 substr 首次出现的**绝对** 1-based 字符位置(不是相对偏移);
6
+ * - 找不到返回 0;任一参数为 NULL 返回 NULL;
7
+ * - pos < 1 按 1 处理。
8
+ *
9
+ * 此前 `applyScalarFunction` 的 LOCATE 分支只把 args[0]/args[1] 交给
10
+ * codePointIndexOf(needle, haystack),args[2] 从未被读取 —— 三参形式
11
+ * 静默退化成两参形式,返回一个"看起来合理"但错误的位置。
12
+ *
13
+ * 参考值:
14
+ * LOCATE('b','abcabc',1) = 2 LOCATE('bar','foobarbar',5) = 7
15
+ * LOCATE('b','abcabc',3) = 5 LOCATE('b','abcabc',6) = 0
16
+ *
17
+ * node test/issue-116.test.js
18
+ */
19
+ const path = require('path');
20
+ const ROOT = path.join(__dirname, '..');
21
+ const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
22
+
23
+ let pass = 0, fail = 0;
24
+ function ok(name, cond, got) {
25
+ if (cond) { pass++; console.log('[OK] ' + name); }
26
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
27
+ }
28
+
29
+ (async () => {
30
+ const db = new Database(':memory:', { autoSave: false });
31
+ const q = async (sql) => {
32
+ const r = await executeSQL(db, sql, { safety: false });
33
+ return r.rows[0][0];
34
+ };
35
+
36
+ // ---------- issue 的差分表:pos 必须生效 ----------
37
+ ok("LOCATE('b','abcabc') = 2", await q("SELECT LOCATE('b','abcabc')") === 2, await q("SELECT LOCATE('b','abcabc')"));
38
+ ok("LOCATE('b','abcabc',1) = 2", await q("SELECT LOCATE('b','abcabc',1)") === 2, await q("SELECT LOCATE('b','abcabc',1)"));
39
+ ok("LOCATE('b','abcabc',3) = 5", await q("SELECT LOCATE('b','abcabc',3)") === 5, await q("SELECT LOCATE('b','abcabc',3)"));
40
+ ok("LOCATE('b','abcabc',5) = 5", await q("SELECT LOCATE('b','abcabc',5)") === 5, await q("SELECT LOCATE('b','abcabc',5)"));
41
+ ok("LOCATE('b','abcabc',6) = 0", await q("SELECT LOCATE('b','abcabc',6)") === 0, await q("SELECT LOCATE('b','abcabc',6)"));
42
+ ok("LOCATE('bar','foobarbar',5) = 7", await q("SELECT LOCATE('bar','foobarbar',5)") === 7, await q("SELECT LOCATE('bar','foobarbar',5)"));
43
+
44
+ // 返回的是绝对位置,不是相对偏移(若实现成相对偏移这里会得到 2/10)
45
+ ok("LOCATE('bar','foobarbar',4) = 4", await q("SELECT LOCATE('bar','foobarbar',4)") === 4, await q("SELECT LOCATE('bar','foobarbar',4)"));
46
+ ok("LOCATE('bar','foobarbar',7) = 7", await q("SELECT LOCATE('bar','foobarbar',7)") === 7, await q("SELECT LOCATE('bar','foobarbar',7)"));
47
+ ok("LOCATE('bar','foobarbar',8) = 0(剩 'ar' 不够长)", await q("SELECT LOCATE('bar','foobarbar',8)") === 0, await q("SELECT LOCATE('bar','foobarbar',8)"));
48
+
49
+ // ---------- 边界 ----------
50
+ ok("LOCATE('b','abcabc',0) = 2(pos<1 按 1)", await q("SELECT LOCATE('b','abcabc',0)") === 2, await q("SELECT LOCATE('b','abcabc',0)"));
51
+ ok("LOCATE('b','abcabc',-5) = 2(pos<1 按 1)", await q("SELECT LOCATE('b','abcabc',-5)") === 2, await q("SELECT LOCATE('b','abcabc',-5)"));
52
+ ok("LOCATE('b','abcabc',7) = 0(pos>len)", await q("SELECT LOCATE('b','abcabc',7)") === 0, await q("SELECT LOCATE('b','abcabc',7)"));
53
+ ok("LOCATE('b','abcabc',99) = 0", await q("SELECT LOCATE('b','abcabc',99)") === 0, await q("SELECT LOCATE('b','abcabc',99)"));
54
+ ok("LOCATE('b','abcabc',3.9) = 5(pos 取整)", await q("SELECT LOCATE('b','abcabc',3.9)") === 5, await q("SELECT LOCATE('b','abcabc',3.9)"));
55
+
56
+ // 空子串:两参形式仍为 1(行为不变);三参形式为 pos(MySQL 同)
57
+ ok("LOCATE('','abc') = 1", await q("SELECT LOCATE('','abc')") === 1, await q("SELECT LOCATE('','abc')"));
58
+ ok("LOCATE('','abc',3) = 3", await q("SELECT LOCATE('','abc',3)") === 3, await q("SELECT LOCATE('','abc',3)"));
59
+
60
+ // ---------- NULL 传播 ----------
61
+ ok("LOCATE(NULL,'abc',2) IS NULL", await q("SELECT LOCATE(NULL,'abc',2)") === null, await q("SELECT LOCATE(NULL,'abc',2)"));
62
+ ok("LOCATE('b',NULL,2) IS NULL", await q("SELECT LOCATE('b',NULL,2)") === null, await q("SELECT LOCATE('b',NULL,2)"));
63
+ ok("LOCATE('b','abcabc',NULL) IS NULL", await q("SELECT LOCATE('b','abcabc',NULL)") === null, await q("SELECT LOCATE('b','abcabc',NULL)"));
64
+
65
+ // ---------- Unicode:pos 与返回值都按 code point 计(Issue #111 语义)----------
66
+ // 'a🚀b🚀' = a 🚀 b 🚀 字符位置:1 2 3 4
67
+ ok("LOCATE('b','a🚀b🚀',1) = 3", await q("SELECT LOCATE('b','a🚀b🚀',1)") === 3, await q("SELECT LOCATE('b','a🚀b🚀',1)"));
68
+ ok("LOCATE('🚀','a🚀b🚀',2) = 2", await q("SELECT LOCATE('🚀','a🚀b🚀',2)") === 2, await q("SELECT LOCATE('🚀','a🚀b🚀',2)"));
69
+ ok("LOCATE('🚀','a🚀b🚀',3) = 4", await q("SELECT LOCATE('🚀','a🚀b🚀',3)") === 4, await q("SELECT LOCATE('🚀','a🚀b🚀',3)"));
70
+ ok("LOCATE('🚀','a🚀b🚀',5) = 0", await q("SELECT LOCATE('🚀','a🚀b🚀',5)") === 0, await q("SELECT LOCATE('🚀','a🚀b🚀',5)"));
71
+
72
+ // ---------- 两参形式与 INSTR 不受影响 ----------
73
+ ok("LOCATE('bar','foobarbar') = 4", await q("SELECT LOCATE('bar','foobarbar')") === 4, await q("SELECT LOCATE('bar','foobarbar')"));
74
+ ok("INSTR('abcabc','b') = 2", await q("SELECT INSTR('abcabc','b')") === 2, await q("SELECT INSTR('abcabc','b')"));
75
+ ok("INSTR('foobarbar','bar') = 4", await q("SELECT INSTR('foobarbar','bar')") === 4, await q("SELECT INSTR('foobarbar','bar')"));
76
+
77
+ console.log(`\n${pass} passed, ${fail} failed`);
78
+ process.exit(fail === 0 ? 0 : 1);
79
+ })().catch(e => {
80
+ console.log('[FAIL] unexpected exception: ' + e.stack.split('\n').slice(0, 3).join('\n'));
81
+ process.exit(1);
82
+ });
@@ -0,0 +1,102 @@
1
+ /* ---- Issue #117:MATH_SCALAR_FNS 里声明的 15 个数学函数必须真正求值 ---- */
2
+ /*
3
+ * LOG / LOG10 / LOG2 / LN / EXP / SIN / COS / TAN / ASIN / ACOS / ATAN /
4
+ * ATAN2 / DEGREES / RADIANS / COT 此前在 applyScalarFunction 里没有 case
5
+ * 分支,落到 default 静默返回 NULL。
6
+ *
7
+ * MySQL 8.0 语义:
8
+ * - 任一参数为 NULL → NULL;
9
+ * - 定义域外(LOG(0)、LN(-1)、ASIN(2)、LOG(1, x)…)→ NULL;
10
+ * - LOG(X) 为自然对数,LOG(B, X) 为以 B 为底;ATAN(Y, X) 等同 ATAN2(Y, X)。
11
+ *
12
+ * node test/issue-117.test.js
13
+ */
14
+ const path = require('path');
15
+ const ROOT = path.join(__dirname, '..');
16
+ const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
17
+
18
+ let pass = 0, fail = 0;
19
+ function ok(name, cond, got) {
20
+ if (cond) { pass++; console.log('[OK] ' + name); }
21
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
22
+ }
23
+ const near = (a, b) => typeof a === 'number' && Math.abs(a - b) < 1e-12;
24
+
25
+ (async () => {
26
+ const db = new Database(':memory:', { autoSave: false });
27
+ const q = async (sql) => {
28
+ const r = await executeSQL(db, sql, { safety: false });
29
+ return r.rows[0][0];
30
+ };
31
+ const eq = async (expr, want) => {
32
+ const got = await q('SELECT ' + expr);
33
+ ok(`${expr} = ${want}`, want === null ? got === null : near(got, want), got);
34
+ };
35
+
36
+ // ---------- issue 里的复现语句 ----------
37
+ {
38
+ const r = await executeSQL(db,
39
+ 'SELECT LOG2(8), LOG10(100), LN(1), EXP(0), SIN(0), COS(0), TAN(0), DEGREES(3.141592653589793), RADIANS(180)',
40
+ { safety: false });
41
+ const want = [3, 2, 0, 1, 0, 1, 0, 180, Math.PI];
42
+ ok('issue 复现语句', r.rows[0].length === want.length && r.rows[0].every((v, i) => near(v, want[i])), r.rows[0]);
43
+ }
44
+
45
+ // ---------- 每个函数的取值 ----------
46
+ await eq('LOG(EXP(1))', 1);
47
+ await eq('LOG(2, 8)', 3);
48
+ await eq('LOG(10, 1000)', 3);
49
+ await eq('LN(EXP(2))', 2);
50
+ await eq('LOG10(1000)', 3);
51
+ await eq('LOG2(1024)', 10);
52
+ await eq('EXP(1)', Math.E);
53
+ await eq('SIN(1.5707963267948966)', 1);
54
+ await eq('COS(3.141592653589793)', -1);
55
+ await eq('TAN(0.7853981633974483)', Math.tan(Math.PI / 4));
56
+ await eq('COT(1)', 1 / Math.tan(1));
57
+ await eq('ASIN(1)', Math.PI / 2);
58
+ await eq('ACOS(1)', 0);
59
+ await eq('ATAN(1)', Math.PI / 4);
60
+ await eq('ATAN(1, 1)', Math.PI / 4);
61
+ await eq('ATAN(-1, -1)', Math.atan2(-1, -1));
62
+ await eq('ATAN2(1, 1)', Math.PI / 4);
63
+ await eq('ATAN2(1, 0)', Math.PI / 2);
64
+ await eq('DEGREES(3.141592653589793)', 180);
65
+ await eq('RADIANS(90)', Math.PI / 2);
66
+ await eq("EXP('0')", 1);
67
+
68
+ // ---------- 定义域外 → NULL(不能漏出 NaN / Infinity)----------
69
+ await eq('LOG(0)', null);
70
+ await eq('LN(-1)', null);
71
+ await eq('LOG10(0)', null);
72
+ await eq('LOG2(-8)', null);
73
+ await eq('LOG(1, 8)', null);
74
+ await eq('LOG(-2, 8)', null);
75
+ await eq('LOG(2, 0)', null);
76
+ await eq('ASIN(2)', null);
77
+ await eq('ACOS(-1.5)', null);
78
+ await eq('COT(0)', null);
79
+ await eq('EXP(1000)', null);
80
+
81
+ // ---------- NULL 传播 ----------
82
+ for (const expr of ['LOG(NULL)', 'LOG(NULL, 8)', 'LOG(2, NULL)', 'LN(NULL)', 'LOG10(NULL)', 'LOG2(NULL)',
83
+ 'EXP(NULL)', 'SIN(NULL)', 'COS(NULL)', 'TAN(NULL)', 'COT(NULL)', 'ASIN(NULL)', 'ACOS(NULL)',
84
+ 'ATAN(NULL)', 'ATAN(1, NULL)', 'ATAN2(NULL, 1)', 'ATAN2(1, NULL)', 'DEGREES(NULL)', 'RADIANS(NULL)']) {
85
+ await eq(expr, null);
86
+ }
87
+
88
+ // ---------- BigInt 入参降级为 number(issue #38 的路径)----------
89
+ await eq('LOG2(9007199254740993)', 53);
90
+
91
+ // ---------- 用在表数据上 ----------
92
+ await executeSQL(db, 'CREATE TABLE m (id INT, x DOUBLE)', { safety: false });
93
+ await executeSQL(db, 'INSERT INTO m VALUES (1, 100), (2, 0), (3, NULL)', { safety: false });
94
+ const rows = (await executeSQL(db, 'SELECT id, LOG10(x) AS l FROM m ORDER BY id', { safety: false })).rows;
95
+ ok('LOG10 列计算:[2, NULL, NULL]', JSON.stringify(rows.map(r => r[1])) === '[2,null,null]', rows);
96
+
97
+ console.log(`\n${pass} passed, ${fail} failed`);
98
+ process.exit(fail === 0 ? 0 : 1);
99
+ })().catch(e => {
100
+ console.log('[FAIL] unexpected exception: ' + e.stack.split('\n').slice(0, 3).join('\n'));
101
+ process.exit(1);
102
+ });
@@ -0,0 +1,175 @@
1
+ /*
2
+ * MongoDB 数组字段过滤语义 + find 排序(与上游 dict 的 6 项缺陷对应):
3
+ *
4
+ * 1. find 命令静默忽略 sort —— 排序只在 aggregate 生效,sort+skip/limit 分页取错页。
5
+ * 2. 数组字段无元素匹配语义:{tags:"a"} / $in / $nin 拿整个数组对象比较,全部落空。
6
+ * 3. $ne 用严格 !== :同字节 ObjectId 等值被误判(编译快路径 $eq/$in/$nin 同病)。
7
+ * 4. $all 未实现:mongo_server 里未知操作符 vacuous 通过,table.js 里恒 false。
8
+ * 5. $elemMatch 只认对象元素:标量元素的操作符条件永远不命中。
9
+ * 6. 索引快路径丢行:数组字段的元素命中不在标量索引键里;range 路径还把
10
+ * 空索引命中当「无数据」。schemaless / JSON 列现在跳过索引走全表过滤。
11
+ *
12
+ * 范围声明:null/缺失不参与范围比较(JS 的 null > -1 === true 是陷阱);
13
+ * findAndModify 现在也尊重 doc.sort。
14
+ */
15
+ const path = require('path');
16
+ const { Database, createMongoServer } = require(path.join(__dirname, '..', 'index.js'));
17
+ const { ObjectId } = require(path.join(__dirname, '..', 'lib', 'objectid.js'));
18
+
19
+ let pass = 0, fail = 0;
20
+ function ok(name, cond, extra) {
21
+ if (cond) { pass++; console.log('[OK] ', name); }
22
+ else { fail++; console.log('[FAIL]', name, extra !== undefined ? '-> ' + JSON.stringify(extra, (k, v) => v && v.bytes ? v.toString() : v).slice(0, 300) : ''); }
23
+ }
24
+
25
+ async function insert(srv, docs) {
26
+ const r = await srv._dispatch('insert', { insert: 'c', $db: 'test', documents: docs });
27
+ if (r.ok !== 1 || r.n !== docs.length) throw new Error('insert failed: ' + JSON.stringify(r));
28
+ }
29
+
30
+ async function find(srv, filter, extra = {}) {
31
+ const r = await srv._dispatch('find', { find: 'c', $db: 'test', filter, ...extra });
32
+ return r.cursor ? r.cursor.firstBatch : [];
33
+ }
34
+
35
+ const ids = (batch) => batch.map((d) => d._id).sort((a, b) => a - b);
36
+
37
+ (async () => {
38
+ try {
39
+ /* ---------- 1. find + sort + skip/limit(mongo_server) ---------- */
40
+ {
41
+ const srv = createMongoServer({ port: 0, noAuth: true, dataDir: ':memory:' });
42
+ await (await srv._getEngine('test')).createTable('c', {});
43
+ await insert(srv, [
44
+ { _id: 1, score: 30, g: 'b' },
45
+ { _id: 2, score: 10, g: 'a' },
46
+ { _id: 3, score: 20, g: 'a' },
47
+ { _id: 4, score: 20, g: 'b' },
48
+ ]);
49
+
50
+ const asc = await find(srv, {}, { sort: { score: 1 } });
51
+ ok('find sort 升序生效', JSON.stringify(asc.map((d) => d.score)) === JSON.stringify([10, 20, 20, 30]), asc.map((d) => d.score));
52
+
53
+ const page = await find(srv, {}, { sort: { score: -1 }, skip: 1, limit: 2 });
54
+ ok('find sort+skip+limit 分页(sort 先于分页)', JSON.stringify(page.map((d) => d.score)) === JSON.stringify([20, 20]), page.map((d) => d.score));
55
+
56
+ const multi = await find(srv, {}, { sort: { g: 1, score: -1 } });
57
+ ok('find 多键排序', JSON.stringify(multi.map((d) => [d.g, d.score])) === JSON.stringify([['a', 20], ['a', 10], ['b', 30], ['b', 20]]), multi.map((d) => [d.g, d.score]));
58
+
59
+ const fam = await srv._dispatch('findAndModify', {
60
+ findAndModify: 'c', $db: 'test', query: {}, sort: { score: -1 }, update: { $set: { top: true } },
61
+ });
62
+ ok('findAndModify 尊重 sort(取最高分)', fam.value && fam.value._id === 1, fam.value);
63
+ }
64
+
65
+ /* ---------- 2-5. 数组字段过滤语义(mongo_server._match) ---------- */
66
+ {
67
+ const srv = createMongoServer({ port: 0, noAuth: true, dataDir: ':memory:' });
68
+ await (await srv._getEngine('test')).createTable('c', {});
69
+ await insert(srv, [
70
+ { _id: 1, tags: ['a', 'b'], scores: [5, 15] },
71
+ { _id: 2, tags: ['b'], scores: [25] },
72
+ { _id: 3, tags: ['c'], scores: [20], note: 'no arrays on other fields' },
73
+ ]);
74
+
75
+ ok('{tags:"a"} 元素命中', JSON.stringify(ids(await find(srv, { tags: 'a' }))) === '[1]');
76
+ ok('{tags:{$eq:"b"}} 元素命中', JSON.stringify(ids(await find(srv, { tags: { $eq: 'b' } }))) === '[1,2]');
77
+ ok('{tags:{$in:["a","c"]}}', JSON.stringify(ids(await find(srv, { tags: { $in: ['a', 'c'] } }))) === '[1,3]');
78
+ ok('{tags:{$nin:["b"]}}', JSON.stringify(ids(await find(srv, { tags: { $nin: ['b'] } }))) === '[3]');
79
+ ok('{tags:{$ne:"b"}}', JSON.stringify(ids(await find(srv, { tags: { $ne: 'b' } }))) === '[3]');
80
+ ok('{tags:{$all:["a","b"]}}', JSON.stringify(ids(await find(srv, { tags: { $all: ['a', 'b'] } }))) === '[1]');
81
+ ok('{tags:{$all:["b"]}}', JSON.stringify(ids(await find(srv, { tags: { $all: ['b'] } }))) === '[1,2]');
82
+ ok('{tags:{$gt:"a"}} 元素范围("b">"a"、"c">"a")', JSON.stringify(ids(await find(srv, { tags: { $gt: 'a' } }))) === '[1,2,3]');
83
+ ok('{scores:{$elemMatch:{$gt:10,$lt:25}}} 标量元素', JSON.stringify(ids(await find(srv, { scores: { $elemMatch: { $gt: 10, $lt: 25 } } }))) === '[1,3]');
84
+ // shortcut: 整数组等值({arr:[1,2]} / $in:[[1,2]])仍是引用严格相等,需要时再补深度相等
85
+ ok('{note:{$all:["no arrays on other fields"]}} 标量字段退化等值', JSON.stringify(ids(await find(srv, { note: { $all: ['no arrays on other fields'] } }))) === '[3]');
86
+
87
+ // aggregate $match 复用同一 _match,抽查一个
88
+ const agg = await srv._dispatch('aggregate', {
89
+ aggregate: 'c', $db: 'test', pipeline: [{ $match: { tags: 'a' } }],
90
+ });
91
+ ok('aggregate $match 数组语义', JSON.stringify(ids(agg.cursor.firstBatch)) === '[1]');
92
+
93
+ // null/缺失不参与范围比较:null > -1 在 JS 里是 true,必须挡住
94
+ const nullSrv = createMongoServer({ port: 0, noAuth: true, dataDir: ':memory:' });
95
+ await (await nullSrv._getEngine('test')).createTable('c', {});
96
+ await insert(nullSrv, [{ _id: 1, score: null }, { _id: 2, score: 5 }]);
97
+ ok('{score:{$gt:-1}} 不命中 null', JSON.stringify(ids(await find(nullSrv, { score: { $gt: -1 } }))) === '[2]');
98
+ }
99
+
100
+ /* ---------- 3. $ne 同字节 ObjectId(table.js 编译快路径) ---------- */
101
+ {
102
+ const db = new Database(':memory:');
103
+ await db.createTable('oid', {});
104
+ await db.insert('oid', { _id: 1, ref: new ObjectId('aaaaaaaaaaaaaaaaaaaaaaaa') });
105
+ await db.insert('oid', { _id: 2, ref: new ObjectId('bbbbbbbbbbbbbbbbbbbbbbbb') });
106
+ const rows = await db.find('oid', { ref: { $ne: new ObjectId('aaaaaaaaaaaaaaaaaaaaaaaa') } });
107
+ ok('table $ne:同字节 ObjectId 实例视为相等', JSON.stringify(rows.map((r) => r._id)) === '[2]', rows.map((r) => r._id));
108
+ const eq = await db.find('oid', { ref: new ObjectId('bbbbbbbbbbbbbbbbbbbbbbbb') });
109
+ ok('table 隐式等值:同字节 ObjectId 命中(快路径 valuesEqual)', JSON.stringify(eq.map((r) => r._id)) === '[2]', eq.map((r) => r._id));
110
+ }
111
+
112
+ /* ---------- 2/4/5/6. table.js 文档 API + 索引正确性 ---------- */
113
+ {
114
+ const db = new Database(':memory:');
115
+ // type 'object':json 类型的字符串值必须是合法 JSON,会拒绝标量 'a';
116
+ // object 类型不做该校验,标量与数组可以共存
117
+ await db.createTable('t', { id: { type: 'integer', primaryKey: true }, tags: { type: 'object' } });
118
+ await db.insert('t', { id: 1, tags: ['a', 'b'] });
119
+ await db.insert('t', { id: 2, tags: 'a' }); // 标量共存:索引命中部分行时数组行不能丢
120
+ await db.insert('t', { id: 3, tags: ['c'] });
121
+
122
+ // 6:先建索引(hash + B-Tree 都过一遍),数组行不得被索引预过滤丢掉
123
+ const table = db._ensureTable('t');
124
+ const withHash = await db.find('t', { tags: 'a' });
125
+ table.createIndex('tags');
126
+ const withHashIdx = await db.find('t', { tags: 'a' });
127
+ table.dropIndex('tags');
128
+ table.createBTreeIndex('tags');
129
+ const withBTree = await db.find('t', { tags: 'a' });
130
+ ok('无索引:{tags:"a"} 命中数组+标量行', JSON.stringify(withHash.map((r) => r.id)) === '[1,2]', withHash.map((r) => r.id));
131
+ ok('hash 索引不丢数组行', JSON.stringify(withHashIdx.map((r) => r.id)) === '[1,2]', withHashIdx.map((r) => r.id));
132
+ ok('B-Tree 索引不丢数组行', JSON.stringify(withBTree.map((r) => r.id)) === '[1,2]', withBTree.map((r) => r.id));
133
+
134
+ const inRows = await db.find('t', { tags: { $in: ['a', 'c'] } });
135
+ ok('table $in 数组语义(B-Tree 在场)', JSON.stringify(inRows.map((r) => r.id).sort()) === '[1,2,3]', inRows.map((r) => r.id));
136
+
137
+ const ninRows = await db.find('t', { tags: { $nin: ['b', 'a'] } });
138
+ ok('table $nin 数组语义', JSON.stringify(ninRows.map((r) => r.id)) === '[3]', ninRows.map((r) => r.id));
139
+
140
+ const allRows = await db.find('t', { tags: { $all: ['a', 'b'] } });
141
+ ok('table $all', JSON.stringify(allRows.map((r) => r.id)) === '[1]', allRows.map((r) => r.id));
142
+
143
+ const emRows = await db.find('t', { tags: { $elemMatch: { $eq: 'c' } } });
144
+ ok('table $elemMatch 标量元素(操作符条件)', JSON.stringify(emRows.map((r) => r.id)) === '[3]', emRows.map((r) => r.id));
145
+
146
+ // 6:JSON 列上的范围查询走全表过滤(B-Tree 范围键只有标量行)
147
+ await db.createTable('r', { id: { type: 'integer', primaryKey: true }, v: { type: 'json' } });
148
+ await db.insert('r', { id: 1, v: [5] });
149
+ await db.insert('r', { id: 2, v: [15] });
150
+ await db.insert('r', { id: 3, v: 10 });
151
+ const rt = db._ensureTable('r');
152
+ rt.createBTreeIndex('v');
153
+ const gt = await db.find('r', { v: { $gt: 6 } });
154
+ ok('JSON 列范围查询索引不丢行(元素+标量都命中)', JSON.stringify(gt.map((x) => x.id).sort()) === '[2,3]', gt.map((x) => x.id));
155
+
156
+ // 标量类型列的索引快路径保持原行为(不受 guard 影响)
157
+ await db.createTable('s', { id: { type: 'integer', primaryKey: true }, n: { type: 'integer' } });
158
+ await db.insert('s', { id: 1, n: 1 });
159
+ await db.insert('s', { id: 2, n: 2 });
160
+ db._ensureTable('s').createBTreeIndex('n');
161
+ const sRows = await db.find('s', { n: { $gte: 2 } });
162
+ ok('标量列 B-Tree 范围仍正确', JSON.stringify(sRows.map((x) => x.id)) === '[2]', sRows.map((x) => x.id));
163
+
164
+ // update/remove 也走 _applyFilterOptimized:数组字段不得漏改漏删
165
+ const upd = await db.update('t', { tags: 'a' }, { $set: { hit: true } });
166
+ ok('update 按数组语义命中所有行', upd === 2, upd);
167
+ }
168
+ } catch (e) {
169
+ fail++;
170
+ console.log('[FAIL] unexpected exception:', e && e.stack || e);
171
+ }
172
+
173
+ console.log(`\n${fail === 0 ? 'ALL PASS' : 'FAILURES'} — ${pass} passed, ${fail} failed\n`);
174
+ if (fail > 0) process.exit(1);
175
+ })();