jsql-neo 6.8.14 → 6.8.16

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.
@@ -11,6 +11,45 @@ const SZ = {
11
11
  DATA: 4096 - 64
12
12
  };
13
13
 
14
+ // ---------------------------------------------------------------------------
15
+ // 静态加密(Issue #260)
16
+ //
17
+ // 目录模式(hybrid/disk)的 `.jsql` 数据块此前只做 gzip,明文可直接解压看到。
18
+ // `encryptKey` 只在 legacy 单文件模式生效,目录模式静默忽略密钥 —— 用户以为
19
+ // 落盘已加密,实际裸奔。
20
+ //
21
+ // 现在把目录模式的数据块也加密:
22
+ // 写:原始行字节 → gzip → AES-256-CBC 加密 → 落盘
23
+ // 读:落盘字节 → AES-256-CBC 解密 → gunzip
24
+ //
25
+ // 布局:块头 [49] = 加密标记(0 未加密 / 1 已加密);
26
+ // 密文区 = IV(16 字节) + 密文本体。
27
+ // IV 每次随机生成,随密文一起落盘。
28
+ // ---------------------------------------------------------------------------
29
+
30
+ /** 由用户密钥派生 32 字节 AES-256 密钥(scrypt,固定 salt 以便同一密钥可重复解密)。 */
31
+ function deriveAesKey(encryptKey) {
32
+ const raw = Buffer.from(String(encryptKey), 'utf8');
33
+ return crypto.scryptSync(raw, Buffer.from('jsql-neo-static-encryption-v1', 'utf8'), 32);
34
+ }
35
+
36
+ /** 加密一段数据,返回 IV(16) + 密文。 */
37
+ function encryptBlock(data, key) {
38
+ const iv = crypto.randomBytes(16);
39
+ const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
40
+ const enc = Buffer.concat([cipher.update(data), cipher.final()]);
41
+ return Buffer.concat([iv, enc]);
42
+ }
43
+
44
+ /** 解密 IV(16) + 密文。 */
45
+ function decryptBlock(payload, key) {
46
+ if (payload.length < 16) throw new Error('encrypted block too short');
47
+ const iv = payload.subarray(0, 16);
48
+ const body = payload.subarray(16);
49
+ const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
50
+ return Buffer.concat([decipher.update(body), decipher.final()]);
51
+ }
52
+
14
53
  const BT = { FREE: 0, DATA: 1, IDX: 2 };
15
54
 
16
55
  const TYPE = { NUL:0, BOL:1, I32:2, F64:3, STR:4, BUF:5, ARR:6, OBJ:7, I64:8, DATE:9, OID:10 };
@@ -177,7 +216,7 @@ function verifyHash(buf) {
177
216
  }
178
217
 
