jsql-neo 6.7.2 → 6.7.5

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/sql.js CHANGED
@@ -490,9 +490,14 @@ function tokenize(sql) {
490
490
 
491
491
  // 聚合函数集合:这些必须走 aggregate 节点,否则会被当成逐行标量函数(返回 null 且不折叠行)
492
492
  const AGG_FUNCS = new Set(['SUM', 'AVG', 'MIN', 'MAX', 'COUNT',
493
- 'GROUP_CONCAT', 'STDDEV', 'STDDEV_POP', 'STDDEV_SAMP',
493
+ 'GROUP_CONCAT', 'STDDEV', 'STD', 'STDDEV_POP', 'STDDEV_SAMP',
494
494
  'VARIANCE', 'VAR_POP', 'VAR_SAMP', 'FIRST', 'LAST']);
495
495
 
496
+ // 方差/标准差族(Issue #114):MySQL 里无后缀的 VARIANCE / STDDEV / STD
497
+ // 都是**总体**口径(= VAR_POP / STDDEV_POP),不是样本。
498
+ const VARIANCE_FUNCS = new Set(['STDDEV', 'STD', 'STDDEV_POP', 'STDDEV_SAMP',
499
+ 'VARIANCE', 'VAR_POP', 'VAR_SAMP']);
500
+
496
501
  // 这些词会跟在表名/子查询之后,不能被误当成表别名。
497
502
  // 新增任何"跟在 FROM 之后"的子句时,都要往这里加词。
498
503
  const NOT_ALIAS_WORDS = ['JOIN', 'LEFT', 'RIGHT', 'FULL', 'WHERE', 'GROUP', 'ORDER', 'LIMIT',
@@ -2574,9 +2579,21 @@ class Parser {
2574
2579
  }
2575
2580
  column = { type: 'tuple', items: cols };
2576
2581
  } else if (this.peek().type === 'op' && this.peek().value === ',') {
2577
- // GROUP_CONCAT(expr, 'sep')
2578
- this.next();
2579
- separator = this.parseValue();
2582
+ if (VARIANCE_FUNCS.has(fn)) {
2583
+ // Issue #114:MySQL 的 VARIANCE/STDDEV/STD 只接受单个表达式,
2584
+ // 但本项目历史上接受 VARIANCE(1,2,3) 这种多参数写法,统一收集成 arglist,
2585
+ // 让每个参数值都参与统计(多参数时不再误当成 GROUP_CONCAT 的分隔符)。
2586
+ const items = [column];
2587
+ while (this.peek().type === 'op' && this.peek().value === ',') {
2588
+ this.next();
2589
+ items.push(this.parseScalar());
2590
+ }
2591
+ column = { type: 'arglist', items };
2592
+ } else {
2593
+ // GROUP_CONCAT(expr, 'sep')
2594
+ this.next();
2595
+ separator = this.parseValue();
2596
+ }
2580
2597
  }
2581
2598
  // GROUP_CONCAT(expr ORDER BY col [DESC])
2582
2599
  if (this.isKeyword('ORDER')) {
@@ -3404,9 +3421,108 @@ function mysqlNum(v) {
3404
3421
  const n = Number(m[0]);
3405
3422
  return Number.isFinite(n) ? n : 0;
3406
3423
  }
3424
+ // Issue #108:二进制值按 latin1 文本参与数字上下文(MySQL 的隐式转换)
3425
+ if (isBinaryValue(v)) return mysqlNum(v.toString());
3407
3426
  return 0;
3408
3427
  }
3409
3428
 
3429
+ // ---------------------------------------------------------------------------
3430
+ // 二进制字符串(Issue #108)
3431
+ //
3432
+ // 问题:UNHEX() 曾用 `Buffer.from(h, 'hex').toString('latin1')` 把字节塞进
3433
+ // JS 字符串,HEX()/LENGTH()/BIT_LENGTH() 再用 UTF-8 解释该字符串 —— 于是
3434
+ // 码点 0x80-0xFF 被二次编码成两个字节(UNHEX('DEADBEEF') 的 4 字节变成 8 字节,
3435
+ // HEX(UNHEX('DEADBEEF')) 变成 'C39EC2ADC2BEC3AF')。数据被静默放大,无法往返。
3436
+ //
3437
+ // 方案:UNHEX() 返回 BinaryValue(内部持有 Buffer),字节层面无损;HEX /
3438
+ // LENGTH / BIT_LENGTH / CHAR_LENGTH 识别该类型并直接按字节数/字节内容处理。
3439
+ // BinaryValue 不是字符串,但在需要文本的地方(比较、CONCAT、输出)通过
3440
+ // toString() 降级为 latin1 文本,与 MySQL「binary string 也当字符串用」一致。
3441
+ // 结果信封(rows)里仍会降级成普通字符串(见 finalizeResultBigInts),
3442
+ // 所以对外 API 与旧行为保持兼容。
3443
+ // ---------------------------------------------------------------------------
3444
+ class BinaryValue {
3445
+ constructor(buf) {
3446
+ this.bytes = Buffer.isBuffer(buf) ? Buffer.from(buf) : Buffer.from(String(buf), 'latin1');
3447
+ }
3448
+ /** 字节数(MySQL 的 LENGTH / CHAR_LENGTH 对二进制串都按字节计) */
3449
+ get length() { return this.bytes.length; }
3450
+ toString() { return this.bytes.toString('latin1'); }
3451
+ valueOf() { return this.bytes.toString('latin1'); }
3452
+ toJSON() { return this.bytes.toString('latin1'); }
3453
+ [Symbol.toPrimitive]() { return this.bytes.toString('latin1'); }
3454
+ }
3455
+
3456
+ function isBinaryValue(v) { return v instanceof BinaryValue; }
3457
+
3458
+ /**
3459
+ * Issue #111:按 Unicode code point 定位子串,返回 1-based 字符位置;
3460
+ * 未找到返回 0(与 MySQL LOCATE/INSTR 一致)。空子串返回 1。
3461
+ * 用 Array.from 把代理对拆成单个 code point,避免 emoji 被当成两个字符。
3462
+ */
3463
+ function codePointIndexOf(needle, haystack) {
3464
+ const hay = Array.from(String(haystack));
3465
+ 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++) {
3468
+ for (let j = 0; j < pat.length; j++) {
3469
+ if (hay[i + j] !== pat[j]) continue outer;
3470
+ }
3471
+ return i + 1;
3472
+ }
3473
+ return 0;
3474
+ }
3475
+
3476
+ /** 去重 / GROUP BY / 窗口分组用的键:二进制值按文本,其余保持原逻辑 */
3477
+ function valueKey(v) {
3478
+ if (isBinaryValue(v)) return v.toString();
3479
+ return typeof v === 'object' ? JSON.stringify(v) : String(v);
3480
+ }
3481
+
3482
+ // ---------------------------------------------------------------------------
3483
+ // 位运算(Issue #109)
3484
+ //
3485
+ // MySQL 的 `<<` / `>>`:操作数先按 64 位无符号整数处理(小数部分被丢),
3486
+ // 移位量取整数部分(`1 << 1.9` = `1 << 1` = 2)。此前用的是
3487
+ // `l * Math.pow(2, r)`,既没截断小数(1 << 1.9 = 3.73),又在大移位量下
3488
+ // 丢浮点精度(1 << 63 = 9223372036854776000)。这里全程用 BigInt 精确计算,
3489
+ // 结果超过 2^53 时保留 BigInt(由 finalizeResultBigInts 转成字符串输出)。
3490
+ // 边界与 MySQL 一致:移位量 < 0 或 >= 64 → 0;64 位溢出按无符号回绕。
3491
+ // ---------------------------------------------------------------------------
3492
+ const U64_MASK = (1n << 64n) - 1n;
3493
+ const MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);
3494
+
3495
+ /** MySQL 整数转换:小数四舍五入(远离零),负数按补码转到 64 位无符号 */
3496
+ function toUint64(v) {
3497
+ let n;
3498
+ if (typeof v === 'bigint') n = v;
3499
+ else if (typeof v === 'boolean') n = v ? 1n : 0n;
3500
+ else if (isBinaryValue(v)) n = BigInt(Math.round(mysqlNum(v.toString())));
3501
+ else {
3502
+ const x = mysqlNum(v);
3503
+ // 四舍五入且远离零:-1.5 → -2(Math.round 会得到 -1)
3504
+ n = BigInt(x >= 0 ? Math.floor(x + 0.5) : Math.ceil(x - 0.5));
3505
+ }
3506
+ return n & U64_MASK;
3507
+ }
3508
+
3509
+ /** BigInt 结果 → 对外值:安全整数范围内给 number,否则保留 BigInt(输出为字符串) */
3510
+ function fromUint64(n) {
3511
+ return n <= MAX_SAFE_BIGINT ? Number(n) : n;
3512
+ }
3513
+
3514
+ function sqlBitShift(l, r, op) {
3515
+ const a = toUint64(l);
3516
+ // 移位量只取整数部分(trunc,不是 round)—— MySQL 丢弃小数位
3517
+ const rawShift = mysqlNum(r);
3518
+ if (!Number.isFinite(rawShift)) return 0;
3519
+ const s = Math.trunc(rawShift);
3520
+ if (s < 0 || s >= 64) return 0;
3521
+ const shift = BigInt(s);
3522
+ if (op === '<<') return fromUint64((a << shift) & U64_MASK);
3523
+ return fromUint64(a >> shift);
3524
+ }
3525
+
3410
3526
  // ---------------------------------------------------------------------------
