jsql-neo 6.8.7 → 6.8.9

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.7** — 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.9** — 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.7 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.8.9 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
package/lib/cache.js CHANGED
@@ -365,16 +365,25 @@ class Cache {
365
365
  } catch (_) { /* ignore */ }
366
366
  }
367
367
 
368
- _startAutoSave() { this._saveTimer = setInterval(() => { if (this._dirty) this.save(); }, this._saveInterval); }
369
- _startTTLCleaner() {
370
- this._ttlTimer = setInterval(() => {
371
- for (let i = 0; i < this._dbs.length; i++) {
372
- const exp = this._dbsExpires[i]; if (!exp) continue;
373
- const now = Date.now();
374
- for (const [key, ttl] of exp) { if (ttl <= now) { if (this._dbs[i]) this._dbs[i].delete(key); exp.delete(key); } }
375
- }
376
- }, 1000);
377
- }
368
+ // #319:两个后台定时器都必须 unref()。
369
+ // 嵌入式库被实例化后如果调用方忘记 close(),未 unref 的 setInterval 会一直
370
+ // 持有 Node 事件循环,CLI / 批处理 / 测试脚本跑完就「挂在那里」不退出,
371
+ // CI 里表现为超时被杀。与 lib/database.js 的 _flushTimer / _monitorTimer
372
+ // 保持同一套处理。
373
+ _startAutoSave() {
374
+ this._saveTimer = setInterval(() => { if (this._dirty) this.save(); }, this._saveInterval);
375
+ if (this._saveTimer && this._saveTimer.unref) this._saveTimer.unref();
376
+ }
377
+ _startTTLCleaner() {
378
+ this._ttlTimer = setInterval(() => {
379
+ for (let i = 0; i < this._dbs.length; i++) {
380
+ const exp = this._dbsExpires[i]; if (!exp) continue;
381
+ const now = Date.now();
382
+ for (const [key, ttl] of exp) { if (ttl <= now) { if (this._dbs[i]) this._dbs[i].delete(key); exp.delete(key); } }
383
+ }
384
+ }, 1000);
385
+ if (this._ttlTimer && this._ttlTimer.unref) this._ttlTimer.unref();
386
+ }
378
387
 
379
388
  close() { if (this._persistPath && this._dirty) this.save(); if (this._saveTimer) clearInterval(this._saveTimer); if (this._ttlTimer) clearInterval(this._ttlTimer); }
380
389
  _isExpired(key) {
package/lib/database.js CHANGED
@@ -2731,6 +2731,10 @@ class Database {
2731
2731
  this._autoSaveTimer = null;
2732
2732
  if (this._dirty) this.save();
2733
2733
  }, this._options.autoSaveInterval);
2734
+ // #321:legacy 文件模式的自动保存定时器也要 unref()。
2735
+ // 同文件的 _flushTimer / _monitorTimer 都已经 unref,唯独这个漏了,
2736
+ // 漏调 close() 时进程会被挂到下一次自动保存触发才退出。
2737
+ if (this._autoSaveTimer && this._autoSaveTimer.unref) this._autoSaveTimer.unref();
2734
2738
  } else {
2735
2739
  this.save();
2736
2740
  }
package/lib/migrate.js CHANGED
@@ -39,14 +39,16 @@ function normalizeSchema(schema) {
39
39
  }
40
40
 
41
41
  function serializeValue(v) {
42
- // #235:NULL 与空串必须可区分(MySQL 约定 NULL 写 \N)
42
+ // #235:NULL 与空串必须可区分(MySQL 约定 NULL 写 \N);字面量 \N 反向转义
43
43
  if (v === null || v === undefined) return '\\N';
44
+ if (v === '\\N') return '\\\\N';
44
45
  if (v instanceof Date) return v.toISOString();
45
46
  if (typeof v === 'object') return JSON.stringify(v);
46
47
  return String(v);
47
48
  }
48
49
 
