jsql-neo 6.8.1 → 6.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.1",
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/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/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",
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; });
@@ -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 版本比较