jsql-neo 6.6.2 → 6.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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.6.2** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
6
+ > **v6.6.3** — 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.6.2 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.6.3 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
package/lib/cache.js CHANGED
@@ -187,6 +187,9 @@ class Cache {
187
187
  if (start < 0) start = Math.max(list.length + start, 0);
188
188
  if (stop < 0) stop = list.length + stop;
189
189
  stop = Math.min(stop, list.length - 1);
190
+ // #89:stop 越界到负数也要钳到 0(与 Redis 一致)。
191
+ // 此前 stop 只有上限钳制,负数越界后 start > stop → 错误返回 []。
192
+ stop = Math.max(stop, 0);
190
193
  if (start > stop) return [];
191
194
  return list.slice(start, stop + 1);
192
195
  }
@@ -595,7 +595,9 @@ class MysqlConnection {
595
595
  this._send(encodeLenenc(1));
596
596
  this._send(columnDefinition({ name: 'Id', type: MYSQL_TYPE_LONG }));
597
597
  this._send(eofPacket());
598
- this._send(Buffer.from([0x31]));
598
+ // #95:结果行字段必须是 length-encoded string。
599
+ // 此前直接发裸字节 0x31('1'),客户端把它当字段长度读后续 49 字节 → 协议失步。
600
+ this._send(encodeLenencString('1'));
599
601
  this._send(eofPacket());
600
602
  break;
601
603
  }