49
50
  function parseValue(str, type) {
51
+ if (str === '\\\\N') return '\\N'; // 字面量 \N 的转义形式
50
52
  if (str === '\\N') return null; // #235:显式 NULL 标记
51
53
  if (str === null || str === undefined) return null;
52
54
  const t = String(type || 'string').toLowerCase();
@@ -77,6 +79,8 @@ function parseCSV(text, opts = {}) {
77
79
  if (typeof text !== 'string') {
78
80
  throw new Error('parseCSV: csv must be a string');
79
81
  }
82
+ // 带 BOM 的 UTF-8 文件:去掉 BOM,否则首列表头会变成 \uFEFFid
83
+ if (text.charCodeAt(0) === 0xFEFF) text = text.slice(1);
80
84
  const maxLen = opts.maxInputSize == null ? DEFAULT_MAX_CSV_LENGTH : opts.maxInputSize;
81
85
  if (typeof maxLen === 'number' && Number.isFinite(maxLen) && text.length > maxLen) {
82
86
  throw new Error(
@@ -1054,6 +1054,7 @@ class MongoServer {
1054
1054
  applyModifier(doc, updateDoc, { strict: true });
1055
1055
  // updateByIds 是 Object.assign 合并:被 $unset 删除的顶层字段需显式置 undefined
1056
1056
  for (const k of Object.keys(r)) if (!(k in doc)) doc[k] = undefined;
1057
+ this._checkUniqueIndexes(engine, coll, doc, r);
1057
1058
  entries.push([key, doc]);
1058
1059
  }
1059
1060
  if (entries.length > 0) {
@@ -1077,6 +1078,7 @@ class MongoServer {
1077
1078
  if (key === undefined) continue;
1078
1079
  const d = cloneDoc(replacement || {});
1079
1080
  if (r._id !== undefined) d._id = r._id;
1081
+ this._checkUniqueIndexes(engine, coll, d, r);
1080
1082
  ids.push(key);
1081
1083
  docs.push(d);
1082
1084
  }
@@ -1091,6 +1093,29 @@ class MongoServer {
1091
1093
  return out;
1092
1094
  }
1093
1095
 
1096
+ /** #221:写入/更新前按二级唯一索引查重 */
1097
+ _checkUniqueIndexes(engine, coll, doc, excludeRow) {
1098
+ let defs = [];
1099
+ for (const [key, list] of this._indexesByColl) {
1100
+ if (key.endsWith('.' + coll)) defs = defs.concat(list.filter(ix => ix.unique && ix.name !== '_id_'));
1101
+ }
1102
+ if (defs.length === 0) return;
1103
+ const table = engine && engine._tables && engine._tables[coll];
1104
+ if (!table || !Array.isArray(table._rows)) return;
1105
+ for (const ix of defs) {
1106
+ if (ix.columns.some(c => getPath(doc, c) === undefined || getPath(doc, c) === null)) continue;
1107
+ for (const row of table._rows) {
1108
+ if (row === excludeRow) continue;
1109
+ if (ix.columns.every(c => deepEqualMongo(getPath(row, c), getPath(doc, c)))) {
1110
+ const err = new Error(`E11000 duplicate key error collection: ${coll} index: ${ix.name} dup key: ${JSON.stringify(Object.fromEntries(ix.columns.map(c => [c, getPath(doc, c)])))}`);
1111
+ err.code = 11000;
1112
+ err.keyPattern = Object.fromEntries(ix.columns.map(c => [c, 1]));
1113
+ throw err;
1114
+ }
1115
+ }
1116
+ }
1117
+ }
1118
+
1094
1119
  async _removeRows(engine, coll, rows) {
1095
1120
  // 收集所有需要删除的行的 id,走 engine.removeByIds
1096
1121
  // 这样会写 WAL、触发 hooks、检查约束
package/lib/pg_server.js CHANGED
@@ -690,14 +690,14 @@ class PgConnection {
690
690
  this._send(buildReadyForQuery(this._rfqStatus()));
691
691
  return;
692
692
  }
693
- if (trimmed.startsWith('SET ')) {
694
- this._send(buildCommandComplete('SET'));
693
+ // aborted 事务里除 ROLLBACK/COMMIT 外一律拒绝(SET 也不能绕过)
694
+ if (this._txAborted && !/^(ROLLBACK|COMMIT)\b/i.test(trimmed)) {
695
+ this._send(buildErrorResponse('25P02', 'current transaction is aborted, commands ignored until end of transaction block'));
695
696
  this._send(buildReadyForQuery(this._rfqStatus()));
696
697
  return;
697
698
  }
698
- // #213:事务已 aborted 时,除 ROLLBACK/COMMIT 外的命令一律 25P02
699
- if (this._txAborted && !/^(ROLLBACK|COMMIT)\b/i.test(trimmed)) {
700
- this._send(buildErrorResponse('25P02', 'current transaction is aborted, commands ignored until end of transaction block'));
699
+ if (trimmed.startsWith('SET ')) {
700
+ this._send(buildCommandComplete('SET'));
701
701
  this._send(buildReadyForQuery(this._rfqStatus()));
702
702
  return;
703
703
  }
@@ -73,11 +73,15 @@ function globToRegex(pattern) {
73
73
  const BIN_PREFIX = '\u0001';
74
74
  function decodeBulk(buf) {
75
75
  const s = buf.toString('utf8');
76
- if (Buffer.from(s, 'utf8').equals(buf)) return s;
76
+ if (Buffer.from(s, 'utf8').equals(buf)) {
77
+ // 合法文本恰好以保留前缀开头时再加一层前缀,回包时还原
78
+ return s.startsWith(BIN_PREFIX) ? BIN_PREFIX + BIN_PREFIX + s : s;
79
+ }
77
80
  return BIN_PREFIX + buf.toString('latin1');
78
81
  }
79
82
  function bulkToBuffer(v) {
80
83
  const s = String(v);
84
+ if (s.startsWith(BIN_PREFIX + BIN_PREFIX)) return Buffer.from(s.slice(BIN_PREFIX.length * 2), 'utf8');
81
85
  if (s.startsWith(BIN_PREFIX)) return Buffer.from(s.slice(BIN_PREFIX.length), 'latin1');
82
86
  return Buffer.from(s, 'utf8');
83
87
  }
@@ -481,8 +485,11 @@ class RedisServer {
481
485
  const hasCount = args.length >= 2;
482
486
  let count = 1;
483
487
  if (hasCount) {
484
- count = parseInt(args[1], 10);
485
- if (isNaN(count) || count < 0) throw new Error('ERR value is out of range, must be positive');
488
+ // #314:count 必须是严格十进制非负整数。此前用裸 parseInt,
489
+ // '1.5' 被截成 1、'2abc' 被截成 2,尾随垃圾静默接受。
490
+ // 复用库内已有的 parseRedisInt(与 #175/#227 同口径)。
491
+ count = parseRedisInt(args[1]);
492
+ if (count < 0) throw new Error('ERR value is out of range, must be positive');
486
493
  }
487
494
  const v = this._get(args[0]);
488
495
  if (!v) return hasCount ? [] : null;
package/lib/sql.js CHANGED
@@ -5161,7 +5161,11 @@ function applyScalarFunction(fnNode, row, ctx) {
5161
5161
  // · 需要填充时 padstr **循环使用并截断**到恰好 len(LPAD('hi',5,'ab') = 'abahi')
5162
5162
  // · padstr 为空串且 len > 原长 → ''(MySQL 语义);旧 while 循环此时会死循环
5163
5163
  case 'LPAD': {
5164
+ // #318:填充串为 NULL → 整体返回 NULL(MySQL 三值逻辑)。
5165
+ // 此前只守卫 args[0]/args[1],args[2] 为 NULL 时用字面量 ' ' 兜底,
5166
+ // 产出 ' 7' 这种错误字符串。缺省第三参(args.length < 3)才用空格填充。
5164
5167
  if (args[0] == null || args[1] == null) return null;
5168
+ if (args.length > 2 && args[2] == null) return null;
5165
5169
  const s = String(args[0]);
5166
5170
  const cps = Array.from(s); // Issue #111:长度/截断都按 code point
5167
5171
  const n = Math.trunc(Number(args[1]));
@@ -5176,7 +5180,9 @@ function applyScalarFunction(fnNode, row, ctx) {
5176
5180
  return fill + s;
5177
5181
  }
5178
5182
  case 'RPAD': {
5183
+ // #318:同 LPAD,填充串为 NULL → 整体 NULL。
5179
5184
  if (args[0] == null || args[1] == null) return null;
5185
+ if (args.length > 2 && args[2] == null) return null;
5180
5186
  const s = String(args[0]);
5181
5187
  const cps = Array.from(s); // Issue #111:长度/截断都按 code point
5182
5188
  const n = Math.trunc(Number(args[1]));
@@ -6105,7 +6111,18 @@ function evaluateExpr(expr, row, ctx) {
6105
6111
  if (p === null || p === undefined) return null;
6106
6112
  // REGEXP / RLIKE 历史上就是大小写不敏感的;`~` 敏感、`~*` 不敏感
6107
6113
  const binaryCmp = isBinaryNode(expr.operand) || isBinaryNode(expr.pattern);
6108
- const re = new RegExp(String(p), (expr.ci === false || binaryCmp) ? '' : 'i');
6114
+ // #317:非法正则模式串原来直接抛 V8 的裸 SyntaxError(无 errno/SQLSTATE),
6115
+ // 跨协议透传时客户端无法按 MySQL 错误码处理。归一为 ER_REGEXP_ERROR(1139)。
6116
+ let re;
6117
+ try {
6118
+ re = new RegExp(String(p), (expr.ci === false || binaryCmp) ? '' : 'i');
6119
+ } catch (e) {
6120
+ const err = new Error('Illegal argument to a regular expression');
6121
+ err.code = 'ER_REGEXP_ERROR';
6122
+ err.errno = 1139;
6123
+ err.sqlState = '42000';
6124
+ throw err;
6125
+ }
6109
6126
  const r = re.test(String(v));
6110
6127
  return expr.not ? !r : r;
6111
6128
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.8.7",
3
+ "version": "6.8.9",
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",
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",
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",
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",
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",
@@ -39,6 +39,85 @@ function ok(name, cond, extra) {
39
39
  c.close();
40
40
  }
41
41
 
42
+ // CSV literal \\N must not collapse to NULL
43
+ {
44
+ const fs = require('fs');
45
+ const os = require('os');
46
+ const { Database, migrate } = require(path.join(ROOT, 'index.js'));
47
+ const db = new Database(':memory:');
48
+ await db.query('CREATE TABLE t (id INTEGER PRIMARY KEY, s TEXT)', { safety: false });
49
+ await db.query("INSERT INTO t VALUES (1,'\\\\N'),(2,NULL)", { safety: false });
50
+ const csv = await migrate.exportTableToCSV(db, 't');
51
+ const db2 = new Database(':memory:');
52
+ await db2.query('CREATE TABLE t (id INTEGER PRIMARY KEY, s TEXT)', { safety: false });
53
+ await migrate.importFromCSV(db2, 't', csv);
54
+ const r = (await db2.query('SELECT * FROM t ORDER BY id', { safety: false })).rows;
55
+ ok('CSV literal \\N round-trips without becoming NULL', JSON.stringify(r) === JSON.stringify([[1, '\\N'], [2, null]]), r);
56
+ db.stop(); db2.stop();
57
+ }
58
+
59
+ // PG aborted transaction also rejects SET
60
+ {
61
+ const { Client } = (() => { try { return require(path.join(ROOT, 'node_modules', 'pg')); } catch (e) { return {}; } })();
62
+ if (Client) {
63
+ const { createPgServer } = require(path.join(ROOT, 'lib', 'pg_server.js'));
64
+ const srv = createPgServer({ port: 0, host: '127.0.0.1', dataDir: ':memory:', noAuth: true });
65
+ await new Promise((r) => srv.listen(r));
66
+ const c = new Client({ host: '127.0.0.1', port: srv.address.port, user: 'root', database: 'app' });
67
+ await c.connect();
68
+ await c.query('BEGIN');
69
+ try { await c.query('SELECT * FROM no_such_table'); } catch (e) { /* aborted */ }
70
+ let code = null;
71
+ try { await c.query('SET search_path=foo'); } catch (e) { code = e.code; }
72
+ ok('PG aborted transaction rejects SET too', code === '25P02', code);
73
+ await c.query('ROLLBACK');
74
+ await c.end(); srv.close();
75
+ } else {
76
+ console.log('[SKIP] PG aborted SET (pg not installed)');
77
+ }
78
+ }
79
+
80
+ // CSV BOM header
81
+ {
82
+ const { Database, migrate } = require(path.join(ROOT, 'index.js'));
83
+ const db = new Database(':memory:');
84
+ await db.query('CREATE TABLE t (id INTEGER PRIMARY KEY, s TEXT)', { safety: false });
85
+ await migrate.importFromCSV(db, 't', '\uFEFFid,s\n1,hi\n');
86
+ const r = (await db.query('SELECT * FROM t', { safety: false })).rows;
87
+ ok('CSV BOM header is stripped', JSON.stringify(r) === JSON.stringify([[1, 'hi']]), r);
88
+ db.stop();
89
+ }
90
+
91
+ // Redis valid text starting with the binary marker must round-trip
92
+ {
93
+ const net = require('net');
94
+ const { createRedisServer } = require(path.join(ROOT, 'lib', 'redis_server.js'));
95
+ const srv = createRedisServer({ port: 0, dataDir: null });
96
+ await new Promise((r) => srv.listen(r));
97
+ const sock = net.connect(srv.server.address().port, '127.0.0.1');
98
+ await new Promise((r) => sock.on('connect', r));
99
+ const chunks = [];
100
+ sock.on('data', (c) => chunks.push(c));
101
+ const val = Buffer.from('\u0001hello', 'utf8');
102
+ sock.write(Buffer.concat([Buffer.from('*3\r\n$3\r\nSET\r\n$1\r\nk\r\n$' + val.length + '\r\n'), val, Buffer.from('\r\n')]));
103
+ sock.write(Buffer.from('*2\r\n$3\r\nGET\r\n$1\r\nk\r\n'));
104
+ await new Promise((r) => setTimeout(r, 120));
105
+ const out = Buffer.concat(chunks);
106
+ const at = out.indexOf('$' + val.length + '\r\n');
107
+ ok('Redis leading \\u0001 text is not treated as binary', at >= 0 && out.slice(at + 3 + String(val.length).length, at + 3 + String(val.length).length + val.length).equals(val), out.toString('hex'));
108
+ sock.end(); srv.stop();
109
+ }
110
+
111
+ // Mongo unique index must also block UPDATE to a duplicate key
112
+ {
113
+ const { createMongoServer } = require(path.join(ROOT, 'lib', 'mongo_server.js'));
114
+ const mongo = createMongoServer({ dataDir: ':memory:' });
115
+ await mongo._dispatch('createIndexes', { createIndexes: 'c', indexes: [{ key: { email: 1 }, name: 'email_1', unique: true }], $db: 'test' });
116
+ await mongo._dispatch('insert', { insert: 'c', documents: [{ email: 'a@x.com' }, { email: 'b@x.com' }], $db: 'test' });
117
+ const upd = await mongo._dispatch('update', { update: 'c', updates: [{ q: { email: 'b@x.com' }, u: { $set: { email: 'a@x.com' } } }], $db: 'test' });
118
+ ok('Mongo unique index enforced on UPDATE', upd.ok === 0, upd);
119
+ }
120
+
42
121
  // #240
43
122
  {
44
123
  const db = new JSQL();
@@ -0,0 +1,162 @@
1
+ /* ---- 回归:#314 / #317 / #318 / #319 / #321 ---- */
2
+ /*
3
+ * #314 Redis LPOP/RPOP 的 count 参数用裸 parseInt —— '1.5' 被截成 1、'2abc'
4
+ * 被截成 2,尾随垃圾静默接受。改为复用 parseRedisInt(严格十进制)。
5
+ * #317 REGEXP/RLIKE 非法正则模式串抛裸 V8 SyntaxError(无 errno/SQLSTATE),
6
+ * 归一为 MySQL 的 ER_REGEXP_ERROR(1139) / SQLSTATE 42000。
7
+ * #318 LPAD/RPAD 的填充串为 NULL 时退化成空格填充(' 7'),MySQL 应整体 NULL。
8
+ * #319 Cache 的 TTL 清理定时器与自动保存定时器未 unref(),漏调 close() 时
9
+ * 挂住 Node 事件循环,进程无法自然退出。
10
+ * #321 legacy 单文件模式的自动保存定时器未 unref()(同文件 _flushTimer /
11
+ * _monitorTimer 已 unref),处理不一致。
12
+ */
13
+ const path = require('path');
14
+ const { execFileSync } = require('child_process');
15
+ const ROOT = path.join(__dirname, '..');
16
+ const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
17
+
18
+ let pass = 0, fail = 0;
19
+ function ok(name, cond, got) {
20
+ if (cond) { pass++; console.log('[OK] ' + name); }
21
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
22
+ }
23
+
24
+ async function main() {
25
+ const db = new Database(':memory:', { autoSave: false });
26
+ const q = async (sql) => (await executeSQL(db, sql, { safety: false })).rows[0][0];
27
+
28
+ // ================= #318 LPAD / RPAD 的 NULL 填充串 =================
29
+ ok("LPAD('7',3,NULL) = NULL(MySQL 三值逻辑)",
30
+ await q("SELECT LPAD('7', 3, NULL)") === null, null);
31
+ ok("RPAD('7',3,NULL) = NULL(MySQL 三值逻辑)",
32
+ await q("SELECT RPAD('7', 3, NULL)") === null, null);
33
+ ok("LPAD('7',3,NULL) IS NULL 为真",
34
+ await q("SELECT LPAD('7', 3, NULL) IS NULL") === 1, null);
35
+ ok("LPAD('7',3,'0') = '007'(不回归)",
36
+ await q("SELECT LPAD('7', 3, '0')") === '007', null);
37
+ ok("RPAD('7',3,'0') = '700'(不回归)",
38
+ await q("SELECT RPAD('7', 3, '0')") === '700', null);
39
+ ok("LPAD('hi',5,'ab') = 'abahi'(填充串循环不回归)",
40
+ await q("SELECT LPAD('hi', 5, 'ab')") === 'abahi', null);
41
+ ok("LPAD('hi',4,'') = ''(空填充串不回归)",
42
+ await q("SELECT LPAD('hi', 4, '')") === '', null);
43
+ // 缺省第三参仍按空格填充(MySQL 允许省略 padstr)
44
+ ok("LPAD('7',3) = ' 7'(缺省填充串仍用空格)",
45
+ await q("SELECT LPAD('7', 3)") === ' 7', null);
46
+
47
+ // ================= #317 REGEXP 非法正则 =================
48
+ let regexpErr = null;
49
+ try { await q("SELECT 'abc' REGEXP '['"); }
50
+ catch (e) { regexpErr = e; }
51
+ ok("非法正则 '[' 抛出错误而不是静默", !!regexpErr, regexpErr && regexpErr.message);
52
+ ok("非法正则归一为 errno 1139", regexpErr && regexpErr.errno === 1139,
53
+ regexpErr && regexpErr.errno);
54
+ ok("非法正则带 SQLSTATE 42000", regexpErr && regexpErr.sqlState === '42000',
55
+ regexpErr && regexpErr.sqlState);
56
+ ok("非法正则带 code ER_REGEXP_ERROR", regexpErr && regexpErr.code === 'ER_REGEXP_ERROR',
57
+ regexpErr && regexpErr.code);
58
+
59
+ let rlikeErr = null;
60
+ try { await q("SELECT 'abc' RLIKE '('"); }
61
+ catch (e) { rlikeErr = e; }
62
+ ok("非法正则 '('(RLIKE)同样归一为 1139", rlikeErr && rlikeErr.errno === 1139,
63
+ rlikeErr && rlikeErr.errno);
64
+
65
+ // 合法正则行为不变
66
+ ok("合法 REGEXP 不受影响:'abc' REGEXP '^a' = 1",
67
+ await q("SELECT 'abc' REGEXP '^a'") === 1, null);
68
+ ok("合法 REGEXP 不受影响:'abc' REGEXP '^z' = 0",
69
+ await q("SELECT 'abc' REGEXP '^z'") === 0, null);
70
+ ok("REGEXP 操作数为 NULL 仍返回 NULL(#230 不回归)",
71
+ await q("SELECT NULL REGEXP 'a'") === null, null);
72
+
73
+ // ================= #314 Redis LPOP / RPOP count 校验 =================
74
+ const { createRedisServer } = require(path.join(ROOT, 'lib/redis_server.js'));
75
+ const net = require('net');
76
+
77
+ function frame(args) {
78
+ const parts = args.map((a) => { const b = Buffer.from(String(a)); return '$' + b.length + '\r\n' + b + '\r\n'; });
79
+ return Buffer.from('*' + args.length + '\r\n' + parts.join(''));
80
+ }
81
+ const srv = createRedisServer({ port: 0, dataDir: null });
82
+ await new Promise((r) => srv.listen(r));
83
+ const sock = net.connect(srv.server.address().port, '127.0.0.1');
84
+ await new Promise((r) => sock.on('connect', r));
85
+ const chunks = [];
86
+ sock.on('data', (c) => chunks.push(c));
87
+ const send = async (args) => {
88
+ chunks.length = 0;
89
+ sock.write(frame(args));
90
+ await new Promise((r) => setTimeout(r, 120));
91
+ return Buffer.concat(chunks).toString('utf8');
92
+ };
93
+
94
+ await send(['RPUSH', 'l', '1', '2', '3']);
95
+ ok('RPUSH 返回 :3', (await send(['RPUSH', 'l2', '1', '2', '3'])) === ':3\r\n', null);
96
+
97
+ const lpopFrac = await send(['LPOP', 'l', '1.5']);
98
+ ok('LPOP count=1.5 报 integer 错误', lpopFrac.startsWith('-ERR'), lpopFrac);
99
+ ok('LPOP count=1.5 错误文案为 not an integer',
100
+ /not an integer or out of range/.test(lpopFrac), lpopFrac);
101
+
102
+ const lpopJunk = await send(['LPOP', 'l', '2abc']);
103
+ ok('LPOP count=2abc 报 integer 错误', lpopJunk.startsWith('-ERR'), lpopJunk);
104
+
105
+ const lpopNeg = await send(['LPOP', 'l', '-1']);
106
+ ok('LPOP count=-1 报 out of range 错误', lpopNeg.startsWith('-ERR'), lpopNeg);
107
+
108
+ // 报错后不应弹出任何元素
109
+ const llen = await send(['LLEN', 'l']);
110
+ ok('非法 count 不弹出元素(LLEN 仍为 3)', llen === ':3\r\n', llen);
111
+
112
+ const lpopOk = await send(['LPOP', 'l', '2']);
113
+ ok('LPOP count=2 正常返回两个元素', /^\*2\r\n/.test(lpopOk), lpopOk);
114
+ const llen2 = await send(['LLEN', 'l']);
115
+ ok('LPOP count=2 后 LLEN = 1', llen2 === ':1\r\n', llen2);
116
+
117
+ const rpopOk = await send(['RPOP', 'l2', '1']);
118
+ ok('RPOP count=1 正常返回', /^\*1\r\n/.test(rpopOk), rpopOk);
119
+
120
+ sock.destroy();
121
+ srv.stop();
122
+
123
+ // ================= #319 / #321 定时器 unref =================
124
+ // 用子进程跑一个「实例化后不 close()」的脚本,检查进程能自然退出。
125
+ const timerProbe = `
126
+ const root = ${JSON.stringify(ROOT)};
127
+ const { Database } = require(root + '/index.js');
128
+ const Cache = require(root + '/lib/cache.js');
129
+ const fs = require('fs'), os = require('os'), path = require('path');
130
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-timer-'));
131
+ const db = new Database(path.join(dir, 'db.json'), { autoSave: true, autoSaveInterval: 5000 });
132
+ const cache = new Cache();
133
+ cache.set('a', '1');
134
+ db.createTable('t', { id: { type: 'integer', primaryKey: true } }).then(() => {
135
+ db.insert('t', { id: 1 }).then(() => {
136
+ console.log('READY');
137
+ });
138
+ });
139
+ `;
140
+ const probeFile = path.join(ROOT, 'test', '.tmp-timer-probe.js');
141
+ fs.writeFileSync(probeFile, timerProbe, 'utf8');
142
+ let exited = false;
143
+ try {
144
+ execFileSync(process.execPath, [probeFile], { timeout: 4000, stdio: 'pipe' });
145
+ exited = true;
146
+ } catch (e) {
147
+ // 超时(SIGTERM)说明定时器挂住了事件循环
148
+ exited = false;
149
+ } finally {
150
+ fs.unlinkSync(probeFile);
151
+ }
152
+ ok('#319/#321 未 close() 时进程能自然退出(定时器已 unref)', exited, null);
153
+
154
+ console.log(`\n${pass} passed, ${fail} failed`);
155
+ process.exit(fail === 0 ? 0 : 1);
156
+ }
157
+
158
+ const fs = require('fs');
159
+ main().catch(e => {
160
+ console.log('[FAIL] unexpected exception: ' + (e.stack || e).split('\n').slice(0, 4).join('\n'));
161
+ process.exit(1);
162
+ });
@@ -73,8 +73,12 @@ try {
73
73
  ok('非法版本号 → FAIL', r4.ok === false, r4.checks.filter(c => !c.ok));
74
74
 
75
75
  // 开发中往 Unreleased 累积内容不应让门禁变红(只给软提示)
76
+ // 注意:工作区可能是 CRLF(core.autocrlf=true),用字面量 '\n' 匹配会静默失配,
77
+ // 反例没构造出来 → 断言变成假红/假绿。这里用 \r?\n 且必须真的替换成功。
76
78
  const wip = fixture('wip-unreleased', (c) => {
77
- c['CHANGELOG.md'] = c['CHANGELOG.md'].replace('## [Unreleased]\n', '## [Unreleased]\n\n### Added\n\n- 开发中\n');
79
+ const re = /## \[Unreleased\]\r?\n/;
80
+ if (!re.test(c['CHANGELOG.md'])) throw new Error('反例构造失败:CHANGELOG 缺 [Unreleased] 段');
81
+ c['CHANGELOG.md'] = c['CHANGELOG.md'].replace(re, '## [Unreleased]\r\n\r\n### Added\r\n\r\n- 开发中\r\n');
78
82
  });
79
83
  const r5 = checkReleaseMetadata(wip);
80
84
  ok('开发中 Unreleased 有内容仍通过', r5.ok === true, r5.checks.filter(c => !c.ok));