jsql-neo 6.8.0 → 6.8.2

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/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
@@ -453,6 +453,13 @@ impl Engine for HybridEngine {
453
453
  r
454
454
  }
455
455
 
456
+ fn aggregate(&self, table: &str, op: &str, field: &str) -> Result<String, String> {
457
+ self.ensure_table(table);
458
+ let r = self.mem.borrow().aggregate(table, op, field);
459
+ if r.is_ok() { self.touch(table); }
460
+ r
461
+ }
462
+
456
463
  fn update_by_id(&mut self, table: &str, id: u64, data: HashMap<String, serde_json::Value>) -> Result<bool, String> {
457
464
  self.ensure_table(table);
458
465
  let r = self.mem.borrow_mut().update_by_id(table, id, data)?;
@@ -107,6 +107,11 @@ impl Engine for MemoryEngine {
107
107
  Ok(t.count())
108
108
  }
109
109
 
110
+ fn aggregate(&self, table: &str, op: &str, field: &str) -> Result<String, String> {
111
+ let t = self.tables.get(table).ok_or_else(|| format!("table '{}' not found", table))?;
112
+ Ok(t.aggregate_json(op, field))
113
+ }
114
+
110
115
  fn update_by_id(&mut self, table: &str, id: u64, data: HashMap<String, serde_json::Value>) -> Result<bool, String> {
111
116
  let t = self.tables.get_mut(table).ok_or_else(|| format!("table '{}' not found", table))?;
112
117
  t.update_row(id, data)
@@ -68,6 +68,8 @@ pub trait Engine {
68
68
  Ok((json, cursor, has_more))
69
69
  }
70
70
  fn count(&self, table: &str) -> Result<usize, String>;
71
+ /// 按列聚合(#126),返回 JSON 数值字符串。
72
+ fn aggregate(&self, table: &str, op: &str, field: &str) -> Result<String, String>;
71
73
  fn update_by_id(&mut self, table: &str, id: u64, data: HashMap<String, serde_json::Value>) -> Result<bool, String>;
72
74
  fn update_by_ids(&mut self, table: &str, batch: Vec<(u64, HashMap<String, serde_json::Value>)>) -> Result<usize, String>;
73
75
  fn remove_by_id(&mut self, table: &str, id: u64) -> Result<bool, String>;
@@ -906,6 +906,42 @@ impl Table {
906
906
  self.rows.len()
907
907
  }
908
908
 
909
+ /// 按列聚合 SUM/AVG/MIN/MAX(#126):直接在列式行缓冲区上单遍扫描,
910
+ /// 避免把整表行拉回 JS 层再聚合。返回 JSON 数值,空集/未知列返回 null。
911
+ pub fn aggregate_json(&self, op: &str, field: &str) -> String {
912
+ let col = match self.field_index.get(field) {
913
+ Some(i) => *i,
914
+ None => return "null".to_string(),
915
+ };
916
+ let mut sum = 0.0f64;
917
+ let mut count = 0usize;
918
+ let mut min: Option<f64> = None;
919
+ let mut max: Option<f64> = None;
920
+ for rs in &self.rows {
921
+ let vals = self.get_row_values(rs);
922
+ let n = match vals.get(col) {
923
+ Some(FieldValue::Int(i)) => *i as f64,
924
+ Some(FieldValue::UInt(u)) => *u as f64,
925
+ Some(FieldValue::Float(f)) => *f,
926
+ Some(FieldValue::Bool(b)) => if *b { 1.0 } else { 0.0 },
927
+ _ => continue,
928
+ };
929
+ if !n.is_finite() { continue; }
930
+ count += 1;
931
+ sum += n;
932
+ min = Some(min.map_or(n, |m| m.min(n)));
933
+ max = Some(max.map_or(n, |m| m.max(n)));
934
+ }
935
+ match op.to_ascii_uppercase().as_str() {
936
+ "COUNT" => count.to_string(),
937
+ "SUM" => if count == 0 { "null".to_string() } else { sum.to_string() },
938
+ "AVG" => if count == 0 { "null".to_string() } else { (sum / count as f64).to_string() },
939
+ "MIN" => min.map_or_else(|| "null".to_string(), |v| v.to_string()),
940
+ "MAX" => max.map_or_else(|| "null".to_string(), |v| v.to_string()),
941
+ _ => "null".to_string(),
942
+ }
943
+ }
944
+
909
945
  // ============================================================
910
946
  // 磁盘持久化导出 / 导入(供 HybridEngine 使用)
911
947
  // ============================================================
@@ -317,6 +317,11 @@ napi_engine_fn!(jsql_count, jsql_count_h, (table: String) => |eng| {
317
317
  }
318
318
  });
319
319
 
320
+ // #126:SUM/AVG/MIN/MAX 下沉到 Rust,单遍扫描列式行缓冲区
321
+ napi_engine_fn!(jsql_aggregate, jsql_aggregate_h, (table: String, op: String, field: String) => |eng| {
322
+ safe_json_result(eng.aggregate(&table, &op, &field))
323
+ });
324
+
320
325
  napi_engine_fn!(jsql_update_by_id, jsql_update_by_id_h,
321
326
  (table: String, id: i64, data_json: String) => |eng| {
322
327
  let data: HashMap<String, serde_json::Value> = match serde_json::from_str(&data_json) {
@@ -317,6 +317,14 @@ pub fn jsql_count(table: &str) -> String {
317
317
  })
318
318
  }
319
319
 
320
+ #[wasm_bindgen]
321
+ pub fn jsql_aggregate(table: &str, op: &str, field: &str) -> String {
322
+ ENGINE.with(|eng| match eng.borrow().aggregate(table, op, field) {
323
+ Ok(v) => v,
324
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),
325
+ })
326
+ }
327
+
320
328
  #[wasm_bindgen]
321
329
  pub fn jsql_update_by_id(table: &str, id: u64, data_json: &str) -> String {
322
330
  ENGINE.with(|eng| {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.8.0",
3
+ "version": "6.8.2",
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 && 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/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 && 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/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",
package/postinstall.js CHANGED
@@ -328,7 +328,9 @@ async function fetchExpectedHash(asset, tag) {
328
328
 
329
329
  function buildNativeFromSource() {
330
330
  const crate = path.join(ROOT, 'nativesrc', 'jsql-neo-native');
331
- if (!fs.existsSync(path.join(crate, 'Cargo.toml'))) return;
331
+ if (!fs.existsSync(path.join(crate, 'Cargo.toml'))) {
332
+ throw new Error(`native source crate not found at ${crate}; cannot build from source`);
333
+ }
332
334
  console.log('[jsql-neo] building native module from source...');
333
335
  try {
334
336
  execSync('cargo build --release', { cwd: crate, stdio: 'inherit' });
@@ -338,14 +340,24 @@ function buildNativeFromSource() {
338
340
  : process.platform === 'darwin'
339
341
  ? path.join(rel, 'libjsql_neo_native.dylib')
340
342
  : path.join(rel, 'libjsql_neo_native.so');
341
- if (fs.existsSync(src)) {
342
- fs.mkdirSync(path.dirname(NATIVE_PATH), { recursive: true });
343
- fs.copyFileSync(src, NATIVE_PATH);
344
- fs.chmodSync(NATIVE_PATH, 0o755);
345
- console.log(`[jsql-neo] native module built: native/jsql-neo-native.node`);
346
- }
343
+ if (!fs.existsSync(src)) throw new Error(`cargo build produced no module at ${src}`);
344
+ fs.mkdirSync(path.dirname(NATIVE_PATH), { recursive: true });
345
+ fs.copyFileSync(src, NATIVE_PATH);
346
+ fs.chmodSync(NATIVE_PATH, 0o755);
347
+ console.log(`[jsql-neo] native module built: native/jsql-neo-native.node`);
348
+ } catch (e) {
349
+ throw new Error(`native source build failed: ${e.message}`);
350
+ }
351
+ }
352
+
353
+ // 源码编译失败必须出声,但不能让 npm install 整体崩掉(WASM/JS 兜底仍可用)
354
+ function tryBuildNativeFromSource() {
355
+ try {
356
+ buildNativeFromSource();
357
+ return true;
347
358
  } catch (e) {
348
- console.warn('[jsql-neo] native build failed:', e.message);
359
+ console.warn(`[jsql-neo] ${e.message}; using WASM/JS engine.`);
360
+ return false;
349
361
  }
350
362
  }
351
363
 
@@ -529,7 +541,7 @@ async function ensureNativeNode() {
529
541
  console.log('[jsql-neo] native module ready: native/jsql-neo-native.node');
530
542
  return;
531
543
  }
532
- buildNativeFromSource();
544
+ tryBuildNativeFromSource();
533
545
  return;
534
546
  }
535
547
 
@@ -553,7 +565,7 @@ async function ensureNativeNode() {
553
565
  return;
554
566
  }
555
567
  console.warn('[jsql-neo] could not fetch a verified native module; falling back to source build / WASM.');
556
- buildNativeFromSource();
568
+ tryBuildNativeFromSource();
557
569
  }
558
570
 
559
571
  /**
@@ -655,28 +667,11 @@ function ensureServerBinary() {
655
667
  console.log(`[jsql-neo] binary ready: ${BP}`);
656
668
  return;
657
669
  }
658
-
659
- // Build from source
660
- const serverDir = path.join(ROOT, '..', 'jsql-neo-server');
661
- if (fs.existsSync(path.join(serverDir, 'Cargo.toml'))) {
662
- console.log('[jsql-neo] building Rust server from source...');
663
- try {
664
- execSync('cargo build --release', { cwd: serverDir, stdio: 'inherit' });
665
- const src = path.join(serverDir, 'target', 'release', BIN_NAME);
666
- if (fs.existsSync(src)) {
667
- fs.mkdirSync(path.join(ROOT, 'bin'), { recursive: true });
668
- fs.copyFileSync(src, BP);
669
- fs.chmodSync(BP, 0o755);
670
- console.log(`[jsql-neo] binary built: ${BP}`);
671
- return;
672
- }
673
- } catch (e) {
674
- console.warn('[jsql-neo] cargo build failed:', e.message);
675
- }
676
- }
677
-
678
- console.warn(`[jsql-neo] server binary not found at ${BP}`);
679
- console.warn('[jsql-neo] install Rust from https://rustup.rs and run: npm run build');
670
+ // HTTP 服务端二进制不随 npm release 提供,旧版本里指向的同名源码目录
671
+ // (ROOT/../jsql-neo-server)也早已不存在。这里给出明确指引而不是走死路径。
672
+ console.warn(`[jsql-neo] optional HTTP server binary not found at ${BP}`);
673
+ console.warn('[jsql-neo] It is not shipped in npm releases; use NativeJSQL (embedded engine) or run an external jsql-neo-server.');
674
+ console.warn('[jsql-neo] To build the embedded native module from source (Rust required), run: npm run build:native');
680
675
  }
681
676
 
682
677
  async function main() {
@@ -0,0 +1,86 @@
1
+ /* 回归测试:issue #118 #119 #125 #129 #130 #131 #132 #133 #134 #135 #136 */
2
+ const path = require('path');
3
+ const ROOT = path.join(__dirname, '..');
4
+ const { executeSQL, tokenize } = require(path.join(ROOT, 'lib', 'sql.js'));
5
+
6
+ let pass = 0, fail = 0;
7
+ function ok(name, cond, got) {
8
+ if (cond) { pass++; console.log('[OK] ' + name); }
9
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
10
+ }
11
+
12
+ const engine = {
13
+ hasTable: () => true,
14
+ truncate: async () => {},
15
+ flush: async () => {},
16
+ find: async () => [],
17
+ getTableSchema: async () => ({}),
18
+ };
19
+ async function q(sql) {
20
+ const r = await executeSQL(engine, sql, { safety: false });
21
+ return r.rows[0][0];
22
+ }
23
+
24
+ (async () => {
25
+ // #118: 0b 二进制整数字面量
26
+ const toks = tokenize('0b1010');
27
+ ok('#118 tokenize 0b1010 为单个 number token', toks[0].type === 'number' && toks[0].value === 10 && toks[1].type === 'eof', toks);
28
+ ok('#118 SELECT 0b1010', await q('SELECT 0b1010') === 10);
29
+ ok('#118 SELECT 0b1111', await q('SELECT 0b1111') === 15);
30
+ ok('#118 SELECT 0b1010+0', await q('SELECT 0b1010+0') === 10);
31
+
32
+ // #119: BINARY / CAST AS BINARY 让 LIKE / REGEXP 大小写敏感
33
+ ok('#119 BINARY = 仍大小写敏感', await q("SELECT BINARY 'abc' = 'ABC'") === 0);
34
+ ok('#119 BINARY LIKE 大小写敏感', await q("SELECT BINARY 'abc' LIKE 'ABC'") === 0);
35
+ ok('#119 BINARY LIKE 反向', await q("SELECT BINARY 'ABC' LIKE 'abc'") === 0);
36
+ ok('#119 BINARY REGEXP 大小写敏感', await q("SELECT BINARY 'a' REGEXP 'A'") === 0);
37
+ ok('#119 CAST AS BINARY LIKE', await q("SELECT CAST('abc' AS BINARY) LIKE 'ABC'") === 0);
38
+ ok('#119 普通 LIKE 仍不敏感', await q("SELECT 'abc' LIKE 'ABC'") === 1);
39
+
40
+ // #125: PI()
41
+ ok('#125 PI()', Math.abs(await q('SELECT PI()') - Math.PI) < 1e-12);
42
+
43
+ // #129: TIMESTAMPDIFF 负差值向零截断
44
+ ok('#129 YEAR 官方示例', await q("SELECT TIMESTAMPDIFF(YEAR,'2002-05-01','2001-01-01')") === -1);
45
+ ok('#129 DAY', await q("SELECT TIMESTAMPDIFF(DAY,'2024-01-02 12:00:00','2024-01-01 00:00:00')") === -1);
46
+ ok('#129 HOUR', await q("SELECT TIMESTAMPDIFF(HOUR,'2024-01-01 01:30:00','2024-01-01 00:00:00')") === -1);
47
+ ok('#129 正差值不变', await q("SELECT TIMESTAMPDIFF(YEAR,'2001-01-01','2002-05-01')") === 1);
48
+
49
+ // #130: MAKEDATE dayofyear<=0 返回 NULL
50
+ ok('#130 MAKEDATE(y,0)', await q('SELECT MAKEDATE(2011,0)') === null);
51
+ ok('#130 MAKEDATE(y,-1)', await q('SELECT MAKEDATE(2024,-1)') === null);
52
+
53
+ // #131: MOD(bigint, 小数)
54
+ ok('#131 MOD(bigint,0.5)', await q('SELECT MOD(9007199254740993,0.5)') === 0);
55
+ ok('#131 MOD(bigint,2.5)', await q('SELECT MOD(9007199254740993,2.5)') === 0.5);
56
+
57
+ // #132: NULLIF 跨类型等值
58
+ ok('#132 NULLIF(1,1)', await q("SELECT NULLIF(1,'1')") === null);
59
+ ok("#132 NULLIF('1',1)", await q("SELECT NULLIF('1',1)") === null);
60
+ ok('#132 NULLIF(1,2) 不相等保留原值', await q('SELECT NULLIF(1,2)') === 1);
61
+
62
+ // #133: STR_TO_DATE 非法日历日期
63
+ ok('#133 2024-02-30', await q("SELECT STR_TO_DATE('2024-02-30','%Y-%m-%d')") === null);
64
+ ok('#133 2024-13-01', await q("SELECT STR_TO_DATE('2024-13-01','%Y-%m-%d')") === null);
65
+ ok('#133 13:00 PM', await q("SELECT STR_TO_DATE('13:00 PM','%h:%i %p')") === null);
66
+ ok('#133 合法日期仍可解析', await q("SELECT STR_TO_DATE('2024-02-29','%Y-%m-%d')") === '2024-02-29');
67
+
68
+ // #134: TRUNCATE/ROUND BigInt 第二参数
69
+ ok('#134 TRUNCATE(bigint,-2)', await q('SELECT TRUNCATE(9007199254740993,-2)') === '9007199254740900');
70
+ ok('#134 ROUND(bigint,-2)', await q('SELECT ROUND(9007199254740993,-2)') === '9007199254741000');
71
+ ok('#134 TRUNCATE(number,-2)', await q('SELECT TRUNCATE(123456789,-2)') === 123456700);
72
+
73
+ // #135: CONV 负数按 64 位补码
74
+ ok('#135 CONV(-1,10,2)', await q('SELECT CONV(-1,10,2)') === '1'.repeat(64));
75
+ ok('#135 CONV(-10,10,16)', await q('SELECT CONV(-10,10,16)') === 'FFFFFFFFFFFFFFF6');
76
+ ok('#135 CONV(255,10,16)', await q('SELECT CONV(255,10,16)') === 'FF');
77
+
78
+ // #136: TRIM 省略 remstr
79
+ ok('#136 TRIM(LEADING FROM)', await q("SELECT TRIM(LEADING FROM ' x ')") === 'x ');
80
+ ok('#136 TRIM(TRAILING FROM)', await q("SELECT TRIM(TRAILING FROM ' x ')") === ' x');
81
+ ok('#136 TRIM(BOTH FROM)', await q("SELECT TRIM(BOTH FROM ' x ')") === 'x');
82
+ ok('#136 TRIM(LEADING rem FROM) 仍正常', await q("SELECT TRIM(LEADING 'x' FROM 'xxxabcxxx')") === 'abcxxx');
83
+
84
+ console.log(`\n${pass} passed, ${fail} failed`);
85
+ process.exitCode = fail ? 1 : 0;
86
+ })().catch(e => { console.error(e); process.exitCode = 1; });
@@ -0,0 +1,38 @@
1
+ /* 回归测试:issue #127 live 新建大表也要挂行级 LRU(rowCache) */
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const fs = require('fs');
5
+ const ROOT = path.join(__dirname, '..');
6
+ const Database = require(path.join(ROOT, 'lib', 'database'));
7
+
8
+ let pass = 0, fail = 0;
9
+ function ok(name, cond, got) {
10
+ if (cond) { pass++; console.log('[OK] ' + name); }
11
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
12
+ }
13
+
14
+ (async () => {
15
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-issue127-'));
16
+ const db = new Database(dir, { mode: 'hybrid', flushInterval: 0 });
17
+ await db.createTable('t', {
18
+ id: { type: 'integer', primaryKey: true, autoIncrement: true },
19
+ v: { type: 'integer' },
20
+ });
21
+ const rows = [];
22
+ for (let i = 1; i <= 1500; i++) rows.push({ v: i });
23
+ await db.insertMany('t', rows);
24
+ await db.flush();
25
+
26
+ const table = db._tables['t'];
27
+ ok('#127 live 大表挂上 rowCache', !!table._rowCache);
28
+ ok('#127 数据量正确', table.find().length === 1500);
29
+ ok('#127 淘汰前可读', table.find({ v: 1234 })[0].v === 1234);
30
+
31
+ const evicted = table._evictRows(Infinity);
32
+ ok('#127 行级 LRU 可逐行淘汰', evicted === 1500, evicted);
33
+ ok('#127 淘汰后回读正确', table.find({ v: 1234 })[0].v === 1234);
34
+
35
+ await db.close();
36
+ console.log(`\n${pass} passed, ${fail} failed`);
37
+ process.exitCode = fail ? 1 : 0;
38
+ })().catch(e => { console.error(e); process.exitCode = 1; });