179
218
  class JSQLFormat {
180
- constructor(path) {
219
+ constructor(path, encryptKey) {
181
220
  this.path = path;
182
221
  this.fd = null;
183
222
  this.tables = new Map();
@@ -186,6 +225,37 @@ class JSQLFormat {
186
225
  this.dirty = false;
187
226
  this.open = false;
188
227
  this._nextTableId = 1;
228
+ // #260:目录模式的静态加密密钥(未提供则为 null,即不加密)
229
+ this._encryptKey = encryptKey ? deriveAesKey(encryptKey) : null;
230
+ }
231
+
232
+ /** 块头 [49] 加密标记 */
233
+ static get ENC_FLAG_OFF() { return 49; }
234
+
235
+ /**
236
+ * 把块内载荷编码成落盘字节:gzip → (可选)加密。
237
+ * 返回 { payload, compLen, encFlag }
238
+ */
239
+ _encodeBlockPayload(raw) {
240
+ const comp = zlib.gzipSync(raw, { level: 1 });
241
+ if (!this._encryptKey) {
242
+ return { payload: comp, compLen: comp.length, encFlag: 0 };
243
+ }
244
+ const payload = encryptBlock(comp, this._encryptKey);
245
+ return { payload, compLen: payload.length, encFlag: 1 };
246
+ }
247
+
248
+ /**
249
+ * 解析块内载荷: (可选)解密 → gunzip。
250
+ */
251
+ _decodeBlockPayload(buf) {
252
+ const compFlag = buf[48];
253
+ const encFlag = buf[JSQLFormat.ENC_FLAG_OFF];
254
+ const dataLen = compFlag ? buf.readUInt32LE(44) : buf.readUInt32LE(40);
255
+ let payload = buf.slice(SZ.HEADER, SZ.HEADER + dataLen);
256
+ if (encFlag) payload = decryptBlock(payload, this._encryptKey);
257
+ if (!compFlag) return payload;
258
+ return zlib.gunzipSync(payload);
189
259
  }
190
260
 
191
261
  _open() {
@@ -426,13 +496,15 @@ class JSQLFormat {
426
496
  // Compress and write blocks
427
497
  for (let i = 0; i < p.rawBlocks.length; i++) {
428
498
  const bid = p.blockIds[i];
429
- const compBuf = zlib.gzipSync(p.rawBlocks[i], { level: 1 });
499
+ // #260:gzip 后加密(目录模式静态加密)
500
+ const { payload, compLen, encFlag } = this._encodeBlockPayload(p.rawBlocks[i]);
430
501
  const block = Buffer.alloc(SZ.BLOCK);
431
502
  mkHeader(BT.DATA, bid, p.tableId).copy(block);
432
503
  block.writeUInt32LE(p.rawBlocks[i].length, 40);
433
504
  block[48] = 1;
434
- block.writeUInt32LE(compBuf.length, 44);
435
- compBuf.copy(block, SZ.HEADER);
505
+ block[JSQLFormat.ENC_FLAG_OFF] = encFlag;
506
+ block.writeUInt32LE(compLen, 44);
507
+ payload.copy(block, SZ.HEADER);
436
508
  finalize(block);
437
509
  fs.writeSync(this.fd, block, 0, SZ.BLOCK, bid * SZ.BLOCK);
438
510
  }
@@ -519,11 +591,13 @@ class JSQLFormat {
519
591
  const bid = this._alloc();
520
592
  const buf = Buffer.alloc(SZ.BLOCK);
521
593
  mkHeader(BT.DATA, bid, t.tableId).copy(buf);
522
- const comp = zlib.gzipSync(Buffer.from(scratch.subarray(0, end)), { level: 1 });
594
+ // #260:gzip 后加密(目录模式静态加密)
595
+ const { payload, compLen, encFlag } = this._encodeBlockPayload(Buffer.from(scratch.subarray(0, end)));
523
596
  buf.writeUInt32LE(end, 40);
524
597
  buf[48] = 1;
525
- buf.writeUInt32LE(comp.length, 44);
526
- comp.copy(buf, SZ.HEADER);
598
+ buf[JSQLFormat.ENC_FLAG_OFF] = encFlag;
599
+ buf.writeUInt32LE(compLen, 44);
600
+ payload.copy(buf, SZ.HEADER);
527
601
  finalize(buf);
528
602
  fs.writeSync(this.fd, buf, 0, SZ.BLOCK, bid * SZ.BLOCK);
529
603
  t.dataBlock = bid;
@@ -569,10 +643,7 @@ class JSQLFormat {
569
643
  if (!verifyHash(buf)) {
570
644
  throw new Error(`[JSQLFormat] Table '${name}': data block ${bid} failed integrity check`);
571
645
  }
572
- const compFlag = buf[48];
573
- const raw = compFlag
574
- ? zlib.gunzipSync(buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(44)))
575
- : buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(40));
646
+ const raw = this._decodeBlockPayload(buf);
576
647
 
577
648
  let off = 0;
578
649
  while (off + 4 <= raw.length) {
@@ -625,10 +696,7 @@ class JSQLFormat {
625
696
  throw new Error(`[JSQLFormat] Table '${name}': data block ${bid} failed integrity check`);
626
697
  }
627
698
 
628
- const compFlag = buf[48];
629
- const raw = compFlag
630
- ? zlib.gunzipSync(buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(44)))
631
- : buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(40));
699
+ const raw = this._decodeBlockPayload(buf);
632
700
 
633
701
  let off = 0;
634
702
  while (off + 4 <= raw.length) {
@@ -689,15 +757,7 @@ class JSQLFormat {
689
757
  _readInBlock(blockId, off) {
690
758
  const buf = Buffer.alloc(SZ.BLOCK);
691
759
  fs.readSync(this.fd, buf, 0, SZ.BLOCK, blockId * SZ.BLOCK);
692
- const compFlag = buf[48];
693
- const compSz = buf.readUInt32LE(44);
694
- const dataSz = buf.readUInt32LE(40);
695
- let raw;
696
- if (compFlag) {
697
- raw = zlib.gunzipSync(buf.slice(SZ.HEADER, SZ.HEADER + compSz));
698
- } else {
699
- raw = buf.slice(SZ.HEADER, SZ.HEADER + dataSz);
700
- }
760
+ const raw = this._decodeBlockPayload(buf);
701
761
  const r = decRow(raw, off);
702
762
  return r.row;
703
763
  }
@@ -653,6 +653,11 @@ class MongoServer {
653
653
  const engine = await this._ensureCollection(coll, this._dbOf(doc), docs);
654
654
  const ids = [];
655
655
  const writeErrors = [];
656
+ // #255:MongoDB 的 insert 命令 ordered 选项默认 true ——
657
+ // 一旦某条文档写入失败(如 E11000 重复键),**后续文档不再插入**。
658
+ // 此前循环从头到尾没读 doc.ordered,冲突之后continue 继续插下一条,
659
+ // 导致「本应中止保护上游批次语义」的写入实际全部落库。
660
+ const ordered = doc.ordered !== false;
656
661
  for (let i = 0; i < docs.length; i++) {
657
662
  const doc2 = { ...docs[i] };
658
663
  // 检查 _id 唯一性
@@ -680,6 +685,8 @@ class MongoServer {
680
685
  keyPattern: { _id: 1 },
681
686
  keyValue: { _id: doc2._id },
682
687
  });
688
+ // #255:ordered:true 时首个写入失败即中止本批(后续文档不插入)
689
+ if (ordered) break;
683
690
  continue;
684
691
  }
685
692
  }
@@ -703,6 +710,8 @@ class MongoServer {
703
710
  keyPattern: Object.fromEntries(dupIdx.columns.map(c => [c, 1])),
704
711
  keyValue,
705
712
  });
713
+ // #255:ordered:true 时首个写入失败即中止本批
714
+ if (ordered) break;
706
715
  continue;
707
716
  }
708
717
  }
package/lib/sql.js CHANGED
@@ -934,23 +934,35 @@ class Parser {
934
934
  if (type === 'json' || type === 'jsonb') def.jsonType = true;
935
935
  if (/^(BIG)?SERIAL$/i.test(typeRaw)) { def.autoIncrement = true; def.required = true; }
936
936
 
937
- // 长度限制: TEXT(255) / VARCHAR(100) / INTEGER(11) ...
937
+ // 长度限制: TEXT(255) / VARCHAR(100) / INTEGER(11) / DECIMAL(10,2) ...
938
938
  if (this.peek().type === 'op' && this.peek().value === '(') {
939
939
  this.next();
940
940
  const lenTok = this.next();
941
941
  if (lenTok.type !== 'number') throw new Error(`Expected length after type '(', got '${lenTok.value}'`);
942
942
  const len = lenTok.value;
943
+ // #266:DECIMAL(p,s) 的两个参数语义不同 ——
944
+ // p = 总位数(precision),s = 小数位(scale)。
945
+ // 此前把 s 存进了 def.precision,而全库没有任何消费者,
946
+ // 于是列级 DECIMAL(10,2) 完全没有按标度舍入(1.005 原样存成 1.005)。
947
+ let scale = null;
943
948
  if (this.peek().type === 'op' && this.peek().value === ',') {
944
949
  this.next();
945
950
  const decTok = this.next();
946
951
  if (decTok.type !== 'number') throw new Error(`Expected precision after ',', got '${decTok.value}'`);
947
- def.precision = decTok.value;
952
+ scale = decTok.value;
948
953
  }
949
954
  this.expect('op', ')');
950
955
  if (len > 0) {
951
956
  def.length = len;
952
957
  if (mapped === 'string') def.maxLength = len;
953
958
  }
959
+ if (scale !== null) {
960
+ def.scale = scale;
961
+ // 总位数 = p;p - s 才是整数部分允许的位数
962
+ def.precision = Math.max(0, len - scale);
963
+ def.decimalPrecision = len;
964
+ def.decimalScale = scale;
965
+ }
954
966
  }
955
967
 
956
968
  while (true) {
@@ -4817,6 +4829,11 @@ function applyScalarFunction(fnNode, row, ctx) {
4817
4829
  return (a && b) ? pgAge(b, a) : null;
4818
4830
  }
4819
4831
  case 'FROM_UNIXTIME': {
4832
+ // #256:NULL 必须传播,不能当成时间戳 0。
4833
+ // JS 里 Number(null) === 0,Number(null) 又是有限数 —— 于是
4834
+ // FROM_UNIXTIME(NULL) 与 FROM_UNIXTIME(0) 输出完全一样。
4835
+ // MySQL:「If unix_timestamp or format is NULL, this function returns NULL」。
4836
+ if (args[0] == null) return null;
4820
4837
  const ts = Number(args[0]);
4821
4838
  if (!Number.isFinite(ts)) return null;
4822
4839
  const d = new Date(ts * 1000);
@@ -5386,7 +5403,12 @@ function applyScalarFunction(fnNode, row, ctx) {
5386
5403
  }
5387
5404
  case 'RAND': return args.length > 0 && args[0] != null ? seedRand(Number(args[0]))() : Math.random();
5388
5405
  case 'UNIX_TIMESTAMP': {
5389
- if (args.length > 0 && args[0] != null) {
5406
+ // #257:显式传 NULL 与「不传参」必须区分。
5407
+ // 此前 `args.length > 0 && args[0] != null` 把两者合并成同一分支,
5408
+ // UNIX_TIMESTAMP(NULL) 于是落到 Date.now() 兜底,返回执行时刻的时间戳。
5409
+ // MySQL:date 为 NULL 时返回 NULL;只有无参形式才返回当前时间戳。
5410
+ if (args.length > 0) {
5411
+ if (args[0] == null) return null;
5390
5412
  // 字符串按 UTC 基准解释(与落库值同口径),Date / 数字走绝对时刻
5391
5413
  let ms = null;
5392
5414
  if (args[0] instanceof Date) ms = args[0].getTime();
@@ -106,18 +106,24 @@ function toRows(result) {
106
106
 
107
107
  let _lastInsertId = 0;
108
108
 
109
- async function executeStatement(sql, params) {
109
+ async function executeStatement(sql, params, extraOpts) {
110
110
  if (params && typeof params === 'object' && !Array.isArray(params)) {
111
111
  sql = applyParams(sql, params);
112
112
  params = null;
113
113
  }
114
114
  const result = await executeSQL(db, sql, params, {
115
+ // #264:better-sqlite3 的 db.exec() 设计上就是执行一条或多条 SQL
116
+ // (常用于跑建表脚本 / BEGIN;…;COMMIT;)。sqlite 兼容层的 exec 必须
117
+ // 走 allowStacked —— 否则迁移过来的多语句脚本直接被安全策略拦掉。
118
+ // prepare()/run()/get()/all() 等单语句路径保持拦截(allowStacked 为 false)。
119
+ allowStacked: false,
115
120
  session: {
116
121
  get lastInsertId() { return _lastInsertId; },
117
122
  set lastInsertId(v) { _lastInsertId = Number(v); },
118
123
  },
119
124
  functions: userFunctions,
120
125
  aggregates: userAggregates,
126
+ ...(extraOpts || {}),
121
127
  });
122
128
  if (result && result.type === 'insert' && result.insertId !== null && result.insertId !== undefined) {
123
129
  _lastInsertId = Number(result.insertId);
@@ -157,7 +163,8 @@ async function handleOp(op, args) {
157
163
  break;
158
164
  }
159
165
  case 'exec': {
160
- result = await executeStatement(args[0], args[1]);
166
+ // #264:exec 固定允许堆叠多语句(better-sqlite3 语义)
167
+ result = await executeStatement(args[0], args[1], { allowStacked: true });
161
168
  break;
162
169
  }
163
170
  case 'run': {
package/lib/table.js CHANGED
@@ -2210,11 +2210,18 @@ class Table {
2210
2210
  // 显式 BigInt:>2^53 也能精确保存(Issue #38)。
2211
2211
  result[field] = normalizeInteger(v, t);
2212
2212
  } else if (typeof v === 'number') {
2213
- if (!Number.isInteger(v)) throw integerError(t, v);
2213
+ // #270:向整数列写带小数部分的值,MySQL 按四舍五入取整
2214
+ // (1.9 → 2、1.4 → 1;负数 -1.5 → -2,半远离零),
2215
+ // 不报错。此前直接抛 1292,导致任何来自 JSON/CSV/ORM 的
2216
+ // 小数写整型列都会失败。
2217
+ let iv = v;
2218
+ if (!Number.isInteger(iv)) {
2219
+ iv = iv < 0 ? -Math.round(-iv) : Math.round(iv);
2220
+ }
2214
2221
  // 超过 2^53-1 的 number 在调用方就已经丢失精度,不能再假装
2215
2222
  // 存进去了:明确报错,要求传 BigInt 或十进制字符串。
2216
- if (!Number.isSafeInteger(v)) throw integerError(t, v);
2217
- result[field] = v;
2223
+ if (!Number.isSafeInteger(iv)) throw integerError(t, v);
2224
+ result[field] = iv;
2218
2225
  } else if (typeof v === 'string' && DECIMAL_INT_RE.test(v.trim())) {
2219
2226
  result[field] = normalizeInteger(v.trim(), t);
2220
2227
  } else {
@@ -2229,6 +2236,15 @@ class Table {
2229
2236
  }
2230
2237
  else if (v && v.__decimalRaw) result[field] = Number(v.__decimalRaw);
2231
2238
  else throw createError('ER_TRUNCATED_WRONG_VALUE', t, v);
2239
+ // #266:DECIMAL(p,s) 的列必须按标度 s 舍入。
2240
+ // 此前 def.precision 全库没有消费者,列级 DECIMAL(10,2) 形同虚设 ——
2241
+ // 1.005 原样存成 1.005,SUM() 还会累积 IEEE754 误差。
2242
+ // 用定点十进制字符串做舍入,避免 Math.round(v * 100) 的二进制误差。
2243
+ const scale = def.decimalScale !== undefined ? def.decimalScale
2244
+ : (def.scale !== undefined ? def.scale : null);
2245
+ if (scale !== null && scale >= 0 && typeof result[field] === 'number') {
2246
+ result[field] = roundDecimalToScale(result[field], scale);
2247
+ }
2232
2248
  } else if (t === 'boolean' || t === 'bool') {
2233
2249
  if (typeof v === 'boolean') result[field] = v;
2234
2250
  else if (v === 0 || v === 1) result[field] = !!v;
@@ -2412,4 +2428,48 @@ class Table {
2412
2428
  }
2413
2429
  }
2414
2430
 
2431
+ /**
2432
+ * 把数值按小数位 scale 四舍五入(半远离零),返回 number。
2433
+ *
2434
+ * #266:DECIMAL(p,s) 列的标度必须生效。直接用
2435
+ * `Math.round(v * 10**scale) / 10**scale` 会有二进制浮点误差
2436
+ * (1.005 * 100 = 100.49999999999999 → Math.round 得 100 → 1.00,
2437
+ * 而 MySQL 的 DECIMAL(10,2) 是 1.01)。
2438
+ *
2439
+ * 这里把数字转成十进制字符串做定点运算:移位取整 → 依据被丢弃的
2440
+ * 第一位小数决定进位(>= 5 进位)→ 还原成 number。
2441
+ */
2442
+ function roundDecimalToScale(value, scale) {
2443
+ if (!Number.isFinite(value)) return value;
2444
+ const s = String(value);
2445
+ const neg = s.startsWith('-');
2446
+ const body = neg ? s.slice(1) : s;
2447
+ const dot = body.indexOf('.');
2448
+ const intPart = dot >= 0 ? body.slice(0, dot) : body;
2449
+ const fracPart = dot >= 0 ? body.slice(dot + 1) : '';
2450
+ if (!/^\d*$/.test(intPart)) return value; // 指数形式等不处理
2451
+ const keep = fracPart.slice(0, scale).padEnd(scale, '0');
2452
+ const nextDigit = fracPart.charCodeAt(scale);
2453
+ // 决定进位:被丢弃部分的第一个数字 >= '5' → 进位(半远离零)
2454
+ let roundedInt = BigInt(intPart || '0');
2455
+ const keepNum = BigInt(keep || '0');
2456
+ if (scale > 0 && (nextDigit >= 53 /* '5' */ )) {
2457
+ roundedInt = roundedInt * 10n ** BigInt(scale) + keepNum + 1n;
2458
+ } else {
2459
+ roundedInt = roundedInt * 10n ** BigInt(scale) + keepNum;
2460
+ }
2461
+ // 还原成定点字符串
2462
+ let out;
2463
+ if (scale === 0) {
2464
+ out = roundedInt.toString();
2465
+ } else {
2466
+ const digits = roundedInt.toString().padStart(scale + 1, '0');
2467
+ const ip = digits.slice(0, digits.length - scale);
2468
+ const fp = digits.slice(digits.length - scale);
2469
+ out = ip + '.' + fp;
2470
+ }
2471
+ const n = Number(out);
2472
+ return neg && n !== 0 ? -n : n;
2473
+ }
2474
+
2415
2475
  module.exports = Table;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.8.14",
3
+ "version": "6.8.16",
4
4
  "description": "JSQL-NEO — Rust-powered embedded database with WASM, REST API, B-Tree indexes, WAL, crash recovery",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -52,12 +52,12 @@
52
52
  "build:native": "node scripts/build-native.js",
53
53
  "check:release": "node scripts/check-release-metadata.js",
54
54
  "release:prep": "node scripts/release.js",
55
- "test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.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 && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js && node test/issue-301-305.test.js && node test/issue-248-252.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/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.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 && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js && node test/issue-301-305.test.js && node test/issue-248-252.test.js && node test/issue-259-264.test.js && node test/issue-255-270.test.js",
56
56
  "test:parser": "node test/sql-parser.test.js",
57
57
  "test:btree": "node test/btree.test.js",
58
58
  "test:native": "node test/native.test.js",
59
59
  "test:regress": "node test/regress-5.1.0.js",
60
- "test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.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 && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js && node test/issue-301-305.test.js && node test/issue-248-252.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/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.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 && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js && node test/issue-301-305.test.js && node test/issue-248-252.test.js && node test/issue-259-264.test.js && node test/issue-255-270.test.js",
61
61
  "test:coverage": "c8 --all --include='lib/**' --exclude='lib/web_ui.js' --reporter=text --reporter=lcov node test/coverage.js",
62
62
  "test:orms": "node examples/orms/run-all.js",
63
63
  "test:dml": "node test/dml-constraints.test.js",
@@ -0,0 +1,145 @@
1
+ /* ---- 回归:#255 / #256 / #257 / #266 / #270 ---- */
2
+ /*
3
+ * #255 Mongo insert 忽略 ordered 标志:ordered:true 遇重复键后仍继续插入后续文档。
4
+ * #256 FROM_UNIXTIME(NULL) 返回 1970-01-01 00:00:00 而非 NULL(NULL 未传播)。
5
+ * #257 UNIX_TIMESTAMP(NULL) 返回当前时间戳而非 NULL(无参分支被误用)。
6
+ * #266 列类型 DECIMAL(p,s) 的标度在写入时完全不生效。
7
+ * #270 向 INT 列写 1.9 直接抛 1292,MySQL 会四舍五入成 2。
8
+ */
9
+ const path = require('path');
10
+ const net = require('net');
11
+ const ROOT = path.join(__dirname, '..');
12
+ const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
13
+ const { createMongoServer, bsonDocument, bsonReadDocument } = require(path.join(ROOT, 'lib/mongo_server.js'));
14
+
15
+ let pass = 0, fail = 0;
16
+ function ok(name, cond, got) {
17
+ if (cond) { pass++; console.log('[OK] ' + name); }
18
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
19
+ }
20
+
21
+ function mongoOpMsg(doc) {
22
+ const p = bsonDocument(doc);
23
+ const h = Buffer.alloc(16);
24
+ h.writeInt32LE(16 + 4 + 1 + p.length, 0);
25
+ h.writeInt32LE(1, 4); h.writeInt32LE(0, 8); h.writeInt32LE(2013, 12);
26
+ return Buffer.concat([h, Buffer.alloc(4), Buffer.from([0]), p]);
27
+ }
28
+ function mongoCall(srv, doc) {
29
+ return new Promise((resolve, reject) => {
30
+ const sock = net.connect(srv._server.address().port, '127.0.0.1', () => sock.write(mongoOpMsg(doc)));
31
+ const chunks = [];
32
+ sock.on('error', reject);
33
+ sock.on('data', (c) => {
34
+ chunks.push(c);
35
+ const buf = Buffer.concat(chunks);
36
+ if (buf.length >= 16 && buf.length >= buf.readInt32LE(0)) {
37
+ try { resolve(bsonReadDocument(buf.slice(21), 0).value); }
38
+ catch (e) { reject(e); }
39
+ sock.end();
40
+ }
41
+ });
42
+ });
43
+ }
44
+
45
+ (async () => {
46
+ const db = new Database(':memory:', { autoSave: false });
47
+ const q = async (sql) => (await executeSQL(db, sql, { safety: false })).rows;
48
+ const one = async (sql) => (await q(sql))[0][0];
49
+
50
+ // ================= #255 Mongo ordered =================
51
+ {
52
+ const srv = createMongoServer({ dataDir: ':memory:' });
53
+ await new Promise((r) => srv.listen(r));
54
+ await mongoCall(srv, { insert: 'od', documents: [{ _id: 'a', v: 1 }], $db: 'test' });
55
+ const rep = await mongoCall(srv, {
56
+ insert: 'od', ordered: true,
57
+ documents: [{ _id: 'b', v: 2 }, { _id: 'a', v: 9 }, { _id: 'c', v: 3 }],
58
+ $db: 'test',
59
+ });
60
+ const all = await mongoCall(srv, { find: 'od', filter: {}, $db: 'test' });
61
+ const ids = (all.cursor.firstBatch || []).map(x => x._id);
62
+ ok('ordered:true 冲突后不再插入后续文档', ids.length === 2 && !ids.includes('c'), ids);
63
+ ok('ordered:true 回复 n 只统计实际写入数', rep.n === 1, rep.n);
64
+ ok('ordered:true 仍报告 writeErrors', rep.writeErrors && rep.writeErrors.length === 1, rep.writeErrors);
65
+
66
+ // ordered:false 应继续逐条尝试
67
+ await mongoCall(srv, { insert: 'od2', documents: [{ _id: 'x', v: 1 }], $db: 'test' });
68
+ const rep2 = await mongoCall(srv, {
69
+ insert: 'od2', ordered: false,
70
+ documents: [{ _id: 'x', v: 2 }, { _id: 'y', v: 3 }],
71
+ $db: 'test',
72
+ });
73
+ const all2 = await mongoCall(srv, { find: 'od2', filter: {}, $db: 'test' });
74
+ const ids2 = (all2.cursor.firstBatch || []).map(x => x._id);
75
+ ok('ordered:false 冲突后仍继续插入后续文档',
76
+ ids2.includes('x') && ids2.includes('y'), ids2);
77
+ // 本批 2 条:'x' 重复失败、'y' 成功 → n = 1
78
+ ok('ordered:false 回复 n 统计本批成功数', rep2.n === 1, rep2.n);
79
+ ok('ordered:false 仍报告 writeErrors',
80
+ rep2.writeErrors && rep2.writeErrors.length === 1, rep2.writeErrors);
81
+ srv.close();
82
+ }
83
+
84
+ // ================= #256 FROM_UNIXTIME NULL =================
85
+ ok('FROM_UNIXTIME(NULL) = NULL', await one('SELECT FROM_UNIXTIME(NULL)') === null, null);
86
+ ok('FROM_UNIXTIME(NULL) IS NULL 为真',
87
+ await one('SELECT FROM_UNIXTIME(NULL) IS NULL') === 1, null);
88
+ ok('FROM_UNIXTIME(0) 仍是 1970-01-01 00:00:00(不回归)',
89
+ await one('SELECT FROM_UNIXTIME(0)') === '1970-01-01 00:00:00', null);
90
+ ok('FROM_UNIXTIME(NULL, "%Y") 也是 NULL',
91
+ await one("SELECT FROM_UNIXTIME(NULL, '%Y')") === null, null);
92
+
93
+ // ================= #257 UNIX_TIMESTAMP NULL =================
94
+ ok('UNIX_TIMESTAMP(NULL) = NULL', await one('SELECT UNIX_TIMESTAMP(NULL)') === null, null);
95
+ ok('UNIX_TIMESTAMP(NULL) IS NULL 为真',
96
+ await one('SELECT UNIX_TIMESTAMP(NULL) IS NULL') === 1, null);
97
+ const nowTs = await one('SELECT UNIX_TIMESTAMP()');
98
+ ok('UNIX_TIMESTAMP() 无参仍返回当前时间戳',
99
+ typeof nowTs === 'number' && Math.abs(nowTs - Math.floor(Date.now() / 1000)) < 5, nowTs);
100
+ ok("UNIX_TIMESTAMP('1970-01-01 00:00:00') = 0(不回归)",
101
+ await one("SELECT UNIX_TIMESTAMP('1970-01-01 00:00:00')") === 0, null);
102
+
103
+ // ================= #266 DECIMAL 标度 =================
104
+ await q('CREATE TABLE dc (id INT PRIMARY KEY, d DECIMAL(10,2))');
105
+ await q('INSERT INTO dc VALUES (1, 1.005)');
106
+ await q('INSERT INTO dc VALUES (2, 123.456)');
107
+ await q('INSERT INTO dc VALUES (3, 2.675)');
108
+ const dcRows = await q('SELECT id, d FROM dc ORDER BY id');
109
+ ok('DECIMAL(10,2) 把 1.005 舍入成 1.01', dcRows[0][1] === 1.01, dcRows[0]);
110
+ ok('DECIMAL(10,2) 把 123.456 舍入成 123.46', dcRows[1][1] === 123.46, dcRows[1]);
111
+ ok('DECIMAL(10,2) 把 2.675 舍入成 2.68(半远离零,无浮点误差)', dcRows[2][1] === 2.68, dcRows[2]);
112
+ const mul = await q('SELECT d * 100 FROM dc ORDER BY id');
113
+ ok('DECIMAL 乘法无浮点误差(101 / 12346 / 268)',
114
+ JSON.stringify(mul.map(r => r[0])) === JSON.stringify([101, 12346, 268]), mul);
115
+ // 不回归:普通 number 列不受影响
116
+ await q('CREATE TABLE nf (id INT PRIMARY KEY, n FLOAT)');
117
+ await q('INSERT INTO nf VALUES (1, 1.005)');
118
+ ok('FLOAT 列不受 DECIMAL 标度影响',
119
+ (await q('SELECT n FROM nf'))[0][0] === 1.005, await q('SELECT n FROM nf'));
120
+
121
+ // ================= #270 向 INT 列写小数 =================
122
+ await q('CREATE TABLE n (id INT PRIMARY KEY, i INT)');
123
+ await q('INSERT INTO n VALUES (1, 1.9)');
124
+ await q('INSERT INTO n VALUES (2, 1.4)');
125
+ await q('INSERT INTO n VALUES (3, -1.5)');
126
+ const intRows = await q('SELECT id, i FROM n ORDER BY id');
127
+ ok('向 INT 列写 1.9 舍入成 2', intRows[0][1] === 2, intRows[0]);
128
+ ok('向 INT 列写 1.4 舍入成 1', intRows[1][1] === 1, intRows[1]);
129
+ ok('向 INT 列写 -1.5 舍入成 -2(半远离零)', intRows[2][1] === -2, intRows[2]);
130
+ // 不回归:整数值与字符串整数字面量
131
+ await q('INSERT INTO n VALUES (4, 7)');
132
+ await q("INSERT INTO n VALUES (5, '8')");
133
+ ok('整数值不回归', (await q('SELECT i FROM n WHERE id=4'))[0][0] === 7, null);
134
+ ok('整数字符串不回归', (await q('SELECT i FROM n WHERE id=5'))[0][0] === 8, null);
135
+ // 不回归:非数字字符串仍报错
136
+ let strErr = null;
137
+ try { await q("INSERT INTO n VALUES (6, 'abc')"); } catch (e) { strErr = e; }
138
+ ok('非数字字符串写 INT 列仍报 1292', !!strErr, strErr && strErr.message);
139
+
140
+ console.log(`\n${pass} passed, ${fail} failed`);
141
+ process.exit(fail === 0 ? 0 : 1);
142
+ })().catch(e => {
143
+ console.log('[FAIL] unexpected exception: ' + (e.stack || e).split('\n').slice(0, 4).join('\n'));
144
+ process.exit(1);
145
+ });