jsql-neo 6.8.15 → 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.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  > **One engine to rule them all** — a Rust-powered embedded database that speaks your language:
4
4
  > MySQL, PostgreSQL, MongoDB, Redis, SQL, TypeScript, **and the browser**.
5
5
 
6
- > **v6.8.15** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
6
+ > **v6.8.16** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
7
7
 
8
8
  ![Engines](https://img.shields.io/badge/engines-Native%20%7C%20WASM%20%7C%20Pure%20JS-7ee787)
9
9
  ![MySQL](https://img.shields.io/badge/protocol-MySQL%20compatible-1f6feb)
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.8.15 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.8.16 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
@@ -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();
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.15",
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 && node test/issue-259-264.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 && node test/issue-259-264.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
+ });
@@ -84,9 +84,12 @@ async function testApi() {
84
84
  ok('#38 API filter with BigInt matches', hit.length === 1 && hit[0].id === r1.id, hit);
85
85
 
86
86
  // 8. 非法值仍然报错
87
- threw = null;
88
- try { t.insert({ v: 1.5 }); } catch (e) { threw = e; }
89
- ok('#38 API float into bigint column throws 1292', threw && codeOf(threw) === 1292);
87
+ // #270:MySQL 向整型列写带小数部分的值是**四舍五入**而不是报错
88
+ // (1.5 → 2)。这里改为验证舍入结果;布尔仍是非法值。
89
+ let floatRow = null;
90
+ try { floatRow = t.insert({ v: 1.5 }); } catch (e) { floatRow = null; }
91
+ ok('#38 API float into bigint column rounds half away from zero',
92
+ floatRow && Number(floatRow.v) === 2, floatRow);
90
93
  threw = null;
91
94
  try { t.insert({ v: true }); } catch (e) { threw = e; }
92
95
  ok('#38 API boolean into bigint column throws 1292', threw && codeOf(threw) === 1292);
@@ -258,8 +261,10 @@ async function testNoRegression() {
258
261
  const rows = db.t.find({});
259
262
  ok('#38 regression integer/float/string coercion intact',
260
263
  rows.length === 2 && rows[0].n === 42 && rows[1].n === 43 && rows[1].f === 2.5 && rows[1].s === '7', rows);
261
- ok('#38 regression integer still rejects 1.5', (() => {
262
- try { db.t.insert({ n: 1.5 }); return false; } catch (e) { return codeOf(e) === 1292; }
264
+ // #270:MySQL 语义 —— 整数列对带小数部分的值做四舍五入(1.5 → 2),
265
+ // 不再报 1292。
266
+ ok('#38 regression integer rounds 1.5 to 2', (() => {
267
+ try { const r = db.t.insert({ n: 1.5 }); return r.n === 2; } catch (e) { return false; }
263
268
  })());
264
269
  }
265
270