3411
3527
  // CHECK 约束(Issue #70)
3412
3528
  //
@@ -3638,8 +3754,8 @@ function resolveOperand(operand, row, ctx) {
3638
3754
  case '^': return (mysqlNum(l) | 0) ^ (mysqlNum(r) | 0);
3639
3755
  // P1-22: JavaScript 位运算只使用 32 位整数,移位量对 32 取模
3640
3756
  // 1 << 32 = 1 << 0 = 1,但 SQL 中 1 << 32 = 4294967296
3641
- case '<<': return mysqlNum(l) * Math.pow(2, mysqlNum(r));
3642
- case '>>': return Math.floor(mysqlNum(l) / Math.pow(2, mysqlNum(r)));
3757
+ // Issue #109:移位量截断为整数并用 BigInt 精确计算(见 sqlBitShift)
3758
+ case '<<': case '>>': return sqlBitShift(l, r, operand.op);
3643
3759
  }
3644
3760
  return null;
3645
3761
  }
@@ -3679,8 +3795,8 @@ function resolveOperand(operand, row, ctx) {
3679
3795
  case '&': return (mysqlNum(l) | 0) & (mysqlNum(r) | 0);
3680
3796
  case '|': return (mysqlNum(l) | 0) | (mysqlNum(r) | 0);
3681
3797
  case '^': return (mysqlNum(l) | 0) ^ (mysqlNum(r) | 0);
3682
- case '<<': return mysqlNum(l) * Math.pow(2, mysqlNum(r));
3683
- case '>>': return Math.floor(mysqlNum(l) / Math.pow(2, mysqlNum(r)));
3798
+ // Issue #109:移位量截断 + BigInt 精确计算
3799
+ case '<<': case '>>': return sqlBitShift(l, r, operand.op);
3684
3800
  default: return null;
3685
3801
  }
