jsql-neo 6.8.26 → 6.8.27

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.
@@ -360,6 +360,7 @@ class MongoServer {
360
360
  this._indexesByColl = new Map(); // "db.coll" → [{ name, columns, unique }]
361
361
  this._cursors = new Map(); // #278:find/getMore 游标
362
362
  this._nextCursorId = 1;
363
+ this._nextConnId = 0; // #459:连接自增标识,游标绑定到创建它的连接
363
364
  // #428:游标空闲超时(默认 10 分钟,与 MongoDB 默认 cursor 超时一致),
364
365
  // 超时后后台清扫回收;可经 options.cursorIdleTimeoutMs 覆盖。
365
366
  this._cursorIdleTimeoutMs = Number(options.cursorIdleTimeoutMs) > 0
@@ -367,6 +368,7 @@ class MongoServer {
367
368
  this._cursorTimer = setInterval(() => this._sweepIdleCursors(), Math.min(this._cursorIdleTimeoutMs, 60 * 1000));
368
369
  if (typeof this._cursorTimer.unref === 'function') this._cursorTimer.unref();
369
370
  this._autoCollections = new Set(); // db.collection 由 Mongo 自动建表(可继续补列)
371
+ this._startedAt = Date.now();
370
372
  }
371
373
 
372
374
  async _getEngine(db = null) {
@@ -477,6 +479,7 @@ class MongoServer {
477
479
 
478
480
  _handleSocket(socket, existing) {
479
481
  this._sockets.add(socket);
482
+ socket._mongoConnId = ++this._nextConnId; // #459:游标归属连接标识
480
483
  socket.on('close', () => this._sockets.delete(socket));
481
484
  let buf = Buffer.isBuffer(existing) ? Buffer.from(existing) : Buffer.alloc(0);
482
485
  if (buf.length > this.maxMessageSize) {
@@ -564,7 +567,7 @@ class MongoServer {
564
567
  try {
565
568
  const body = bsonReadDocument(msg, p).value;
566
569
  const command = this._commandName(body);
567
- const reply = await this._dispatch(command, body);
570
+ const reply = await this._dispatch(command, body, socket._mongoConnId);
568
571
  socket.write(this._wrapReply(bsonDocument(reply), this._reqId(msg)));
569
572
  } catch (e) {
570
573
  socket.write(this._wrapReply(bsonDocument({ ok: 0, errmsg: e.message || String(e) }), this._reqId(msg)));
@@ -623,7 +626,7 @@ class MongoServer {
623
626
  return;
624
627
  }
625
628
  const command = this._commandName(body);
626
- const reply = await this._dispatch(command, body);
629
+ const reply = await this._dispatch(command, body, socket._mongoConnId);
627
630
  socket.write(this._wrapMsg(bsonDocument(reply), this._reqId(msg)));
628
631
  }
629
632
 
@@ -637,15 +640,17 @@ class MongoServer {
637
640
 
638
641
  _decompress(msg) {
639
642
  try {
643
+ // OP_COMPRESSED 布局:16B 标准头 + int32 originalOpcode(16) +
644
+ // int8 compressorId(20) + int32 uncompressedSize(21) + compressedMessage(25)。
645
+ // compressorId:1=snappy,2=zlib,3=zstd。
640
646
  const origOp = msg.readInt32LE(16);
641
- const uncompSize = msg.readInt32LE(20);
642
- const compId = msg[24];
647
+ const compId = msg[20];
648
+ const uncompSize = msg.readInt32LE(21);
643
649
  const data = msg.slice(25);
644
650
  let out;
645
651
  if (compId === 2) out = zlib.inflateSync(data); // zlib
646
- else if (compId === 3) { /* zstd 无内置支持 */ return null; }
647
- else if (compId === 1) { /* snappy 无内置支持 */ return null; }
648
- else return null;
652
+ else return null; // 1=snappy / 3=zstd 无内置支持
653
+ if (uncompSize > 0 && out.length !== uncompSize) return null;
649
654
  const head = Buffer.from(msg.slice(0, 16));
650
655
  head.writeInt32LE(origOp, 12);
651
656
  return Buffer.concat([head, out]);
@@ -658,7 +663,7 @@ class MongoServer {
658
663
  return doc.$db || fallback;
659
664
  }
660
665
 
661
- async _dispatch(cmd, doc) {
666
+ async _dispatch(cmd, doc, connId) {
662
667
 
663
668
  switch (cmd) {
664
669
  case 'hello':
@@ -671,6 +676,22 @@ class MongoServer {
671
676
  };
672
677
  case 'ping': return { ok: 1 };
673
678
  case 'buildInfo': return { ok: 1, version: '6.0.0-jsql-neo', gitVersion: 'jsql-neo', versionArray: [6, 0, 0, 0] };
679
+ case 'serverStatus': {
680
+ const uptimeMs = Math.max(0, Date.now() - this._startedAt);
681
+ return {
682
+ ok: 1,
683
+ host: this.host,
684
+ version: '6.0.0-jsql-neo',
685
+ process: 'mongod',
686
+ pid: process.pid,
687
+ uptime: Math.floor(uptimeMs / 1000),
688
+ uptimeMillis: uptimeMs,
689
+ localTime: new Date(),
690
+ connections: { current: this._sockets.size, available: 100000, totalCreated: this._sockets.size },
691
+ ok: 1,
692
+ };
693
+ }
694
+ case 'getCmdLineOpts': return { ok: 1, argv: ['jsql-neo'], parsed: {} };
674
695
  case 'getParameter': return { ok: 1 };
675
696
  case 'endSessions': return { ok: 1 };
676
697
  case 'listDatabases': {
@@ -874,7 +895,7 @@ class MongoServer {
874
895
  let cursorId = 0;
875
896
  if (rows.length > firstBatch.length) {
876
897
  cursorId = this._nextCursorId++;
877
- this._cursors.set(cursorId, { rows: rows.slice(firstBatch.length), ns, coll, db: this._dbOf(doc), batchSize, lastActive: Date.now() });
898
+ this._cursors.set(cursorId, { rows: rows.slice(firstBatch.length), ns, coll, db: this._dbOf(doc), batchSize, lastActive: Date.now(), connId });
878
899
  }
879
900
  return { ok: 1, cursor: { id: { $long: cursorId }, ns, firstBatch } };
880
901
  }
@@ -882,6 +903,8 @@ class MongoServer {
882
903
  const id = this._parseCursorId(doc.getMore);
883
904
  const cur = this._cursors.get(id);
884
905
  if (!cur) return { ok: 0, errmsg: 'cursor not found', code: 43 };
906
+ // #459:游标与创建它的连接绑定;其他连接 getMore 一律回 cursorNotFound(43)。
907
+ if (cur.connId !== connId) return { ok: 0, errmsg: 'cursor not found', code: 43 };
885
908
  // #428:空闲超时后游标已被清扫,再 getMore 回 cursorNotFound(43)。
886
909
  if (Date.now() - (cur.lastActive || 0) > this._cursorIdleTimeoutMs) {
887
910
  this._cursors.delete(id);
@@ -1034,6 +1057,16 @@ class MongoServer {
1034
1057
  const limit = Number(doc.limit) > 0 ? Math.trunc(Number(doc.limit)) : 0;
1035
1058
  return { ok: 1, n: limit > 0 ? Math.min(rows.length, limit) : rows.length };
1036
1059
  }
1060
+ case 'countDocuments': {
1061
+ // 官方驱动的 collection.countDocuments() 发送此命令;filter 字段名与 count 的 query 不同。
1062
+ const coll = String(doc.countDocuments);
1063
+ const engine = await this._ensureCollection(coll, this._dbOf(doc));
1064
+ let rows = await this._matching(engine, coll, doc.filter);
1065
+ const skip = typeof doc.skip === 'number' && doc.skip > 0 ? Math.trunc(doc.skip) : 0;
1066
+ if (skip > 0) rows = rows.slice(skip);
1067
+ const limit = Number(doc.limit) > 0 ? Math.trunc(Number(doc.limit)) : 0;
1068
+ return { ok: 1, n: limit > 0 ? Math.min(rows.length, limit) : rows.length };
1069
+ }
1037
1070
  case 'aggregate': {
1038
1071
  const coll = String(doc.aggregate);
1039
1072
  const engine = await this._ensureCollection(coll, this._dbOf(doc));
@@ -166,6 +166,9 @@ class MultiServer {
166
166
  socket.on('close', () => this._sockets.delete(socket));
167
167
  let first = Buffer.alloc(0);
168
168
  let routed = false;
169
+ // #456:Mongo 签名(opCode @ offset 12)需要前 16 字节才能校验;4–15 字节的
170
+ // 分片/短首包必须继续等待剩余字节,不能提前落到 Redis/MySQL/PG 兜底分支。
171
+ const MIN_SNIFF_BYTES = 16;
169
172
  // MySQL 客户端会先等服务器握手包,不主动发字节;超时后按 idleProtocol 处理
170
173
  const t = setTimeout(() => {
171
174
  if (routed) return;
@@ -177,7 +180,7 @@ class MultiServer {
177
180
  const sniff = (chunk) => {
178
181
  first = Buffer.concat([first, chunk]);
179
182
  if (routed) return;
180
- if (first.length < 4) return; // 等至少 4 字节再判断
183
+ if (first.length < MIN_SNIFF_BYTES) return;
181
184
  routed = true;
182
185
  clearTimeout(t);
183
186
  socket.removeListener('data', sniff);
@@ -630,7 +630,19 @@ class MysqlConnection {
630
630
  }
631
631
  case 0x11: this._handleChangeUser(body, cmdSeq); break; // COM_CHANGE_USER
632
632
  case 0x0e: this._send(okPacket()); break; // COM_PING
633
- case 0x1f: this._send(okPacket()); break; // COM_RESET_CONNECTION
633
+ case 0x1f: { // COM_RESET_CONNECTION —— #457:释放预处理句柄并复位会话状态
634
+ this._stmts.clear();
635
+ this._stmtSeq = 0;
636
+ this._inTransaction = false;
637
+ this.session.lastInsertId = 0;
638
+ this.session.rowCount = 0;
639
+ this.session.foundRows = 0;
640
+ this.session.sysvars = {};
641
+ this.session.charset = 'utf8mb4';
642
+ this.session.charsetNr = CHARSET_UTF8;
643
+ this._send(okPacket());
644
+ break;
645
+ }
634
646
  case 0x16: this._handleStmtPrepare(body); break; // COM_STMT_PREPARE
635
647
  case 0x17: this._handleStmtExecute(body); break; // COM_STMT_EXECUTE
636
648
  case 0x18: this._handleStmtSendLongData(body); break; // COM_STMT_SEND_LONG_DATA
package/lib/pg_server.js CHANGED
@@ -454,7 +454,7 @@ class PgConnection {
454
454
  }
455
455
  } catch (e) {
456
456
  this._send(buildErrorResponse(
457
- (e && e.sqlState) || 'XX000',
457
+ this._pgErrorCode(e),
458
458
  e && e.message ? e.message : String(e),
459
459
  'ERROR',
460
460
  { position: (e && e.position) ||
@@ -980,6 +980,7 @@ class PgConnection {
980
980
 
981
981
  _pgErrorCode(e) {
982
982
  if (!e) return 'XX000';
983
+ if (e.sqlState) return e.sqlState;
983
984
  if (/current transaction is aborted/i.test(String(e.message || ''))) return '25P02';
984
985
  const codeKey = e.code;
985
986
  const m = String(e.message || '');
@@ -987,7 +988,8 @@ class PgConnection {
987
988
  if (codeKey === 'ER_NO_SUCH_TABLE' || /Table .* doesn't exist/i.test(m)) return '42P01';
988
989
  if (codeKey === 'ER_TABLE_EXISTS' || /already exists/i.test(m)) return '42P07';
989
990
  if (codeKey === 'ER_DUP_ENTRY' || m.includes('ER_DUP_ENTRY') || /Duplicate entry/i.test(m)) return '23505';
990
- if (codeKey === 'ER_BAD_FIELD_ERROR' || /Unknown column/i.test(m)) return '42703';
991
+ // #465:引擎对缺列抛 "no such column: x"(非 MySQL "Unknown column"),同样归 undefined_column
992
+ if (codeKey === 'ER_BAD_FIELD_ERROR' || /Unknown column|no such column/i.test(m)) return '42703';
991
993
  if (codeKey === 'ER_CANT_DROP_FIELD' || /Cannot drop column/i.test(m)) return '428NF';
992
994
  if (codeKey === 'ER_DUP_FIELDNAME' || /Duplicate column name/i.test(m)) return '42711';
993
995
  if (codeKey === 'ER_BAD_NULL_ERROR' || /cannot be null/i.test(m)) return '23502';
@@ -996,6 +998,10 @@ class PgConnection {
996
998
  if (codeKey === 'ER_OUT_OF_RANGE' || /Out of range/i.test(m)) return '22003';
997
999
  if (codeKey === 'ER_NO_REFERENCED_ROW' || /foreign key/i.test(m)) return '23503';
998
1000
  if (codeKey === 'ER_SYNTAX_ERROR' || /syntax|Unexpected token|Expected/i.test(m)) return '42601';
1001
+ // #465:日期/时间值越界 → 22008;格式无法解析 → 22007(ER_INVALID_DATE 码 1292)
1002
+ if (/date\/time field value out of range|time value out of range/i.test(m)) return '22008';
1003
+ if (codeKey === 1292 && /date|time|datetime|timestamp/i.test(m)) return '22007';
1004
+ if (/Incorrect date|Invalid date|invalid datetime|invalid date format/i.test(m)) return '22007';
999
1005
  if (/Table .*(doesn't exist|does not exist)/i.test(m)) return '42P01';
1000
1006
  return 'XX000';
1001
1007
  }
@@ -363,8 +363,11 @@ class RedisServer {
363
363
  const dir = cmd === 'DECR' || cmd === 'DECRBY' ? -1 : 1;
364
364
  const v = this._get(args[0]);
365
365
  let n;
366
+ // #458:非字符串键(hash/list/set/zset)必须回 WRONGTYPE;
367
+ // `ERR value is not an integer` 仅用于键存在但值不是整数字符串。
368
+ if (v && v.type !== 'string') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
366
369
  if (!v) { n = 0; }
367
- else if (v.type === 'string' && /^-?\d+$/.test(v.val)) { n = parseInt(v.val, 10); }
370
+ else if (/^-?\d+$/.test(v.val)) { n = parseInt(v.val, 10); }
368
371
  else throw new Error('ERR value is not an integer or out of range');
369
372
  n += dir * by;
370
373
  this.db.set(args[0], { type: 'string', val: String(n), ttl: v ? v.ttl : null });
package/lib/sql.js CHANGED
@@ -566,7 +566,7 @@ const VARIANCE_FUNCS = new Set(['STDDEV', 'STD', 'STDDEV_POP', 'STDDEV_SAMP',
566
566
  // 新增任何"跟在 FROM 之后"的子句时,都要往这里加词。
567
567
  const NOT_ALIAS_WORDS = ['JOIN', 'LEFT', 'RIGHT', 'FULL', 'WHERE', 'GROUP', 'ORDER', 'LIMIT',
568
568
  'ON', 'HAVING', 'UNION', 'INNER', 'CROSS', 'OUTER', 'INTERSECT', 'EXCEPT',
569
- 'FETCH', 'RETURNING', 'WINDOW', 'OFFSET', 'FOR'];
569
+ 'FETCH', 'RETURNING', 'WINDOW', 'OFFSET', 'FOR', 'NATURAL'];
570
570
 
571
571
  class Parser {
572
572
  constructor(tokens) {
@@ -1702,7 +1702,7 @@ class Parser {
1702
1702
  // 裸 * 不带 starTable,仍展开全部已连接表。
1703
1703
  columns.push(expr.alias ? { expr: '*', starTable: expr.alias } : { expr: '*' });
1704
1704
  } else if (expr.type === 'aggregate') {
1705
- columns.push({ expr: expr.column, aggregate: expr.fn, column: expr.column, alias, scalar: expr, distinct: expr.distinct, separator: expr.separator, orderBy: expr.orderBy });
1705
+ columns.push({ expr: expr.column, aggregate: expr.fn, column: expr.column, alias, scalar: expr, distinct: expr.distinct, separator: expr.separator, orderBy: expr.orderBy, over: expr.over || null, window: !!expr.over });
1706
1706
  } else if (expr.type === 'column') {
1707
1707
  columns.push({ expr: expr.name, scalar: expr, alias });
1708
1708
  } else {
@@ -1984,6 +1984,9 @@ class Parser {
1984
1984
  const joins = [];
1985
1985
  while (true) {
1986
1986
  let type = null;
1987
+ let natural = false;
1988
+ // #468:NATURAL [INNER|LEFT|RIGHT|FULL] JOIN —— 记录标记,执行层按同名公共列等值连接
1989
+ if (this.isWord('NATURAL')) { this.next(); natural = true; }
1987
1990
  if (this.isKeyword('FULL')) {
1988
1991
  this.next();
1989
1992
  if (this.isKeyword('OUTER')) this.next();
@@ -2010,7 +2013,7 @@ class Parser {
2010
2013
  const item = this.parseFromItem();
2011
2014
  let on = null;
2012
2015
  if (this.isKeyword('ON')) { this.next(); on = this.parseBooleanExpr(); }
2013
- joins.push({ type, item, on });
2016
+ joins.push({ type, item, on, natural });
2014
2017
  }
2015
2018
  return { tables, joins };
2016
2019
  }
@@ -8277,6 +8280,19 @@ class SQLExecutor {
8277
8280
  });
8278
8281
  }
8279
8282
 
8283
+ /**
8284
+ * #471:标量子查询(单值上下文)必须恰好返回 1 列。
8285
+ * MySQL 在多列时抛 ERROR 1241 (ER_OPERAND_COLUMNS),而不是静默取首列。
8286
+ * 只用于标量取值路径;IN / EXISTS / = ANY 等多值上下文不适用(它们允许多列语义不同)。
8287
+ */
8288
+ _assertScalarSubqueryColumns(res) {
8289
+ if (!res) return;
8290
+ const n = Array.isArray(res.columns)
8291
+ ? res.columns.length
8292
+ : (res.rows && res.rows[0] && Array.isArray(res.rows[0]) ? res.rows[0].length : 0);
8293
+ if (n > 1) throw createError('ER_OPERAND_COLUMNS');
8294
+ }
8295
+
8280
8296
  // 物化表达式树中的子查询:IN (SELECT ...) -> expr.list
8281
8297
  async _materialize(expr) {
8282
8298
  if (!expr || typeof expr !== 'object') return;
@@ -8288,6 +8304,8 @@ class SQLExecutor {
8288
8304
  }
8289
8305
  if (expr.type === 'subquery') {
8290
8306
  const res = await this.executeSelect(expr.select);
8307
+ // #471:标量子查询返回多列必须报 1241(先于 1242 检查,与 MySQL 一致)
8308
+ this._assertScalarSubqueryColumns(res);
8291
8309
  // #258:标量子查询返回多行必须报 1242,不能静默取首行
8292
8310
  if (res.rows.length > 1) throw createError('ER_SUBSELECT_NO_1_ROW');
8293
8311
  expr._value = res.rows.length > 0 ? res.rows[0][0] : null;
@@ -8368,6 +8386,28 @@ class SQLExecutor {
8368
8386
  return out;
8369
8387
  }
8370
8388
 
8389
+ /**
8390
+ * #468:收集 NATURAL JOIN 两侧的同名公共列。优先取表 schema 键;
8391
+ * 子查询/虚拟行没有 schema 时回退到首行的裸列名。
8392
+ */
8393
+ _naturalSharedCols(leftSchema, rightSchema, leftRows, rightRows) {
8394
+ const namesOf = (schema, rows) => {
8395
+ if (schema && typeof schema === 'object') {
8396
+ return Object.keys(schema).filter(k => k !== '_softDelete');
8397
+ }
8398
+ const out = new Set();
8399
+ for (const r of (rows || []).slice(0, 1)) {
8400
+ for (const k of Object.keys(r)) {
8401
+ out.add(k.includes('.') ? k.slice(k.indexOf('.') + 1) : k);
8402
+ }
8403
+ }
8404
+ return [...out];
8405
+ };
8406
+ const L = new Set(namesOf(leftSchema, leftRows));
8407
+ const R = new Set(namesOf(rightSchema, rightRows));
8408
+ return [...L].filter(n => R.has(n));
8409
+ }
8410
+
8371
8411
  /**
8372
8412
  * 构造 WITH ROLLUP 的汇总行:把各组的原始行合并成一个"超级组",
8373
8413
  * 分组列不设值(投影时会取 null),聚合列则覆盖全部行。
@@ -9063,6 +9103,8 @@ class SQLExecutor {
9063
9103
  node._rowCount = res.rows.length;
9064
9104
  } else if (node.type === 'subquery') {
9065
9105
  const res = await this.executeSelect(node.select);
9106
+ // #471:标量子查询多列 → 1241(相关子查询与普通子查询行为一致)
9107
+ this._assertScalarSubqueryColumns(res);
9066
9108
  if (res.rows.length > 1) throw createError('ER_SUBSELECT_NO_1_ROW');
9067
9109
  node._value = res.rows.length > 0 ? res.rows[0][0] : null;
9068
9110
  } else if (node.type === 'in') {
@@ -9354,7 +9396,8 @@ class SQLExecutor {
9354
9396
  const fn = sc && sc.type === 'aggregate' ? String(sc.fn)
9355
9397
  : (sc && sc.type === 'func' ? String(sc.name).toUpperCase()
9356
9398
  : String(c.aggregate || '').toUpperCase());
9357
- specs.push({ col: c, spec: sc, over, fn, name: scalarColumnName(c) });
9399
+ specs.push({ col: c, spec: sc, over, fn, name: scalarColumnName(c),
9400
+ distinct: !!(sc && sc.distinct) || !!c.distinct });
9358
9401
  }
9359
9402
  if (specs.length === 0) return rows;
9360
9403
  const toNode = (x) => !x ? null : (typeof x === 'string' ? { type: 'column', name: x } : x);
@@ -9503,10 +9546,13 @@ class SQLExecutor {
9503
9546
  case 'SUM':
9504
9547
  case 'AVG':
9505
9548
  case 'MIN':
9506
- case 'MAX': {
9549
+ case 'MAX':
9550
+ case 'GROUP_CONCAT': {
9507
9551
  const f = frameIdx(pos);
9508
9552
  const slice = ordered.slice(f.start, f.end + 1).map(i => rows[i]);
9509
- v = this._aggValue(slice, w.fn, argNode, !!(w.spec && w.spec.distinct), w.spec && w.spec.separator);
9553
+ v = this._aggValue(slice, w.fn, argNode,
9554
+ !!(w.distinct || (w.spec && w.spec.distinct)),
9555
+ w.spec && w.spec.separator, w.spec && w.spec.orderBy);
9510
9556
  break;
9511
9557
  }
9512
9558
  default: v = null;
@@ -9660,9 +9706,25 @@ class SQLExecutor {
9660
9706
  const left = await this.executeSelect(leftStatement);
9661
9707
  const right = await this.executeSelect(statement.intersect.select);
9662
9708
  assertSetOpColumnCount(left, right);
9663
- const seen = new Set(right.rows.map(r => bigintJson.stringify(r)));
9664
- let out = left.rows.filter(r => seen.has(bigintJson.stringify(r)));
9665
- if (!statement.intersect.all) out = dedupeRows(out);
9709
+ let out;
9710
+ if (statement.intersect.all) {
9711
+ // #467:INTERSECT ALL 按多重集多重数取小值 min(nl, nr),保留左表行序。
9712
+ const rightCount = new Map();
9713
+ for (const r of right.rows) { const k = bigintJson.stringify(r); rightCount.set(k, (rightCount.get(k) || 0) + 1); }
9714
+ const used = new Map();
9715
+ out = left.rows.filter((r) => {
9716
+ const k = bigintJson.stringify(r);
9717
+ const avail = rightCount.get(k) || 0;
9718
+ const n = used.get(k) || 0;
9719
+ if (n >= avail) return false;
9720
+ used.set(k, n + 1);
9721
+ return true;
9722
+ });
9723
+ } else {
9724
+ const seen = new Set(right.rows.map(r => bigintJson.stringify(r)));
9725
+ out = left.rows.filter(r => seen.has(bigintJson.stringify(r)));
9726
+ out = dedupeRows(out);
9727
+ }
9666
9728
  out = this._finalizeSetOp(out, left.columns, statement);
9667
9729
  return { ok: true, type: 'select', columns: left.columns, rows: out, raw: out };
9668
9730
  }
@@ -9674,9 +9736,24 @@ class SQLExecutor {
9674
9736
  const left = await this.executeSelect(leftStatement);
9675
9737
  const right = await this.executeSelect(statement.except.select);
9676
9738
  assertSetOpColumnCount(left, right);
9677
- const seen = new Set(right.rows.map(r => bigintJson.stringify(r)));
9678
- let out = left.rows.filter(r => !seen.has(bigintJson.stringify(r)));
9679
- if (!statement.except.all) out = dedupeRows(out);
9739
+ let out;
9740
+ if (statement.except.all) {
9741
+ // #467:EXCEPT ALL 按多重集逐个相减 max(nl - nr, 0),保留左表行序。
9742
+ const rightCount = new Map();
9743
+ for (const r of right.rows) { const k = bigintJson.stringify(r); rightCount.set(k, (rightCount.get(k) || 0) + 1); }
9744
+ const consumed = new Map();
9745
+ out = left.rows.filter((r) => {
9746
+ const k = bigintJson.stringify(r);
9747
+ const rc = rightCount.get(k) || 0;
9748
+ const n = consumed.get(k) || 0;
9749
+ if (n < rc) { consumed.set(k, n + 1); return false; }
9750
+ return true;
9751
+ });
9752
+ } else {
9753
+ const seen = new Set(right.rows.map(r => bigintJson.stringify(r)));
9754
+ out = left.rows.filter(r => !seen.has(bigintJson.stringify(r)));
9755
+ out = dedupeRows(out);
9756
+ }
9680
9757
  out = this._finalizeSetOp(out, left.columns, statement);
9681
9758
  return { ok: true, type: 'select', columns: left.columns, rows: out, raw: out };
9682
9759
  }
@@ -9813,6 +9890,7 @@ class SQLExecutor {
9813
9890
  : (needPrefix || firstItem._virtualRows
9814
9891
  ? rowsAll.rows.map(r => this._prefixRow(r, firstPrefix))
9815
9892
  : rowsAll.rows);
9893
+ this._curNaturalJoins = [];
9816
9894
  for (const j of statement.from.joins) {
9817
9895
  // 虚拟行(递归 CTE 物化的派生表)要直接取行,不能当普通子查询执行
9818
9896
  const jVirtual = j.item._virtualRows ||
@@ -9829,9 +9907,24 @@ class SQLExecutor {
9829
9907
  : (j.item.subquery && j.item.subquery._virtualSource
9830
9908
  ? j.item.subquery._virtualSource
9831
9909
  : (j.item.subquery ? this._subQueryRows(rightRes) : rightRes.rows));
9832
- const rightRows = (j.item._virtualRows && !j.item.subquery)
9833
- ? jRaw
9834
- : jRaw.map(r => this._prefixRow(r, rightPrefix));
9910
+ // #445:JOIN 右侧的递归 CTE 虚拟行也要按别名加前缀副本(同时保留裸列名),
9911
+ // 否则 ON 条件与 SELECT 里的限定引用 h.id / h.depth 在未加前缀的虚拟行上
9912
+ // 解析不到 → INNER JOIN 匹配为空,递归只回锚点行。
9913
+ const rightRows = jRaw.map(r => this._prefixRow(r, rightPrefix));
9914
+
9915
+ // #468:NATURAL JOIN 按两侧同名公共列构造等值 ON 条件;无同名公共列时退化为 CROSS JOIN。
9916
+ if (j.natural) {
9917
+ const shared = this._naturalSharedCols(rowsAll && rowsAll.schema, rightRes.schema, rows, rightRows, firstPrefix, rightPrefix);
9918
+ let onNode = null;
9919
+ for (const col of shared) {
9920
+ const cond = { type: 'compare', op: '=',
9921
+ left: { type: 'column', name: firstPrefix + '.' + col },
9922
+ right: { type: 'column', name: rightPrefix + '.' + col } };
9923
+ onNode = onNode ? { type: 'and', left: onNode, right: cond } : cond;
9924
+ }
9925
+ j.on = onNode;
9926
+ (this._curNaturalJoins = this._curNaturalJoins || []).push({ leftPrefix: firstPrefix, rightPrefix, shared });
9927
+ }
9835
9928
 
9836
9929
  // 匹配(INNER/LEFT/RIGHT)
9837
9930
  if (j.type === 'cross' || (!j.on)) {
@@ -10034,14 +10127,16 @@ class SQLExecutor {
10034
10127
  }
10035
10128
 
10036
10129
  // 聚合输出(无 GROUP BY 时)
10037
- const hasCustomAgg = this.ctx && this.ctx.aggregates && statement.columns.some(c => c.scalar && c.scalar.type === 'func' && Object.prototype.hasOwnProperty.call(this.ctx.aggregates, String(c.scalar.name).toUpperCase()));
10130
+ // #466:带 OVER 的聚合是窗口函数,不是“整表塌缩成一行”的聚合,必须从整表聚合判定里排除
10131
+ const isWindowCol = (c) => !!(c.over || c.window || (c.scalar && c.scalar.over));
10132
+ const hasCustomAgg = this.ctx && this.ctx.aggregates && statement.columns.some(c => !isWindowCol(c) && c.scalar && c.scalar.type === 'func' && Object.prototype.hasOwnProperty.call(this.ctx.aggregates, String(c.scalar.name).toUpperCase()));
10038
10133
  // 注意:带 OVER 的聚合是窗口函数,不是“整表塌缩成一行”的聚合,必须排除
10039
10134
  // 无 GROUP BY 的整表聚合:顶层是聚合(AVG(x))、自定义聚合(total(x)),
10040
10135
  // 以及嵌套聚合(ROUND(AVG(x),1) —— 聚合藏在 scalar 的参数里,顶层 c.aggregate 为空)
10041
10136
  const hasNestedAgg = !statement.groupBy &&
10042
- statement.columns.some(c => (c.scalar && containsAggregateNode(c.scalar)) ||
10043
- (c.caseExpr && containsAggregateNode(c.caseExpr)));
10044
- if (!statement.groupBy && (statement.columns.some(c => c.aggregate && !c.window) || hasCustomAgg || hasNestedAgg)) {
10137
+ statement.columns.some(c => !isWindowCol(c) && ((c.scalar && containsAggregateNode(c.scalar)) ||
10138
+ (c.caseExpr && containsAggregateNode(c.caseExpr))));
10139
+ if (!statement.groupBy && (statement.columns.some(c => c.aggregate && !isWindowCol(c)) || hasCustomAgg || hasNestedAgg)) {
10045
10140
  const cols = statement.columns.map(c => scalarColumnName(c));
10046
10141
  const tableName2 = statement.from ? (statement.from.tables[0].table || null) : null;
10047
10142
  // HAVING 判定不通过时 rows 已为空,此时整表聚合也应为空,不能无条件补一行
@@ -10247,11 +10342,17 @@ class SQLExecutor {
10247
10342
  // JOIN 时:只使用带前缀的键,避免同一列重复。
10248
10343
  // 不能按裸名去重——右表同名列(如 b.id)会被丢弃,导致右表列全部丢失。
10249
10344
  if (hasJoins) {
10345
+ // #468:NATURAL JOIN 合并同名公共列 —— 右表公共列副本不重复输出。
10346
+ const naturalRight = new Set();
10347
+ for (const m of (this._curNaturalJoins || [])) {
10348
+ for (const col of m.shared) naturalRight.add(m.rightPrefix + '.' + col);
10349
+ }
10250
10350
  const seen = new Set();
10251
10351
  cols = [];
10252
10352
  for (const r of rows) {
10253
10353
  for (const k of Object.keys(r)) {
10254
10354
  if (!k.includes('.')) continue; // 只取带前缀的键
10355
+ if (naturalRight.has(k)) continue;
10255
10356
  if (!seen.has(k)) { seen.add(k); cols.push(k); }
10256
10357
  }
10257
10358
  }
@@ -10265,6 +10366,13 @@ class SQLExecutor {
10265
10366
  cols = allKeys;
10266
10367
  }
10267
10368
  }
10369
+ // #468:NATURAL JOIN 左表公共列副本输出为裸列名(与标准一致),不再带表前缀。
10370
+ for (const m of (this._curNaturalJoins || [])) {
10371
+ for (const col of m.shared) {
10372
+ const li = cols.indexOf(m.leftPrefix + '.' + col);
10373
+ if (li >= 0) cols[li] = col;
10374
+ }
10375
+ }
10268
10376
  // 物化派生表(递归 CTE 结果)的行同时带 'c.n' 与 'n':前者供限定引用、
10269
10377
  // 后者供非限定引用。SELECT * 会把两者都输出,同一列重复。
10270
10378
  // 按声明的列去重,优先取带前缀的那个键。
@@ -10298,10 +10406,16 @@ class SQLExecutor {
10298
10406
  starKeys = Object.keys(schema).filter(k => k !== '_softDelete');
10299
10407
  } else if (hasJoins2) {
10300
10408
  // JOIN 时:保留所有带前缀的键,不按裸名去重(否则右表同名列丢失)
10409
+ // #468:NATURAL JOIN 合并同名公共列 —— 右表的公共列副本不重复输出,只保留左表副本。
10410
+ const naturalRight = new Set();
10411
+ for (const m of (this._curNaturalJoins || [])) {
10412
+ for (const col of m.shared) naturalRight.add(m.rightPrefix + '.' + col);
10413
+ }
10301
10414
  const seenK = new Set();
10302
10415
  for (const r of rows) {
10303
10416
  for (const k of Object.keys(r)) {
10304
10417
  if (!k.includes('.')) continue;
10418
+ if (naturalRight.has(k)) continue;
10305
10419
  if (!seenK.has(k)) { seenK.add(k); starKeys.push(k); }
10306
10420
  }
10307
10421
  }
@@ -10895,17 +11009,20 @@ async function executeSQL(engine, sql, paramsOrOpts, opts = {}) {
10895
11009
  // 再被 buildResultEnvelope 读 .type 抛裸 TypeError。纯空白语句早就是空结果,
10896
11010
  // 这里把纯注释统一成同一条路。
10897
11011
  statements = statements.filter((s0) => tokenize(s0).some((t) => t.type !== 'eof'));
11012
+ // 多语句门禁:maxStatements 是显式语句条数上限,同时也是放行多条语句的开关;
11013
+ // 未显式传 maxStatements 时由安全模式的 stacked 门按单语句拦截。
11014
+ // allowStacked: true 是等价显式放行。
10898
11015
  if (opts.maxStatements != null && statements.length > opts.maxStatements) {
10899
11016
  throw new Error(`too many statements (${statements.length} > ${opts.maxStatements})`);
10900
11017
  }
10901
11018
  if (opts.safety !== false) {
10902
11019
  // 堆叠 SQL(分号分隔多语句):经典注入/误操作向量,默认拦截。
10903
- // 需要多语句调用方显式传 { allowStacked: true }(mysql 兼容层在
10904
- // multipleStatements:true 时会这么做)。
10905
- if (statements.length > 1 && opts.allowStacked !== true) {
11020
+ // 需要多语句调用方显式传 { allowStacked: true } 或 { maxStatements: <n> }
11021
+ // (mysql 兼容层在 multipleStatements:true 时会传 allowStacked)。
11022
+ if (statements.length > 1 && opts.allowStacked !== true && opts.maxStatements == null) {
10906
11023
  throw new Error(
10907
11024
  `SQL statement blocked by security policy: stacked statements (${statements.length} statements in one call). ` +
10908
- `Pass { allowStacked: true } to allow multiple statements.`
11025
+ `Pass { maxStatements: <n> } or { allowStacked: true } to allow multiple statements.`
10909
11026
  );
10910
11027
  }
10911
11028
  for (const stmtSql of statements) {
package/lib/table.js CHANGED
@@ -1118,15 +1118,36 @@ class Table {
1118
1118
 
1119
1119
  restore(query = {}) {
1120
1120
  if (!this._softDelete) throw createError('ER_NOT_SUPPORTED', 'Soft delete is not enabled');
1121
- const matched = this._applyFilter(this._rows, { ...query, _deleted: true });
1121
+ // #450:restore 要匹配的恰恰是被可见性过滤跳过的 _deleted 行;
1122
+ // _applyFilter 在软删除模式下先剔除所有 _deleted 行,走它恒匹配为空。
1123
+ // 这里直接在全量行上按 query 匹配软删除行,再对称地撤下索引、清标记、重新登记。
1124
+ const match = this._compileMatcher(query);
1125
+ const matched = [];
1126
+ for (const row of this._rows) {
1127
+ if (!row._deleted) continue;
1128
+ if (match(row)) matched.push(row);
1129
+ }
1130
+ let count = 0;
1122
1131
  for (const row of matched) {
1123
1132
  const index = this._rows.indexOf(row);
1124
- if (index !== -1) {
1125
- delete this._rows[index]._deleted;
1126
- delete this._rows[index]._deletedAt;
1133
+ if (index === -1) continue;
1134
+ this._removeFromIndexes(index, row);
1135
+ delete row._deleted;
1136
+ delete row._deletedAt;
1137
+ this._addToIndexes(index, row);
1138
+ count++;
1139
+ }
1140
+ if (count > 0) {
1141
+ this._dirty = true;
1142
+ this._db._markDirty(this._name);
1143
+ for (const hook of this._hooks.afterRemove) {
1144
+ hook(query, count);
1127
1145
  }
1146
+ this._db._emitChange('restore', this._name, { query, count });
1147
+ this._db._walLogUpsert(this._name, matched);
1148
+ for (const row of matched) this._markRowDirty(row);
1128
1149
  }
1129
- return matched.length;
1150
+ return count;
1130
1151
  }
1131
1152
 
1132
1153
  truncate() {
@@ -1368,6 +1389,22 @@ class Table {
1368
1389
  };
1369
1390
  }
1370
1391
 
1392
+ /**
1393
+ * #451:落盘用的 schema 快照。复合唯一组不落在任何单列定义里,
1394
+ * 必须随 schema 一起持久化(meta / jsql 头 / legacy 快照),
1395
+ * 否则重启后 _uniqueIndexes 为空、重复组合键被静默接受。
1396
+ * 重载时构造器从 schema.__uniqueGroups__ 重建 _uniqueIndexes。
1397
+ */
1398
+ _persistedSchema() {
1399
+ const out = { ...this._schema };
1400
+ const groups = (this._uniqueIndexes || [])
1401
+ .filter(u => u.columns && u.columns.length >= 2 && u.name !== 'PRIMARY')
1402
+ .map(u => u.columns.slice());
1403
+ if (groups.length > 0) out.__uniqueGroups__ = groups;
1404
+ else delete out.__uniqueGroups__;
1405
+ return out;
1406
+ }
1407
+
1371
1408
  selectInto(newTableName, newSchema, query = {}) {
1372
1409
  const rows = this._applyFilterOptimized(this._getVisibleRows(), query);
1373
1410
  this._db.createTable(newTableName, newSchema);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.8.26",
3
+ "version": "6.8.27",
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,7 +52,7 @@
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 && node test/issue-255-270.test.js && node test/issue-253-269.test.js && node test/issue-280-310.test.js && node test/issue-272-311.test.js && node test/issue-279-306.test.js && node test/issue-271-283.test.js && node test/issue-265-307.test.js && node test/issue-258-300.test.js && node test/issue-247-295-277.test.js && node test/issue-322-325.test.js && node test/issue-357-365.test.js && node test/issue-372-387.test.js && node test/issue-383-402.test.js && node test/issue-369-394.test.js && node test/issue-352-386.test.js && node test/issue-395-430.test.js && node test/btree.test.js && node test/regress-5.1.0.js && node test/native-multi-instance.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/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.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/coverage.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/savepoint.test.js && node test/alter-table.test.js && node test/identifier-keywords.test.js && node test/null-semantics.test.js && node test/sql-semantics.test.js && node test/filter-compile.test.js && node test/compat-v1.test.js && node test/issue-327-418.test.js && node test/issue-341-419.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 && node test/issue-253-269.test.js && node test/issue-280-310.test.js && node test/issue-272-311.test.js && node test/issue-279-306.test.js && node test/issue-271-283.test.js && node test/issue-265-307.test.js && node test/issue-258-300.test.js && node test/issue-247-295-277.test.js && node test/issue-322-325.test.js && node test/issue-357-365.test.js && node test/issue-372-387.test.js && node test/issue-383-402.test.js && node test/issue-369-394.test.js && node test/issue-352-386.test.js && node test/issue-395-430.test.js && node test/btree.test.js && node test/regress-5.1.0.js && node test/native-multi-instance.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/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.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/coverage.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/savepoint.test.js && node test/alter-table.test.js && node test/identifier-keywords.test.js && node test/null-semantics.test.js && node test/sql-semantics.test.js && node test/filter-compile.test.js && node test/compat-v1.test.js && node test/issue-327-418.test.js && node test/issue-341-419.test.js && node test/issue-450-454.test.js && node test/issue-445-449.test.js && node test/issue-460-464.test.js && node test/issue-455-459.test.js && node test/issue-465-469.test.js && node test/issue-471.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",