@@ -1108,10 +1110,13 @@ class MysqlServer {
1108
1110
  if (!this._dbExists(db)) await this.createDatabase(db);
1109
1111
  const engine = await this._getDatabase(db);
1110
1112
  let s = sql;
1111
- // 词法扫描:找出所有字符串字面量和注释的位置,替换时跳过它们
1112
- const masked = _maskStringsAndComments(s);
1113
1113
  for (const t of tables) {
1114
1114
  if (t && t.indexOf('.') !== -1) {
1115
+ // #97:每次 s.replace 都会缩短 s(剥掉 db. 前缀),但 offset 是相对当前 s 的。
1116
+ // 此前 masked 只基于最初始的完整 s 算一次,后续 replace 的 offset 相对 masked
1117
+ // 整体"提前",掩码守卫误判 → ≥2 个 db.table 时改写错位(错库/错表)。
1118
+ // 所以每次替换前必须基于**当前 s** 重算掩码,保证 offset 对齐。
1119
+ const masked = _maskStringsAndComments(s);
1115
1120
  const re = new RegExp('\\b' + t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\b', 'g');
1116
1121
  s = s.replace(re, (match, offset) => {
1117
1122
  // 如果匹配位置在字符串字面量或注释中,不替换。
@@ -77,8 +77,14 @@ function matchOperator(value, op, expected) {
77
77
  case '$in': return Array.isArray(expected) && expected.some(e => looseEqual(value, e));
78
78
  case '$nin': return Array.isArray(expected) && !expected.some(e => looseEqual(value, e));
79
79
  case '$exists': return expected ? value !== undefined : value === undefined;
80
- case '$regex':
81
- return typeof value === 'string' && new RegExp(expected.source, expected.flags || 'i').test(value);
80
+ case '$regex': {
81
+ // #88:$regex 用字符串模式('a')时直接用字符串作正则源,不能取 .source
82
+ // (只有 RegExp 才有 .source)。此前 new RegExp(undefined) = /(?:)/ 匹配一切,
83
+ // 导致 find({ $regex: 'a' }) 返回全表。
84
+ const src = typeof expected === 'string' ? expected : (expected && expected.source);
85
+ const flags = (expected && expected.flags) || 'i';
86
+ return typeof value === 'string' && new RegExp(src, flags).test(value);
87
+ }
82
88
  case '$size': return Array.isArray(value) && value.length === expected;
83
89
  default: return false;
84
90
  }
package/lib/pg_server.js CHANGED
@@ -206,6 +206,17 @@ function buildParameterDesc(paramTypes) {
206
206
  return frame(0x74, p.build()); // 't'
207
207
  }
208
208
 
209
+ // #93:PG 二进制参数解码。Bind 的 parameter format code=1 时按参数类型(OID)解码,
210
+ // 不能按 UTF-8 文本读。常见 OID:int4=23, int8=20, float8=701, float4=700, bool=16。
211
+ function decodeBinaryParam(buf, typeOid) {
212
+ if (typeOid === 23) return buf.length >= 4 ? buf.readInt32BE(0) : null; // int4
213
+ if (typeOid === 20) return buf.length >= 8 ? buf.readBigInt64BE(0) : null; // int8
214
+ if (typeOid === 701) return buf.length >= 8 ? buf.readDoubleBE(0) : null; // float8
215
+ if (typeOid === 700) return buf.length >= 4 ? buf.readFloatBE(0) : null; // float4
216
+ if (typeOid === 16) return buf.length >= 1 ? buf[0] !== 0 : null; // bool
217
+ return buf.toString('utf8');
218
+ }
219
+
209
220
  // ---------------------------------------------------------------------------
210
221
  // SCRAM-SHA-256 (RFC 5802 / RFC 7677) — server side
211
222
  // ---------------------------------------------------------------------------
@@ -520,7 +531,10 @@ class PgConnection {
520
531
  if (vlen === -1) { values.push(null); continue; }
521
532
  if (vlen < 0 || off + vlen > body.length) throw new Error('invalid Bind parameter length');
522
533
  const fmt = formats.length > 0 ? formats[Math.min(i, formats.length - 1)] : 0;
523
- values.push(body.toString('utf8', off, off + vlen));
534
+ // #93:fmt=1(binary)时按参数类型解码,此前一律按 UTF-8 文本读导致二进制参数错乱。
535
+ const pt = (stmt.paramTypes && stmt.paramTypes[i]) || 0;
536
+ const raw = body.slice(off, off + vlen);
537
+ values.push(fmt === 1 ? decodeBinaryParam(raw, pt) : body.toString('utf8', off, off + vlen));
524
538
  off += vlen;
525
539
  }
526
540
  this._portal.set(portal, { values, stmt });
@@ -881,4 +895,4 @@ function createPgServer(options) {
881
895
  return new PgServer(options || {});
882
896
  }
883
897
 
884
- module.exports = { PgServer, createPgServer, PgConnection, buildRowDescription, buildDataRow, buildCommandComplete, buildErrorResponse, buildReadyForQuery, buildParameterStatus, buildBackendKeyData, buildParseComplete, buildBindComplete, buildCloseComplete, buildNoData, buildParameterDesc, TYPE_OIDS, pgTypeOid, pgFormatValue };
898
+ module.exports = { PgServer, createPgServer, PgConnection, buildRowDescription, buildDataRow, buildCommandComplete, buildErrorResponse, buildReadyForQuery, buildParameterStatus, buildBackendKeyData, buildParseComplete, buildBindComplete, buildCloseComplete, buildNoData, buildParameterDesc, decodeBinaryParam, TYPE_OIDS, pgTypeOid, pgFormatValue };
package/lib/sql.js CHANGED
@@ -1248,7 +1248,10 @@ class Parser {
1248
1248
  while (true) {
1249
1249
  const col = this.parseTableName();
1250
1250
  this.expect('op', '=');
1251
- const val = this.parseValue();
1251
+ // #99:ON DUPLICATE KEY UPDATE 赋值右侧的裸标识符(如 other=other)是**列引用**,
1252
+ // 不是字符串字面量(MySQL 语义:自赋值是合法 no-op)。
1253
+ // 传 identAsColumn=true 让 parseValue 把裸 ident 解析成 {type:'column'}。
1254
+ const val = this.parseValue(true);
1252
1255
  onDuplicate.push([col, val]);
1253
1256
  if (this.peek().value === ',') { this.next(); continue; }
1254
1257
  break;
@@ -1283,8 +1286,8 @@ class Parser {
1283
1286
  return cols;
1284
1287
  }
1285
1288
 
1286
- parseValue() {
1287
- const atom = this.parseValueAtom();
1289
+ parseValue(identAsColumn = false) {
1290
+ const atom = this.parseValueAtom(identAsColumn);
1288
1291
  return this.parseBinaryFromAtom(atom);
1289
1292
  }
1290
1293
 
@@ -1301,7 +1304,7 @@ class Parser {
1301
1304
  return left;
1302
1305
  }
1303
1306
 
1304
- parseValueAtom() {
1307
+ parseValueAtom(identAsColumn = false) {
1305
1308
  // MySQL 前缀运算符:BINARY expr —— 强制大小写敏感比较。
1306
1309
  // 仅当后面确实是值起始 token 才当作运算符,避免误吞裸列名 `binary`
1307
1310
  // (`SELECT binary FROM t` / `WHERE binary = 1` 仍按列名解析)。
@@ -1348,9 +1351,11 @@ class Parser {
1348
1351
  this.next();
1349
1352
  const col = this.next();
1350
1353
  if (!isUsableNameToken(col)) throw new Error(`Expected column name after '.', got '${col.value}'`);
1351
- return nameOfToken(t) + '.' + nameOfToken(col);
1354
+ const full = nameOfToken(t) + '.' + nameOfToken(col);
1355
+ return identAsColumn ? { type: 'column', name: full } : full;
1352
1356
  }
1353
- return nameOfToken(t);
1357
+ // #99:ON DUPLICATE 赋值右侧裸标识符 → 列引用节点
1358
+ return identAsColumn ? { type: 'column', name: nameOfToken(t) } : nameOfToken(t);
1354
1359
  }
1355
1360
  throw new Error(`Expected value, got '${t.value}'`);
1356
1361
  }
@@ -3257,10 +3262,25 @@ function applyCast(value, dataType) {
3257
3262
  }
3258
3263
  return n;
3259
3264
  }
3260
- if (t === 'FLOAT' || t === 'DOUBLE' || t === 'REAL' || t === 'NUMERIC' || t === 'DECIMAL') {
3265
+ if (t === 'FLOAT' || t === 'DOUBLE' || t === 'REAL') {
3261
3266
  const n = Number(value);
3262
3267
  return Number.isFinite(n) ? n : null;
3263
3268
  }
3269
+ if (t === 'NUMERIC' || t === 'DECIMAL') {
3270
+ // #96:CAST(x AS DECIMAL(p,s)) 必须按标度 s 四舍五入,不能原样返回。
3271
+ // 此前 DECIMAL 被并入 FLOAT 分支,p/s 被剥掉后原值返回(123.456 → 123.456)。
3272
+ const m = String(dataType).match(/\((\d+)(?:,(\d+))?\)/i);
3273
+ const scale = m && m[2] !== undefined ? parseInt(m[2], 10) : 0;
3274
+ let n = Number(value);
3275
+ if (!Number.isFinite(n)) return null;
3276
+ if (scale > 0) {
3277
+ const factor = Math.pow(10, scale);
3278
+ n = Math.round(n * factor) / factor;
3279
+ } else {
3280
+ n = Math.round(n);
3281
+ }
3282
+ return n;
3283
+ }
3264
3284
  if (t === 'BOOLEAN' || t === 'BOOL') {
3265
3285
  if (typeof value === 'boolean') return value;
3266
3286
  if (typeof value === 'number') return value !== 0;
@@ -4882,7 +4902,10 @@ function seedRand(seed) {
4882
4902
  // ci 默认 true:保持 LIKE 既有的大小写不敏感行为不变;ILIKE 同为不敏感。
4883
4903
  // escape:可选转义符(ESCAPE 子句),默认反斜杠;转义符后跟 % _ 或转义符本身按字面量匹配。
4884
4904
  function likeMatch(value, pattern, ci = true, escape = '\\') {
4885
- if (typeof value !== 'string') return false;
4905
+ // #94:NULL LIKE ... → UNKNOWN(null),不能当 false。
4906
+ if (value === null || value === undefined) return null;
4907
+ // #94:MySQL 语义——数值列(及其他类型)先转成字符串再 LIKE(10 LIKE '1%' → '10' LIKE '1%' → true)。
4908
+ const sv = String(value);
4886
4909
  const p = String(pattern);
4887
4910
  const e = (escape === null || escape === undefined || escape === '') ? '\\' : String(escape);
4888
4911
  const reEsc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@@ -4898,7 +4921,7 @@ function likeMatch(value, pattern, ci = true, escape = '\\') {
4898
4921
  else if (ch === '_') out += '.';
4899
4922
  else out += reEsc(ch);
4900
4923
  }
4901
- return new RegExp('^' + out + '$', ci ? 'i' : '').test(value);
4924
+ return new RegExp('^' + out + '$', ci ? 'i' : '').test(sv);
4902
4925
  }
4903
4926
 
4904
4927
  /** 解析 PG 的路径字面量:'{a,b}' 或数组 → ['a','b'] */
@@ -5122,6 +5145,23 @@ function sqlXor(a, b) {
5122
5145
  return a !== b ? 1 : 0;
5123
5146
  }
5124
5147
 
5148
+ // #86:递归把表达式 AST 里的 VALUES(col)/EXCLUDED.col 节点替换成目标行 d 的对应列值。
5149
+ // ON DUPLICATE KEY UPDATE 里 VALUES(col) 引用"本次本应插入的值"(新行 d),
5150
+ // 求值前必须先替换,否则 evaluateExpr/resolveOperand 不认识 _valuesOf 节点。
5151
+ function substituteValuesOf(node, d) {
5152
+ if (node && typeof node === 'object') {
5153
+ if (node._valuesOf !== undefined || node._excludedOf !== undefined) {
5154
+ const col = node._valuesOf !== undefined ? node._valuesOf : node._excludedOf;
5155
+ return (d && d[col] !== undefined) ? d[col] : null;
5156
+ }
5157
+ if (Array.isArray(node)) return node.map(n => substituteValuesOf(n, d));
5158
+ const out = {};
5159
+ for (const k of Object.keys(node)) out[k] = substituteValuesOf(node[k], d);
5160
+ return out;
5161
+ }
5162
+ return node;
5163
+ }
5164
+
5125
5165
  function evaluateExpr(expr, row, ctx) {
5126
5166
  if (expr === null || expr === undefined) return false;
5127
5167
  switch (expr.type) {
@@ -5263,6 +5303,8 @@ function evaluateExpr(expr, row, ctx) {
5263
5303
  // MySQL 的 LIKE 默认不区分大小写;只有显式 BINARY / ci=false 才敏感。
5264
5304
  // 此前写成 !!expr.ci,把 likeMatch 的 ci 默认值 true 覆盖成了 false。
5265
5305
  const r = likeMatch(v, expr.pattern, expr.ci !== false, expr.escape);
5306
+ // #94:NULL LIKE → UNKNOWN(null);NOT (NULL LIKE) 仍为 UNKNOWN(null)。
5307
+ if (r === null) return null;
5266
5308
  return expr.not ? !r : r;
5267
5309
  }
5268
5310
  case 'quantified':
@@ -5907,7 +5949,16 @@ class SQLExecutor {
5907
5949
  const evalRow = existingRow
5908
5950
  ? Object.fromEntries([...Object.entries(d), ...Object.entries(existingRow)])
5909
5951
  : d;
5910
- data[col] = evaluateExpr(val, evalRow, this.ctx);
5952
+ // #86:把表达式里的 VALUES(col)/EXCLUDED.col 解析成"本次本应插入的值"(d),
5953
+ // 否则 evaluateExpr 不认识 _valuesOf 节点 → undefined + 1 → NULL(数据损坏)。
5954
+ data[col] = evaluateExpr(substituteValuesOf(val, d), evalRow, this.ctx);
5955
+ } else if (val && typeof val === 'object' && val.type === 'column') {
5956
+ // #99:裸列名(other=other)按旧行值求值(合法 no-op),不当字符串字面量。
5957
+ // 此前解析成 'other' 赋给 INT 列 → 1292 崩溃。
5958
+ const evalRow = existingRow
5959
+ ? Object.fromEntries([...Object.entries(d), ...Object.entries(existingRow)])
5960
+ : d;
5961
+ data[col] = evalRow[val.name] !== undefined ? evalRow[val.name] : d[val.name];
5911
5962
  } else {
5912
5963
  data[col] = val;
5913
5964
  }
@@ -7000,9 +7051,10 @@ class SQLExecutor {
7000
7051
  const vs = values.filter(v => v !== null && v !== undefined);
7001
7052
  if (!vs.length) return null;
7002
7053
  // 数值按数值比;字符串/日期按字典序/时间序。
7003
- // 此前一律 Number(v) —— 字符串列会得到 NaN,MIN(name) 直接变 null。
7004
- const numeric = (v) => typeof v === 'number' ||
7005
- (typeof v === 'string' && String(v).trim() !== '' && Number.isFinite(Number(v)));
7054
+ // #98:只有**真正的 number** 才按数值比较。全数字字符串列('2','100','9')
7055
+ // 此前被误判为数值 → MIN/MAX 用数值比较且返回 Number,与 ORDER BY 字典序自相矛盾。
7056
+ // MySQL 语义:字符串列一律字典序且结果保持字符串。
7057
+ const numeric = (v) => typeof v === 'number';
7006
7058
  if (vs.every(numeric)) {
7007
7059
  let best = Number(vs[0]);
7008
7060
  for (let i = 1; i < vs.length; i++) {
@@ -8970,7 +9022,9 @@ function applyParams(sql, values) {
8970
9022
  const args = values || [];
8971
9023
  let count = 0;
8972
9024
  let out = '';
8973
- let idx = 0;
9025
+ let idx = 0; // 匿名 ? 的"下一个未占用槽"游标
9026
+ const used = new Set(); // 已被编号占位符 ?N/$N 占用的参数槽
9027
+ let hasIndexed = false; // 是否出现过编号占位符(混用时 Too many 检查会误判)
8974
9028
  let inStr = null;
8975
9029
  let i = 0;
8976
9030
  const named = {};
@@ -8979,6 +9033,8 @@ function applyParams(sql, values) {
8979
9033
  hasNamed = true;
8980
9034
  }
8981
9035
  const n = sql.length;
9036
+ // #92:匿名 ? 按顺序消费"尚未被编号占位符占用"的最小槽,避免编号 ?N 劫持游标。
9037
+ const nextFree = () => { while (used.has(idx)) idx++; return idx; };
8982
9038
  while (i < n) {
8983
9039
  const c = sql[i];
8984
9040
  if (inStr) {
@@ -9007,8 +9063,14 @@ function applyParams(sql, values) {
9007
9063
  continue;
9008
9064
  }
9009
9065
  if (c === '?' && sql[i + 1] === '?') {
9010
- if (!hasNamed && idx >= args.length) throw new Error('Not enough parameters for SQL: expected ' + (count + 1));
9011
- out += escapeId(hasNamed ? args['@@'] : args[idx++]);
9066
+ if (hasNamed) { out += escapeId(args['@@']); }
9067
+ else {
9068
+ const k = nextFree();
9069
+ if (k >= args.length) throw new Error('Not enough parameters for SQL: expected ' + (count + 1));
9070
+ out += escapeId(args[k]);
9071
+ used.add(k);
9072
+ idx++;
9073
+ }
9012
9074
  count++;
9013
9075
  i += 2;
9014
9076
  continue;
@@ -9026,14 +9088,21 @@ function applyParams(sql, values) {
9026
9088
  } else {
9027
9089
  if (n - 1 >= args.length) throw new Error(`Not enough parameters for SQL: expected ?${n}`);
9028
9090
  out += escapeValue(args[n - 1]);
9029
- if (n > idx) idx = n;
9091
+ used.add(n - 1);
9092
+ hasIndexed = true;
9030
9093
  }
9031
9094
  count++;
9032
9095
  i = j;
9033
9096
  continue;
9034
9097
  }
9035
- if (!hasNamed && idx >= args.length) throw new Error('Not enough parameters for SQL: expected ' + (count + 1));
9036
- out += escapeValue(hasNamed ? args['?'] : args[idx++]);
9098
+ if (hasNamed) { out += escapeValue(args['?']); }
9099
+ else {
9100
+ const k = nextFree();
9101
+ if (k >= args.length) throw new Error('Not enough parameters for SQL: expected ' + (count + 1));
9102
+ out += escapeValue(args[k]);
9103
+ used.add(k);
9104
+ idx++;
9105
+ }
9037
9106
  count++;
9038
9107
  i++;
9039
9108
  continue;
@@ -9065,7 +9134,8 @@ function applyParams(sql, values) {
9065
9134
  } else {
9066
9135
  if (n - 1 >= args.length) throw new Error(`Not enough parameters for SQL: expected $${n}`);
9067
9136
  out += escapeValue(args[n - 1]);
9068
- if (n > idx) idx = n;
9137
+ used.add(n - 1);
9138
+ hasIndexed = true;
9069
9139
  }
9070
9140
  count++;
9071
9141
  i = j;
@@ -9086,7 +9156,9 @@ function applyParams(sql, values) {
9086
9156
  out += c;
9087
9157
  i++;
9088
9158
  }
9089
- if (!hasNamed && idx !== args.length) {
9159
+ // #92:混用编号占位符 ?N/$N 时,idx(匿名游标)与 args.length 的"恰好相等"判断
9160
+ // 不可靠(编号占位符会占用任意槽),会误报 Too many。纯匿名场景保留严格检查。
9161
+ if (!hasNamed && !hasIndexed && idx !== args.length) {
9090
9162
  throw new Error(`Too many parameters for SQL: got ${args.length}, expected ${count}`);
9091
9163
  }
9092
9164
  return out;
@@ -296,7 +296,13 @@ class Statement {
296
296
 
297
297
  all(...params) {
298
298
  const r = this._call('all', params.length > 0 ? params : undefined);
299
- if (this._rawMode) return this._call('raw', params.length > 0 ? params : undefined);
299
+ // #87:raw() 只是输出格式开关(对象行 → 值数组),不能重新执行 SQL。
300
+ // 此前 .raw(true).all() 再调 _call('raw') 导致 INSERT/DELETE 重复执行(数据损坏)。
301
+ if (this._rawMode) {
302
+ return Array.isArray(r)
303
+ ? r.map(row => (row && typeof row === 'object' && !Array.isArray(row)) ? Object.values(row) : row)
304
+ : r;
305
+ }
300
306
  if (this._pluck) {
301
307
  const cols = r && r.length > 0 ? Object.keys(r[0]) : [];
302
308
  return cols.length > 0 ? r.map(row => row[cols[0]]) : [];
package/lib/updater.js CHANGED
@@ -45,21 +45,46 @@ function parseVersion(v) {
45
45
  const x = parseInt(n, 10);
46
46
  return Number.isFinite(x) ? x : 0;
47
47
  });
48
- while (nums.length < 3) nums.push(0);
49
48
  return { nums, pre };
50
49
  }
51
50
 
52
- /** semver-ish 比较:a < b → -1,相等 → 0,a > b → 1(prerelease 视为更低) */
51
+ // #90:prerelease 标识符按 semver 规则比较:数字标识符按数值、字母按字典序、
52
+ // 数字 > 字母、长度长者大。此前用 A.pre > B.pre 字符串比较,'alpha.10' < 'alpha.9' 误判。
53
+ function comparePre(a, b) {
54
+ if (a === b) return 0;
55
+ if (!a) return 1; // 无 prerelease > 有 prerelease
56
+ if (!b) return -1;
57
+ const A = a.split('.');
58
+ const B = b.split('.');
59
+ const len = Math.max(A.length, B.length);
60
+ for (let i = 0; i < len; i++) {
61
+ const x = A[i], y = B[i];
62
+ if (x === undefined) return -1;
63
+ if (y === undefined) return 1;
64
+ const xn = /^\d+$/.test(x), yn = /^\d+$/.test(y);
65
+ if (xn && yn) {
66
+ const xi = parseInt(x, 10), yi = parseInt(y, 10);
67
+ if (xi !== yi) return xi > yi ? 1 : -1;
68
+ } else if (xn !== yn) {
69
+ return xn ? 1 : -1; // 数字标识符 > 字母标识符
70
+ } else if (x !== y) {
71
+ return x > y ? 1 : -1;
72
+ }
73
+ }
74
+ return 0;
75
+ }
76
+
77
+ /** semver-ish 比较:a < b → -1,相等 → 0,a > b → 1(prerelease 视为更低)。
78
+ * #90:支持 4+ 段版本号(此前截断为 3 段,1.2.3.4 与 1.2.3 被误判相等)。 */
53
79
  function compareVersions(a, b) {
54
80
  const A = parseVersion(a);
55
81
  const B = parseVersion(b);
56
- for (let i = 0; i < 3; i++) {
57
- if (A.nums[i] !== B.nums[i]) return A.nums[i] > B.nums[i] ? 1 : -1;
82
+ const len = Math.max(A.nums.length, B.nums.length);
83
+ for (let i = 0; i < len; i++) {
84
+ const x = A.nums[i] || 0, y = B.nums[i] || 0;
85
+ if (x !== y) return x > y ? 1 : -1;
58
86
  }
59
- if (A.pre === B.pre) return 0;
60
- if (!A.pre) return 1;
61
- if (!B.pre) return -1;
62
- return A.pre > B.pre ? 1 : -1;
87
+ return comparePre(A.pre, B.pre);
63
88
  }
64
89
 
65
90
  function isNewer(latest, current) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.6.2",
3
+ "version": "6.6.3",
4
4
  "description": "JSQL-NEO — Rust-powered embedded database with WASM, REST API, B-Tree indexes, WAL, crash recovery",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -50,12 +50,12 @@
50
50
  "scripts": {
51
51
  "postinstall": "node postinstall.js",
52
52
  "build:native": "node scripts/build-native.js",
53
- "test": "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",
53
+ "test": "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",
54
54
  "test:parser": "node test/sql-parser.test.js",
55
55
  "test:btree": "node test/btree.test.js",
56
56
  "test:native": "node test/native.test.js",
57
57
  "test:regress": "node test/regress-5.1.0.js",
58
- "test:all": "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",
58
+ "test:all": "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",
59
59
  "test:coverage": "c8 --all --include='lib/**' --exclude='lib/web_ui.js' --reporter=text --reporter=lcov node test/coverage.js",
60
60
  "test:orms": "node examples/orms/run-all.js",
61
61
  "test:dml": "node test/dml-constraints.test.js",
@@ -0,0 +1,154 @@
1
+ // 回归测试:Issue #86-#99
2
+ const Database = require('../lib/database');
3
+ const { executeSQL, applyParams, splitStatements, parseSQL } = require('../lib/sql');
4
+ const { Datastore } = require('../lib/nedb_compat');
5
+ const Cache = require('../lib/cache');
6
+ const updater = require('../lib/updater');
7
+ const { decodeBinaryParam } = require('../lib/pg_server');
8
+ const { createMysqlServer, MysqlConnection } = require('../lib/mysql_server');
9
+ const sqliteCompat = require('../lib/sqlite_compat');
10
+
11
+ let pass = 0, fail = 0;
12
+ function ok(name, cond, extra) {
13
+ if (cond) { pass++; console.log('[OK] ', name); }
14
+ else { fail++; console.log('[FAIL]', name, extra !== undefined ? ' -> ' + JSON.stringify(extra).slice(0, 240) : ''); }
15
+ }
16
+
17
+ (async () => {
18
+ // #86 ON DUPLICATE VALUES(a)+1 表达式
19
+ {
20
+ const db = new Database(':memory:');
21
+ await executeSQL(db, "CREATE TABLE t (id INT PRIMARY KEY, a INT, b INT)");
22
+ await executeSQL(db, "INSERT INTO t VALUES (1,10,3)");
23
+ await executeSQL(db, "INSERT INTO t (id,a,b) VALUES (1,100,200) ON DUPLICATE KEY UPDATE a=VALUES(a)+1, b=VALUES(b)");
24
+ const r = await executeSQL(db, "SELECT * FROM t");
25
+ ok('#86 VALUES(a)+1 → a=101', r.rows[0][1] === 101, r.rows[0]);
26
+ }
27
+
28
+ // #87 sqlite raw(true).all() 不重复执行
29
+ {
30
+ const db = new sqliteCompat.Database(':memory:');
31
+ db.exec('CREATE TABLE t (a INT)');
32
+ db.prepare('INSERT INTO t(a) VALUES (1)').raw(true).all();
33
+ const n = db.prepare('SELECT COUNT(*) c FROM t').get();
34
+ ok('#87 raw(true).all() 只执行一次', n.c === 1, n);
35
+ const rows = db.prepare('SELECT a FROM t').raw(true).all();
36
+ ok('#87 raw 输出数组格式', JSON.stringify(rows) === '[[1]]', rows);
37
+ }
38
+
39
+ // #88 $regex 字符串模式
40
+ {
41
+ const ds = new Datastore({ inMemoryOnly: true });
42
+ await ds.loadDatabase();
43
+ await ds.insert({ name: 'alice' }); await ds.insert({ name: 'bob' }); await ds.insert({ name: 'charlie' });
44
+ const r = await ds.find({ name: { $regex: '^al' } });
45
+ ok('#88 $regex ^al 只返回 alice', r.length === 1, r.length);
46
+ }
47
+
48
+ // #89 lrange 负索引越界
49
+ {
50
+ const c = new Cache();
51
+ c.rpush('k', 'a', 'b', 'c');
52
+ const out = c.lrange('k', 0, -5);
53
+ ok('#89 lrange(0,-5) → ["a"]', out.join(',') === 'a', out);
54
+ }
55
+
56
+ // #90 updater 版本比较
57
+ {
58
+ ok('#90 alpha.10 > alpha.9', updater.isNewer('1.0.0-alpha.10', '1.0.0-alpha.9') === true, updater.isNewer('1.0.0-alpha.10', '1.0.0-alpha.9'));
59
+ ok('#90 1.2.3.4 > 1.2.3', updater.compareVersions('1.2.3.4', '1.2.3') > 0, updater.compareVersions('1.2.3.4', '1.2.3'));
60
+ }
61
+
62
+ // #91 多语句协议(fake connection 应产生 2 个结果集)
63
+ {
64
+ const server = createMysqlServer({ safety: false });
65
+ await server._getEngine();
66
+ const socket = { write: () => {}, destroy: () => {}, remoteAddress: 'x', on: () => {} };
67
+ const conn = new MysqlConnection(socket, server);
68
+ conn.authenticated = true; conn.multiStatements = true;
69
+ await new Promise((res) => { conn._handleQuery('SELECT 1; SELECT 2;'); setTimeout(res, 800); });
70
+ ok('#91 多语句无异常', true);
71
+ }
72
+
73
+ // #92 applyParams 混用 ?N 与 ?
74
+ {
75
+ const a = applyParams("SELECT * FROM t WHERE a=? AND b=?2", [10, 20, 30]);
76
+ ok('#92 a=? AND b=?2 → a=10 b=20', a.includes('a=10') && a.includes('b=20'), a);
77
+ const b = applyParams("SELECT * FROM t WHERE b=?2 AND a=?", [10, 20, 30]);
78
+ ok('#92 b=?2 AND a=? → b=20 a=10', b.includes('b=20') && b.includes('a=10'), b);
79
+ }
80
+
81
+ // #93 pg 二进制参数解码
82
+ {
83
+ const i4 = Buffer.from([0, 0, 0, 42]);
84
+ ok('#93 int4 binary=42', decodeBinaryParam(i4, 23) === 42, decodeBinaryParam(i4, 23));
85
+ const i8 = Buffer.alloc(8); i8.writeBigInt64BE(1234567890123n);
86
+ ok('#93 int8 binary', decodeBinaryParam(i8, 20) === 1234567890123n, decodeBinaryParam(i8, 20));
87
+ const f8 = Buffer.alloc(8); f8.writeDoubleBE(3.14);
88
+ ok('#93 float8 binary', decodeBinaryParam(f8, 701) === 3.14, decodeBinaryParam(f8, 701));
89
+ }
90
+
91
+ // #94 数值 LIKE
92
+ {
93
+ const db = new Database(':memory:');
94
+ await executeSQL(db, "CREATE TABLE t (id INT PRIMARY KEY, a INT)");
95
+ await executeSQL(db, "INSERT INTO t VALUES (1,10),(2,20)");
96
+ const r = await executeSQL(db, "SELECT id FROM t WHERE a LIKE '1%'");
97
+ ok('#94 a LIKE \'1%\' → id=1', r.rows.map(x => x[0]).join(',') === '1', r.rows);
98
+ }
99
+
100
+ // #95 COM_PROCESS_INFO 用 lenenc string
101
+ {
102
+ const server = createMysqlServer({ safety: false });
103
+ await server._getEngine();
104
+ const socket = { write: () => {}, destroy: () => {}, remoteAddress: 'x', on: () => {} };
105
+ const conn = new MysqlConnection(socket, server);
106
+ conn.authenticated = true;
107
+ const sent = [];
108
+ conn._send = (b) => { sent.push(Buffer.from(b)); };
109
+ conn._handlePacket(Buffer.from([0x0a]), 0);
110
+ let found = false;
111
+ for (const p of sent) for (let i = 0; i < p.length - 1; i++) if (p[i] === 0x01 && p[i + 1] === 0x31) found = true;
112
+ ok('#95 数据行含 lenenc 0x01 0x31', found);
113
+ }
114
+
115
+ // #96 CAST DECIMAL 精度
116
+ {
117
+ const db = new Database(':memory:');
118
+ const r = await executeSQL(db, "SELECT CAST(123.456 AS DECIMAL(10,2))");
119
+ ok('#96 CAST DECIMAL(10,2) → 123.46', r.rows[0][0] === 123.46, r.rows[0][0]);
120
+ const r2 = await executeSQL(db, "SELECT CAST(123.456 AS DECIMAL(10,0))");
121
+ ok('#96 CAST DECIMAL(10,0) → 123', r2.rows[0][0] === 123, r2.rows[0][0]);
122
+ }
123
+
124
+ // #97 _route 多限定表
125
+ {
126
+ const server = createMysqlServer({ safety: false });
127
+ await server._getEngine();
128
+ const sql = "SELECT * FROM db1.t JOIN db1.u ON t.id=u.id WHERE name='db1.t'";
129
+ const routed = await server._route(parseSQL(sql), sql, null, null);
130
+ ok('#97 多表改写 + 字符串保留', routed.sql === "SELECT * FROM t JOIN u ON t.id=u.id WHERE name='db1.t'", routed.sql);
131
+ }
132
+
133
+ // #98 字符串列 MIN/MAX 字典序
134
+ {
135
+ const db = new Database(':memory:');
136
+ await executeSQL(db, "CREATE TABLE s (x STRING)");
137
+ await executeSQL(db, "INSERT INTO s VALUES ('2'),('100'),('9')");
138
+ const r = await executeSQL(db, "SELECT MIN(x), MAX(x) FROM s");
139
+ ok('#98 MIN=100 MAX=9 字典序', r.rows[0][0] === '100' && r.rows[0][1] === '9', r.rows[0]);
140
+ }
141
+
142
+ // #99 ON DUPLICATE 裸列名
143
+ {
144
+ const db = new Database(':memory:');
145
+ await executeSQL(db, "CREATE TABLE t (id INT PRIMARY KEY, cnt INT, other INT)");
146
+ await executeSQL(db, "INSERT INTO t VALUES (1,5,7)");
147
+ await executeSQL(db, "INSERT INTO t (id,cnt,other) VALUES (1,5,7) ON DUPLICATE KEY UPDATE cnt=cnt+1, other=other");
148
+ const r = await executeSQL(db, "SELECT * FROM t");
149
+ ok('#99 other=other 不崩溃且 cnt=6', r.rows[0][1] === 6 && r.rows[0][2] === 7, r.rows[0]);
150
+ }
151
+
152
+ console.log(`\n${pass} passed, ${fail} failed`);
153
+ process.exit(fail === 0 ? 0 : 1);
154
+ })().catch(e => { console.error('FATAL', e); process.exit(1); });