3686
3802
  }
@@ -4139,8 +4255,16 @@ function applyScalarFunction(fnNode, row, ctx) {
4139
4255
  // CHAR_LENGTH / CHARACTER_LENGTH 返回**字符**数。
4140
4256
  // 此前 LENGTH 返回 String#length:「héllo」得 5(应为 6)、「🚀🌟」得 4(应为 8),
4141
4257
  // 按字节计长的 varchar(n) 长度校验会被绕过;OCTET_LENGTH 则整个缺失(静默 NULL)。
4142
- case 'LENGTH': case 'OCTET_LENGTH': return args[0] == null ? null : Buffer.byteLength(String(args[0]), 'utf8');
4143
- case 'CHAR_LENGTH': case 'CHARACTER_LENGTH': return args[0] == null ? null : String(args[0]).length;
4258
+ // Issue #108:二进制值按原始字节计数,不能再走 UTF-8 编码(会被放大)
4259
+ case 'LENGTH': case 'OCTET_LENGTH':
4260
+ return args[0] == null ? null
4261
+ : (isBinaryValue(args[0]) ? args[0].bytes.length : Buffer.byteLength(String(args[0]), 'utf8'));
4262
+ case 'CHAR_LENGTH': case 'CHARACTER_LENGTH':
4263
+ // MySQL:二进制串的 CHAR_LENGTH 也等于字节数
4264
+ // Issue #111:文本按 Unicode code point 计数(Array.from 会按代理对合并),
4265
+ // 否则 '🚀' 会被算成 2(UTF-16 code unit 数)。
4266
+ return args[0] == null ? null
4267
+ : (isBinaryValue(args[0]) ? args[0].bytes.length : Array.from(String(args[0])).length);
4144
4268
  // TRIM(s) / TRIM([LEADING|TRAILING|BOTH] chars FROM s) / TRIM(s, chars)
4145
4269
  case 'TRIM': {
4146
4270
  if (args[0] == null) return null;
@@ -4422,6 +4546,8 @@ function applyScalarFunction(fnNode, row, ctx) {
4422
4546
  // MAKE_SET / EXPORT_SET / SOUNDEX 仍未实现(未在文档中承诺)。
4423
4547
  case 'BIT_LENGTH': {
4424
4548
  if (args[0] == null) return null;
4549
+ // Issue #108:二进制值按原始字节数 × 8
4550
+ if (isBinaryValue(args[0])) return args[0].bytes.length * 8;
4425
4551
  return Buffer.byteLength(String(args[0]), 'utf8') * 8;
4426
4552
  }
4427
4553
  case 'BIN': case 'OCT': {
@@ -4437,13 +4563,17 @@ function applyScalarFunction(fnNode, row, ctx) {
4437
4563
  const n = typeof v === 'bigint' ? v : BigInt(Math.trunc(v));
4438
4564
  return (n < 0n ? BigInt.asUintN(64, n) : n).toString(16).toUpperCase();
4439
4565
  }
4566
+ // Issue #108:二进制值直接按字节转十六进制,保证 HEX(UNHEX(x)) 恒等
4567
+ if (isBinaryValue(v)) return v.bytes.toString('hex').toUpperCase();
4440
4568
  return Buffer.from(String(v), 'utf8').toString('hex').toUpperCase();
4441
4569
  }
4442
4570
  case 'UNHEX': {
4443
4571
  if (args[0] == null) return null;
4444
4572
  const h = String(args[0]);
4445
4573
  if (h.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(h)) return null;
4446
- return Buffer.from(h, 'hex').toString('latin1');
4574
+ // Issue #108:返回 BinaryValue 而不是 latin1 字符串 —— 后者在 UTF-8
4575
+ // 编解码往返中会把 0x80-0xFF 摊成两字节,数据被静默放大。
4576
+ return new BinaryValue(Buffer.from(h, 'hex'));
4447
4577
  }
4448
4578
  case 'CONV': {
4449
4579
  if (args[0] == null || args[1] == null || args[2] == null) return null;
@@ -4622,25 +4752,26 @@ function applyScalarFunction(fnNode, row, ctx) {
4622
4752
  }
4623
4753
  case 'SUBSTRING': case 'SUBSTR': {
4624
4754
  if (args[0] == null) return null;
4625
- const s = String(args[0]);
4626
- const len = s.length;
4755
+ // Issue #111:按 code point 切分,避免把 emoji/增补平面字符劈成孤立代理项
4756
+ const cps = Array.from(String(args[0]));
4757
+ const len = cps.length;
4627
4758
  let start = Number(args[1]);
4628
4759
  // MySQL 语义:1-based;负数从末尾倒数;0 视为 1(MySQL 返回空串)
4629
4760
  if (start === 0) return '';
4630
4761
  if (start < 0) start = len + start + 1;
4631
4762
  if (args[2] !== undefined) {
4632
- let n = Number(args[2]);
4763
+ const n = Number(args[2]);
4633
4764
  if (n < 0) return '';
4634
- return s.substr(start - 1, n);
4765
+ return cps.slice(start - 1, start - 1 + n).join('');
4635
4766
  }
4636
- return s.substr(start - 1);
4767
+ return cps.slice(start - 1).join('');
4637
4768
  }
4638
4769
  case 'LEFT': {
4639
4770
  if (args[0] == null) return null;
4640
4771
  const n = Number(args[1]);
4641
4772
  // MySQL:长度 <= 0 返回空串(此前 slice(0, -1) 返回「去尾 1 字符」的 'ab')
4642
4773
  if (!Number.isFinite(n) || n <= 0) return '';
4643
- return String(args[0]).slice(0, Math.trunc(n));
4774
+ return Array.from(String(args[0])).slice(0, Math.trunc(n)).join('');
4644
4775
  }
4645
4776
  case 'RIGHT': {
4646
4777
  if (args[0] == null) return null;
@@ -4649,21 +4780,23 @@ function applyScalarFunction(fnNode, row, ctx) {
4649
4780
  // 所以 0 必须显式短路,不能只判 n < 0。
4650
4781
  if (!Number.isFinite(n) || n <= 0) return '';
4651
4782
  const s = String(args[0]);
4652
- return n >= s.length ? s : s.slice(s.length - n);
4783
+ const cps = Array.from(s); // Issue #111:code point 语义
4784
+ return n >= cps.length ? s : cps.slice(cps.length - n).join('');
4653
4785
  }
4654
4786
  case 'LOCATE': {
4655
4787
  if (args[0] == null || args[1] == null) return null;
4656
- const idx = String(args[1]).indexOf(String(args[0]));
4657
- return idx + 1;
4788
+ // Issue #111:按 code point 定位,返回**字符**位置(不是 UTF-16 code unit 下标)
4789
+ return codePointIndexOf(String(args[0]), String(args[1]));
4658
4790
  }
4659
4791
  case 'INSTR': {
4660
4792
  // INSTR(str, substr):参数顺序与 LOCATE(substr, str) 相反。
4661
4793
  // 此前两者共用一段代码,导致 INSTR 静默返回 0。
4662
4794
  if (args[0] == null || args[1] == null) return null;
4663
- const idx = String(args[0]).indexOf(String(args[1]));
4664
- return idx + 1;
4795
+ // Issue #111:code point 语义,返回字符位置
4796
+ return codePointIndexOf(String(args[1]), String(args[0]));
4665
4797
  }
4666
- case 'REVERSE': return args[0] == null ? null : String(args[0]).split('').reverse().join('');
4798
+ // Issue #111:code point 反转,否则代理对会被倒着拼成非法字符串('b\uDE80\uD83Da')
4799
+ case 'REVERSE': return args[0] == null ? null : Array.from(String(args[0])).reverse().join('');
4667
4800
 
4668
4801
  // ---- 以下这批此前没有实现:调用时静默返回 null(不报错),
4669
4802
  // 只有拿标准答案对照才发现。语义按 MySQL 8.0。
@@ -4720,23 +4853,31 @@ function applyScalarFunction(fnNode, row, ctx) {
4720
4853
  case 'LPAD': {
4721
4854
  if (args[0] == null || args[1] == null) return null;
4722
4855
  const s = String(args[0]);
4856
+ const cps = Array.from(s); // Issue #111:长度/截断都按 code point
4723
4857
  const n = Math.trunc(Number(args[1]));
4724
4858
  if (!Number.isFinite(n) || n < 0) return null;
4725
- if (n <= s.length) return s.slice(0, n);
4859
+ if (n <= cps.length) return cps.slice(0, n).join('');
4726
4860
  const pad = args[2] == null ? ' ' : String(args[2]);
4727
4861
  if (pad === '') return '';
4728
- const fill = pad.repeat(Math.ceil((n - s.length) / pad.length)).slice(0, n - s.length);
4862
+ const padCps = Array.from(pad);
4863
+ let fill = '';
4864
+ const need = n - cps.length;
4865
+ for (let i = 0; i < need; i++) fill += padCps[i % padCps.length];
4729
4866
  return fill + s;
4730
4867
  }
4731
4868
  case 'RPAD': {
4732
4869
  if (args[0] == null || args[1] == null) return null;
4733
4870
  const s = String(args[0]);
4871
+ const cps = Array.from(s); // Issue #111:长度/截断都按 code point
4734
4872
  const n = Math.trunc(Number(args[1]));
4735
4873
  if (!Number.isFinite(n) || n < 0) return null;
4736
- if (n <= s.length) return s.slice(0, n);
4874
+ if (n <= cps.length) return cps.slice(0, n).join('');
4737
4875
  const pad = args[2] == null ? ' ' : String(args[2]);
4738
4876
  if (pad === '') return '';
4739
- const fill = pad.repeat(Math.ceil((n - s.length) / pad.length)).slice(0, n - s.length);
4877
+ const padCps = Array.from(pad);
4878
+ let fill = '';
4879
+ const need = n - cps.length;
4880
+ for (let i = 0; i < need; i++) fill += padCps[i % padCps.length];
4740
4881
  return s + fill;
4741
4882
  }
4742
4883
  case 'RAND': return args.length > 0 && args[0] != null ? seedRand(Number(args[0]))() : Math.random();
@@ -5431,11 +5572,16 @@ function strictNumeric(v) {
5431
5572
  // MySQL 默认 collation(utf8mb4_general_ci)下字符串比较不区分大小写,
5432
5573
  // 与 LIKE 保持一致。cs=true 表示显式 BINARY/COLLATE 强制大小写敏感。
5433
5574
  function ciEq(a, b, cs) {
5575
+ // Issue #108:二进制值先降级为 latin1 文本再比较(MySQL 允许 binary 与文本互比)
5576
+ if (isBinaryValue(a)) a = a.toString();
5577
+ if (isBinaryValue(b)) b = b.toString();
5434
5578
  if (cs) return a === b;
5435
5579
  if (typeof a === 'string' && typeof b === 'string') return a.toLowerCase() === b.toLowerCase();
5436
5580
  return String(a) === String(b);
5437
5581
  }
5438
5582
  function ciCompare(a, b, cs) {
5583
+ if (isBinaryValue(a)) a = a.toString();
5584
+ if (isBinaryValue(b)) b = b.toString();
5439
5585
  if (cs) return a === b ? 0 : (a < b ? -1 : 1);
5440
5586
  const as = String(a).toLowerCase(), bs = String(b).toLowerCase();
5441
5587
  return as === bs ? 0 : (as < bs ? -1 : 1);
@@ -5449,6 +5595,8 @@ function sqlTruthy(v) {
5449
5595
  if (v === null || v === undefined) return null;
5450
5596
  if (typeof v === 'boolean') return v;
5451
5597
  if (typeof v === 'number') return v !== 0;
5598
+ // Issue #108:二进制值按文本判定真值
5599
+ if (isBinaryValue(v)) return sqlTruthy(v.toString());
5452
5600
  if (typeof v === 'string') return v !== '' && !(Number(v) === 0 && String(v).trim() !== '');
5453
5601
  return Boolean(v);
5454
5602
  }
@@ -5714,8 +5862,8 @@ function evaluateExpr(expr, row, ctx) {
5714
5862
  case '&': return (mysqlNum(l) | 0) & (mysqlNum(r) | 0);
5715
5863
  case '|': return (mysqlNum(l) | 0) | (mysqlNum(r) | 0);
5716
5864
  case '^': return (mysqlNum(l) | 0) ^ (mysqlNum(r) | 0);
5717
- case '<<': return mysqlNum(l) * Math.pow(2, mysqlNum(r));
5718
- case '>>': return Math.floor(mysqlNum(l) / Math.pow(2, mysqlNum(r)));
5865
+ // Issue #109:移位量截断 + BigInt 精确计算
5866
+ case '<<': case '>>': return sqlBitShift(l, r, expr.op);
5719
5867
  default: return null;
5720
5868
  }
5721
5869
  }
@@ -7475,16 +7623,20 @@ class SQLExecutor {
7475
7623
  const noColumn = !op || op.type === 'star';
7476
7624
  let values = noColumn
7477
7625
  ? rows.map(r => 1)
7478
- : op && op.type === 'tuple'
7479
- // COUNT(DISTINCT a, b):先把多列拼成元组再聚合
7480
- ? rows.map(r => JSON.stringify(op.items.map(it => resolveOperand(it, r, this.ctx))))
7626
+ // Issue #114:VARIANCE(1,2,3) 这类多参数写法,所有参数值都纳入统计
7627
+ : op && op.type === 'arglist'
7628
+ ? rows.flatMap(r => op.items.map(it => resolveOperand(it, r, this.ctx)))
7481
7629
  .filter(v => v !== null && v !== undefined)
7482
- : rows.map(r => resolveOperand(op, r, this.ctx)).filter(v => v !== null && v !== undefined);
7630
+ // COUNT(DISTINCT a, b):先把多列拼成元组再聚合
7631
+ : op && op.type === 'tuple'
7632
+ ? rows.map(r => JSON.stringify(op.items.map(it => resolveOperand(it, r, this.ctx))))
7633
+ .filter(v => v !== null && v !== undefined)
7634
+ : rows.map(r => resolveOperand(op, r, this.ctx)).filter(v => v !== null && v !== undefined);
7483
7635
  // COUNT(DISTINCT x) / SUM(DISTINCT x):先按值去重再聚合
7484
7636
  if (distinct) {
7485
7637
  const seen = new Set();
7486
7638
  values = values.filter(v => {
7487
- const k = typeof v === 'object' ? JSON.stringify(v) : String(v);
7639
+ const k = valueKey(v); // Issue #108:二进制值按 latin1 文本去重
7488
7640
  if (seen.has(k)) return false;
7489
7641
  seen.add(k);
7490
7642
  return true;
@@ -7588,7 +7740,7 @@ class SQLExecutor {
7588
7740
  if (distinct) {
7589
7741
  const seen = new Set();
7590
7742
  joined = joined.filter(v => {
7591
- const k = typeof v === 'object' ? JSON.stringify(v) : String(v);
7743
+ const k = valueKey(v); // Issue #108:二进制值按 latin1 文本去重
7592
7744
  if (seen.has(k)) return false;
7593
7745
  seen.add(k);
7594
7746
  return true;
@@ -7598,17 +7750,17 @@ class SQLExecutor {
7598
7750
  const sep = (separator !== undefined && separator !== null) ? String(separator) : ',';
7599
7751
  return joined.map(v => (v === null || v === undefined ? '' : String(v))).join(sep);
7600
7752
  }
7601
- // 标准差 / 方差族:_POP 为总体、_SAMP(及无后缀 VAR/STDDEV)为样本
7602
- if (fn === 'STDDEV' || fn === 'STDDEV_POP' || fn === 'STDDEV_SAMP' ||
7603
- fn === 'VARIANCE' || fn === 'VAR_POP' || fn === 'VAR_SAMP') {
7753
+ // 标准差 / 方差族:_POP 与无后缀 VARIANCE/STDDEV/STD 为总体,仅 _SAMP 为样本
7754
+ if (VARIANCE_FUNCS.has(fn)) {
7604
7755
  const nums = values.map(v => Number(v)).filter(v => Number.isFinite(v));
7605
7756
  if (nums.length === 0) return null;
7606
- const pop = (fn === 'STDDEV_POP' || fn === 'VAR_POP');
7757
+ const pop = (fn === 'STDDEV_POP' || fn === 'VAR_POP' || fn === 'VARIANCE' || fn === 'STDDEV' || fn === 'STD');
7607
7758
  const mean = nums.reduce((s, v) => s + v, 0) / nums.length;
7608
7759
  const denom = pop ? nums.length : nums.length - 1; // 样本方差用 n-1
7609
7760
  if (denom <= 0) return null;
7610
7761
  const variance = nums.reduce((s, v) => s + (v - mean) * (v - mean), 0) / denom;
7611
- return fn.indexOf('STDDEV') === 0 ? Math.sqrt(variance) : variance;
7762
+ const isStddev = (fn === 'STDDEV' || fn === 'STD' || fn === 'STDDEV_POP' || fn === 'STDDEV_SAMP');
7763
+ return isStddev ? Math.sqrt(variance) : variance;
7612
7764
  }
7613
7765
  return null;
7614
7766
  }
@@ -9503,6 +9655,7 @@ function escapeValue(value) {
9503
9655
  const p = n => String(n).padStart(2, '0');
9504
9656
  return `'${value.getUTCFullYear()}-${p(value.getUTCMonth() + 1)}-${p(value.getUTCDate())} ${p(value.getUTCHours())}:${p(value.getUTCMinutes())}:${p(value.getUTCSeconds())}'`;
9505
9657
  }
9658
+ if (isBinaryValue(value)) return "UNHEX('" + value.bytes.toString('hex').toUpperCase() + "')";
9506
9659
  if (Buffer.isBuffer(value)) return "X'" + value.toString('hex') + "'";
9507
9660
  if (Array.isArray(value)) {
9508
9661
  if (value.some(Array.isArray)) {
@@ -9755,6 +9908,8 @@ async function inferColumnTypes(engine, stmt, r) {
9755
9908
  // 保留精度且可序列化;内部运算仍走 BigInt,精度不丢。
9756
9909
  function finalizeBigInts(value, seen) {
9757
9910
  if (typeof value === 'bigint') return value.toString();
9911
+ // Issue #108:二进制值在结果信封里降级为 latin1 字符串,对外 API 形状不变
9912
+ if (isBinaryValue(value)) return value.toString();
9758
9913
  if (Array.isArray(value)) {
9759
9914
  if (!seen) seen = new Set();
9760
9915
  if (seen.has(value)) return value;
package/lib/table.js CHANGED
@@ -415,6 +415,7 @@ class Table {
415
415
  hook(data);
416
416
  }
417
417
  this._db._emitChange('insert', this._name, data);
418
+ this._db._walLogUpsert(this._name, [data]);
418
419
 
419
420
  return data;
420
421
  }
@@ -537,6 +538,7 @@ class Table {
537
538
  for (let i = 0; i < N; i++) hook(result[i]);
538
539
  }
539
540
  this._db._emitChange('insertMany', this._name, { count: N });
541
+ this._db._walLogUpsert(this._name, result);
540
542
  return result;
541
543
  }
542
544
 
@@ -648,6 +650,7 @@ class Table {
648
650
  hook(query, updates, count);
649
651
  }
650
652
  this._db._emitChange('update', this._name, { query, updates, count });
653
+ this._db._walLogUpsert(this._name, matched);
651
654
  }
652
655
  return count;
653
656
  }
@@ -690,6 +693,7 @@ class Table {
690
693
  hook({ [this._primaryKey]: id }, updates, 1);
691
694
  }
692
695
  this._db._emitChange('update', this._name, { query: { [this._primaryKey]: id }, updates, count: 1 });
696
+ this._db._walLogUpsert(this._name, [row]);
693
697
  return 1;
694
698
  }
695
699
 
@@ -754,6 +758,7 @@ class Table {
754
758
  hook(query, count);
755
759
  }
756
760
  this._db._emitChange('remove', this._name, { query, count });
761
+ this._db._walLogRemove(this._name, toRemove);
757
762
  }
758
763
  return count;
759
764
  }
@@ -815,6 +820,7 @@ class Table {
815
820
  hook({ [this._primaryKey]: id }, 1);
816
821
  }
817
822
  this._db._emitChange('remove', this._name, { query: { [this._primaryKey]: id }, count: 1 });
823
+ this._db._walLogRemove(this._name, [row]);
818
824
  return 1;
819
825
  }
820
826
 
@@ -839,6 +845,7 @@ class Table {
839
845
  hook(query, count);
840
846
  }
841
847
  this._db._emitChange('remove', this._name, { query, count, soft: true });
848
+ this._db._walLogUpsert(this._name, matched);
842
849
  }
843
850
  return count;
844
851
  }
@@ -884,6 +891,7 @@ class Table {
884
891
  // P1-13: truncate 不应重置软删除模式——保留原值
885
892
  this._dirty = true;
886
893
  this._db._markDirty(this._name);
894
+ this._db._walLogReplaceTable(this._name);
887
895
  return count;
888
896
  }
889
897
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.7.2",
3
+ "version": "6.7.5",
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",
package/postinstall.js CHANGED
@@ -30,18 +30,18 @@ const NATIVE_PATH = process.env.JSQL_NATIVE_PATH
30
30
  ? path.resolve(process.env.JSQL_NATIVE_PATH)
31
31
  : path.join(ROOT, 'native', 'jsql-neo-native.node');
32
32
 
33
- // GitHub 加速代理前缀(可选)。加速站的用法是把原始 URL 直接拼在后面:
33
+ // GitHub 加速代理前缀(可选,默认关闭)。加速站的用法是把原始 URL 直接拼在后面:
34
34
  // https://<host>/https://github.com/owner/repo/releases/download/vX.Y.Z/asset
35
- // 鉴权走 `Authorization: Bearer <token>` 请求头(Worker 从该头读取,不读 ?token=)。
36
- // 前缀必须显式设置 JSQL_GHPROXY(逗号分隔多个,按序回退;'' 表示直连);
37
- // token 只能从环境变量 JSQL_GHPROXY_TOKEN 读取,代码内不再内置任何 token。
35
+ // 启用方式:显式设置 JSQL_GHPROXY(逗号分隔多个,按序回退;空/未设置 = 只直连)。
36
+ // token(可选)只从 JSQL_GHPROXY_TOKEN 读取,并以 `Authorization: Bearer <token>`
37
+ // 请求头发给 **JSQL_GHPROXY 里列出的代理主机** —— 直连 github.com 时不发送;
38
+ // 跨源重定向时也会丢弃该请求头(见 download/fetchText 的 sameOrigin 判断)。
38
39
  //
39
- // 供应链安全(issue #25):已移除内置 de5.net 加速站与硬编码 token。这里只内置
40
- // 「不需要 token 的公共加速站」,且所有代理下载仍强制通过 SHA256SUMS 校验,
41
- // 因此第三方端点被投毒也装不进去(校验不通过即回退到下一个候选/直连)。
42
- // gh-proxy.com 实测:v6.5.32 资产 SHA256 与官方 SHA256SUMS 完全一致,且为合法 ELF。
43
- // 优先级:JSQL_GHPROXY(用户显式)→ 内置公共加速站 → 直连 github.com。
44
- const DEFAULT_PROXIES = ['https://gh-proxy.com/'];
40
+ // 供应链安全(issue #25 / #110):代码内不内置任何加速站,也不内置任何 token。
41
+ // 原生下载只走两条路:官方 GitHub Release 主机(直连),或用户自己显式配置的
42
+ // JSQL_GHPROXY 代理;两者都必须通过 SHA256SUMS 校验(fail closed),
43
+ // 因此就算第三方代理被投毒也装不进去。
44
+ // 优先级:JSQL_GHPROXY(用户显式)→ 直连 github.com。
45
45
  const GHPROXY = process.env.JSQL_GHPROXY !== undefined
46
46
  ? process.env.JSQL_GHPROXY
47
47
  : '';
@@ -61,7 +61,8 @@ const GHPROXY_TOKEN = process.env.JSQL_GHPROXY_TOKEN || '';
61
61
  // JSQL_NATIVE_TAG=vX.Y.Z|latest 指定远端 tag;默认 v<package.version>
62
62
  // JSQL_AUTO_DOWNLOAD_NATIVE=1 / JSQL_NATIVE_DOWNLOAD=1 仍然兼容(显式开)
63
63
  //
64
- // 供应链安全(issue #25):不内置任何加速站/token,代理仍需显式 JSQL_GHPROXY,
64
+ // 供应链安全(issue #25 / #110):不内置任何加速站/token —— 代理只能由用户
65
+ // 显式 JSQL_GHPROXY 指定,未设置时只直连官方 GitHub Release 主机;
65
66
  // 且下载必须通过 SHA256SUMS 校验(除非用户显式 JSQL_ALLOW_UNVERIFIED_NATIVE=1)。
66
67
  const DOWNLOAD_DISABLED = isOffline()
67
68
  || process.env.JSQL_NO_NATIVE_DOWNLOAD === '1'
@@ -81,14 +82,14 @@ function proxyHeaders() {
81
82
 
82
83
  /**
83
84
  * 生成候选下载地址列表(按优先级):
84
- * JSQL_GHPROXY 指定的代理 → 内置加速站 → 直连
85
+ * JSQL_GHPROXY 指定的代理(用户显式)→ 直连官方 github.com
86
+ * 没有内置的第三方加速站;JSQL_GHPROXY 为空时列表里只有直连一项。
85
87
  */
86
88
  function proxyCandidates(raw) {
87
89
  const bases = String(GHPROXY || '')
88
90
  .split(',')
89
91
  .map((s) => s.trim())
90
92
  .filter(Boolean)
91
- .concat(DEFAULT_PROXIES)
92
93
  .concat('');
93
94
  const list = [];
94
95
  for (const base of bases) {
@@ -464,12 +465,12 @@ async function downloadAndVerify(opts = {}) {
464
465
  console.warn('[jsql-neo] WARNING: JSQL_ALLOW_UNVERIFIED_NATIVE=1 — native module integrity is NOT verified.');
465
466
  }
466
467
 
467
- // 依次尝试:环境变量指定的代理 → 内置加速站 → 直连
468
+ // 依次尝试:JSQL_GHPROXY 显式指定的代理 → 直连官方 GitHub Release 主机
468
469
  for (const cand of proxyCandidates(raw)) {
469
470
  console.log(`[jsql-neo] fetching native module (${tag}): ${cand.url}`);
470
471
  const tmp = `${NATIVE_PATH}.${process.pid}.download`;
471
472
  try {
472
- // 加速站鉴权走 Authorization 头,直连时不带
473
+ // 代理鉴权(JSQL_GHPROXY_TOKEN)走 Authorization 头,且只发给代理主机;直连时不带
473
474
  await download(cand.url, tmp, cand.viaProxy ? proxyHeaders() : undefined);
474
475
  if (expected) {
475
476
  const actual = sha256File(tmp);
@@ -152,7 +152,8 @@ console.warn = () => {};
152
152
  ok('LENGTH 是字节数(é = 2 字节)', (await one("SELECT LENGTH('héllo')")) === 6);
153
153
  ok('LENGTH 是字节数(emoji 4 字节 ×2)', (await one("SELECT LENGTH('🚀🌟')")) === 8);
154
154
  ok('CHAR_LENGTH 是字符数', (await one("SELECT CHAR_LENGTH('héllo')")) === 5);
155
- ok('CHARACTER_LENGTH 是字符数', (await one("SELECT CHARACTER_LENGTH('🚀🌟')")) === 4);
155
+ // Issue #111:字符数按 Unicode code point 计(🚀🌟 是 2 个字符,不是 4 个 UTF-16 code unit)
156
+ ok('CHARACTER_LENGTH 是字符数', (await one("SELECT CHARACTER_LENGTH('🚀🌟')")) === 2);
156
157
  ok('OCTET_LENGTH 已实现(= LENGTH)', (await one("SELECT OCTET_LENGTH('中文')")) === 6);
157
158
  ok('LENGTH(NULL) = NULL', (await one('SELECT LENGTH(NULL)')) === null);
158
159
  ok('OCTET_LENGTH(NULL) = NULL', (await one('SELECT OCTET_LENGTH(NULL)')) === null);
@@ -167,10 +167,11 @@ test('Unicode é:LENGTH 为字节数(6),CHAR_LENGTH 为字符数(5)'
167
167
  assert.strictEqual(await one(q, "SELECT UPPER('café')"), 'CAFÉ');
168
168
  });
169
169
 
170
- test('Emoji 按 UTF-8 字节计数(LENGTH=8, CHAR_LENGTH=4)', async () => {
170
+ test('Emoji 按 UTF-8 字节计数(LENGTH=8, CHAR_LENGTH=2)', async () => {
171
171
  const { q } = makeDb();
172
172
  assert.strictEqual(await one(q, "SELECT LENGTH('🚀🌟')"), 8);
173
- assert.strictEqual(await one(q, "SELECT CHAR_LENGTH('🚀🌟')"), 4);
173
+ // Issue #111:CHAR_LENGTH 按 code point 计,两个 emoji = 2 个字符
174
+ assert.strictEqual(await one(q, "SELECT CHAR_LENGTH('🚀🌟')"), 2);
174
175
  });
175
176
 
176
177
  test('Emoji UPPER 无变化', async () => {