jsql-neo 6.8.25 → 6.8.26

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.
@@ -20,6 +20,13 @@ const net = require('net');
20
20
  const fs = require('fs');
21
21
  const path = require('path');
22
22
 
23
+ // #401:出站分数必须用 Redis 词法 ±inf,而不是 JS 的 Infinity/-Infinity
24
+ function formatScore(v) {
25
+ if (v === Infinity) return 'inf';
26
+ if (v === -Infinity) return '-inf';
27
+ return String(v);
28
+ }
29
+
23
30
  // Redis score/increment 必须是完整合法浮点数;parseFloat 会吞掉尾随垃圾("1abc" → 1)
24
31
  function parseRedisFloat(raw) {
25
32
  const s = String(raw).trim();
@@ -124,6 +131,7 @@ class RedisServer {
124
131
  this._selected = new WeakMap(); // socket → db index
125
132
  this.snapshotTimer = null;
126
133
  this._authedSockets = new WeakMap();
134
+ this._clients = new Set(); // #400 INFO connected_clients
127
135
  this._load();
128
136
  }
129
137
 
@@ -254,8 +262,13 @@ class RedisServer {
254
262
  if (sig >= 0 && args.length < sig) throw new Error(`ERR wrong number of arguments for '${cmd}' command`);
255
263
  if (sig < 0 && args.length < -sig) throw new Error(`ERR wrong number of arguments for '${cmd}' command`);
256
264
  switch (cmd) {
257
- case 'PING': return args.length ? args[0] : 'PONG';
258
- case 'ECHO': return args[0];
265
+ case 'PING':
266
+ // #402:PING 只接受 0/1 个参数,多传必须报错而不是静默取第一个
267
+ if (args.length > 1) throw new Error(`ERR wrong number of arguments for '${cmd}' command`);
268
+ return args.length ? args[0] : 'PONG';
269
+ case 'ECHO':
270
+ if (args.length !== 1) throw new Error(`ERR wrong number of arguments for '${cmd}' command`);
271
+ return args[0];
259
272
  case 'AUTH':
260
273
  if (!this.password) throw new Error('ERR Client sent AUTH, but no password is set');
261
274
  if (args[0] !== this.password) throw new Error('ERR invalid password');
@@ -654,7 +667,7 @@ class RedisServer {
654
667
  const out = [];
655
668
  for (let i = from; i <= to && i < entries.length; i++) {
656
669
  out.push(entries[i][0]);
657
- if (withScores) out.push(entries[i][1]);
670
+ if (withScores) out.push(formatScore(entries[i][1]));
658
671
  }
659
672
  return out;
660
673
  }
@@ -671,7 +684,7 @@ class RedisServer {
671
684
  const out = [];
672
685
  for (let i = from; i <= to && i < entries.length; i++) {
673
686
  out.push(entries[i][0]);
674
- if (withScores) out.push(entries[i][1]);
687
+ if (withScores) out.push(formatScore(entries[i][1]));
675
688
  }
676
689
  return out;
677
690
  }
@@ -680,7 +693,7 @@ class RedisServer {
680
693
  if (v && v.type !== 'zset') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
681
694
  if (!v || !Object.prototype.hasOwnProperty.call(v.val, args[1])) return null;
682
695
  // ZSCORE 的分数恒为 bulk string(含整数分数),不能落进 integer reply(#67)
683
- return String(v.val[args[1]]);
696
+ return formatScore(v.val[args[1]]);
684
697
  }
685
698
  case 'ZCARD': {
686
699
  const v = this._get(args[0]);
@@ -715,7 +728,7 @@ class RedisServer {
715
728
  this.db.set(key, { type: 'zset', val: zset, ttl: v ? v.ttl : null });
716
729
  this._scheduleSnapshot();
717
730
  // 同 ZSCORE:分数用 bulk string 回复(#67)
718
- return String(zset[member]);
731
+ return formatScore(zset[member]);
719
732
  }
720
733
  case 'MSET': {
721
734
  const rest = args;
@@ -725,10 +738,15 @@ class RedisServer {
725
738
  return 'OK';
726
739
  }
727
740
  case 'MGET': {
728
- return args.map((k) => {
741
+ // #395:与 Redis 7 一致 —— 任一现存键不是 string 类型,整条命令回
742
+ // WRONGTYPE(而不是把该槽位静默填 nil 与缺失键混淆)。
743
+ const out = [];
744
+ for (const k of args) {
729
745
  const v = this._get(k);
730
- return v && v.type === 'string' ? v.val : null;
731
- });
746
+ if (v && v.type !== 'string') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
747
+ out.push(v ? v.val : null);
748
+ }
749
+ return out;
732
750
  }
733
751
  case 'DBSIZE': {
734
752
  let count = 0;
@@ -748,16 +766,17 @@ class RedisServer {
748
766
  this._scheduleSnapshot();
749
767
  return 'OK';
750
768
  case 'INFO': {
751
- const lines = [
752
- '# Server',
753
- 'redis_version:7.0.0',
754
- 'jsql_neo_version:' + require('../package.json').version,
755
- '# Memory',
756
- 'used_memory:' + JSON.stringify([...this.db.values()]).length,
757
- '# Stats',
758
- 'db_size:' + this.db.size,
759
- 'connected_clients:1',
760
- ];
769
+ // #400:按 section 过滤,used_memory 用字节数,connected_clients 用真实连接数
770
+ const sections = {
771
+ server: ['# Server', 'redis_version:7.0.0', 'jsql_neo_version:' + require('../package.json').version],
772
+ memory: ['# Memory', 'used_memory:' + Buffer.byteLength(JSON.stringify([...this.db.entries()]), 'utf8')],
773
+ stats: ['# Stats', 'db_size:' + this.db.size, 'connected_clients:' + (this._clients ? this._clients.size : 0)],
774
+ keyspace: ['# Keyspace', `db${this.selected || 0}:keys=${this.db.size},expires=0`],
775
+ };
776
+ const wanted = args[0] ? String(args[0]).toLowerCase() : null;
777
+ const keys = wanted && sections[wanted] ? [wanted] : Object.keys(sections);
778
+ const lines = [];
779
+ for (const k of keys) lines.push(...sections[k]);
761
780
  return lines.join('\r\n') + '\r\n';
762
781
  }
763
782
  case 'QUIT': return 'OK';
@@ -782,6 +801,8 @@ class RedisServer {
782
801
  // 转成字符串再按字符切片会把多字节 UTF-8(中文等)截断。
783
802
  let buf = Buffer.isBuffer(existing) ? existing : Buffer.from(String(existing || ''), 'utf8');
784
803
  this._authedSockets.set(socket, false);
804
+ this._clients.add(socket);
805
+ socket.on('close', () => this._clients.delete(socket));
785
806
 
786
807
  const drain = () => {
787
808
  for (;;) {
package/lib/sql.js CHANGED
@@ -246,6 +246,15 @@ function parseHexIntegerLiteral(hexStr) {
246
246
  return b <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(b) : b;
247
247
  }
248
248
 
249
+ // #341:MySQL 口径下 `--` 只有后跟空白/控制字符(或位于行尾)才构成注释 opener;
250
+ // `1--5` 中的 `--5` 不是注释,应按两个减号运算符切分(1 - (-5) = 6)。
251
+ function dashDashStartsComment(sql, i) {
252
+ const ch = sql[i + 2];
253
+ if (ch === undefined) return true;
254
+ const code = ch.charCodeAt(0);
255
+ return ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r' || code < 32;
256
+ }
257
+
249
258
  function tokenize(sql) {
250
259
  const tokens = [];
251
260
  let i = 0;
@@ -270,7 +279,7 @@ function tokenize(sql) {
270
279
 
271
280
  if (c === ' ' || c === '\t' || c === '\n' || c === '\r') { i++; continue; }
272
281
 
273
- if (c === '-' && sql[i + 1] === '-') {
282
+ if (c === '-' && sql[i + 1] === '-' && dashDashStartsComment(sql, i)) {
274
283
  while (i < n && sql[i] !== '\n') i++;
275
284
  continue;
276
285
  }
@@ -283,8 +292,14 @@ function tokenize(sql) {
283
292
  }
284
293
  if (c === '#' || (c === '/' && sql[i + 1] === '*')) {
285
294
  if (c === '#') { while (i < n && sql[i] !== '\n') i++; continue; }
295
+ const start = i;
286
296
  i += 2;
287
- while (i + 1 < n && !(sql[i] === '*' && sql[i + 1] === '/')) i++;
297
+ let closed = false;
298
+ while (i + 1 < n) {
299
+ if (sql[i] === '*' && sql[i + 1] === '/') { closed = true; break; }
300
+ i++;
301
+ }
302
+ if (!closed) throw new Error(`Unterminated block comment at position ${start}`);
288
303
  i += 2;
289
304
  continue;
290
305
  }
@@ -440,10 +455,21 @@ function tokenize(sql) {
440
455
  }
441
456
 
442
457
  if (c === '`') {
458
+ // #346:反引号内的 `` 是转义的单反引号(MySQL 语义),不能当成标识符结束。
443
459
  let j = i + 1;
444
- while (j < n && sql[j] !== '`') j++;
445
- if (j >= n) throw new Error(`Unterminated backtick-quoted identifier at position ${i}`);
446
- tokens.push(new SQLToken('ident', sql.slice(i + 1, j), i));
460
+ let val = '';
461
+ let closed = false;
462
+ while (j < n) {
463
+ if (sql[j] === '`') {
464
+ if (sql[j + 1] === '`') { val += '`'; j += 2; continue; }
465
+ closed = true;
466
+ break;
467
+ }
468
+ val += sql[j];
469
+ j++;
470
+ }
471
+ if (!closed) throw new Error(`Unterminated backtick-quoted identifier at position ${i}`);
472
+ tokens.push(new SQLToken('ident', val, i));
447
473
  i = j + 1;
448
474
  continue;
449
475
  }
@@ -629,7 +655,12 @@ class Parser {
629
655
  this.optionalTailSemicolon();
630
656
  return { type: 'releaseSavepoint', name: nm.value };
631
657
  }
632
- throw new Error(`Expected SQL statement, got '${t.value}'`);
658
+ {
659
+ // #377:把 token 位置带进错误对象,PG 服务端可据此回 ErrorResponse 的 P 字段
660
+ const err = new Error(`Expected SQL statement, got '${t.value}'`);
661
+ err.position = (typeof t.pos === 'number' ? t.pos : 0) + 1;
662
+ throw err;
663
+ }
633
664
  }
634
665
 
635
666
  switch (t.value) {
@@ -930,6 +961,9 @@ class Parser {
930
961
  // #209/#214:保留 BIGINT / NUMERIC 的原始类型标记,供 MySQL/PG 线协议通告正确类型
931
962
  if (type === 'bigint' || type === 'bigserial') def.intType = 'bigint';
932
963
  if (type === 'numeric' || type === 'decimal') def.numericType = 'numeric';
964
+ // #371:保留列声明的原始类型名(smallint/timestamptz/bytea/uuid/real/json/array 等),
965
+ // 供 PG 线协议通告正确的类型 OID 与 typlen;其它层忽略该字段。
966
+ def.rawType = type;
933
967
  // JSON / JSONB 列保留原始标记,供数据层校验非法 JSON({bad json 这类字符串会被 JSON.parse 拒绝)
934
968
  if (type === 'json' || type === 'jsonb') def.jsonType = true;
935
969
  if (/^(BIG)?SERIAL$/i.test(typeRaw)) { def.autoIncrement = true; def.required = true; }
@@ -1478,6 +1512,11 @@ class Parser {
1478
1512
  this.expect('op', '(');
1479
1513
  const select = this.parseSelect();
1480
1514
  this.expect('op', ')');
1515
+ // #360:MySQL 对同名 CTE 报 "Duplicate CTE name",此前后定义静默遮蔽前一个。
1516
+ const cteName = String(nameTok.value);
1517
+ if (ctes.some((c0) => String(c0.name).toLowerCase() === cteName.toLowerCase())) {
1518
+ throw new Error(`Duplicate CTE name '${cteName}'`);
1519
+ }
1481
1520
  ctes.push({ name: nameTok.value, columns, select, recursive });
1482
1521
  if (this.peek().type === 'op' && this.peek().value === ',') { this.next(); continue; }
1483
1522
  break;
@@ -1567,7 +1606,11 @@ class Parser {
1567
1606
  this.next();
1568
1607
  end = bound();
1569
1608
  } else {
1609
+ // #344:简写帧(只给起始 bound)按 SQL 标准缺省结束 bound 为 CURRENT ROW,
1610
+ // 与 ROWS BETWEEN <start> AND CURRENT ROW 等价;此前 end=null 被执行层
1611
+ // 当成分区末行,累计求和恒为全分区总和。
1570
1612
  start = bound();
1613
+ end = { type: 'currentRow' };
1571
1614
  }
1572
1615
  return { unit, start, end };
1573
1616
  }
@@ -1655,7 +1698,9 @@ class Parser {
1655
1698
  let alias = null;
1656
1699
  alias = this.parseOptionalAlias();
1657
1700
  if (expr.type === 'star') {
1658
- columns.push({ expr: '*' });
1701
+ // #419:保留表别名限定符(o.*),执行层只展开该表的列;
1702
+ // 裸 * 不带 starTable,仍展开全部已连接表。
1703
+ columns.push(expr.alias ? { expr: '*', starTable: expr.alias } : { expr: '*' });
1659
1704
  } else if (expr.type === 'aggregate') {
1660
1705
  columns.push({ expr: expr.column, aggregate: expr.fn, column: expr.column, alias, scalar: expr, distinct: expr.distinct, separator: expr.separator, orderBy: expr.orderBy });
1661
1706
  } else if (expr.type === 'column') {
@@ -6681,12 +6726,28 @@ class SQLExecutor {
6681
6726
  if (prev.primaryKey && !def.primaryKey) { def.primaryKey = true; def.unique = true; }
6682
6727
  }
6683
6728
  table._schema[op.column] = def;
6729
+ // #359:MODIFY COLUMN 直接改 _schema,绕过了 Table 的默认值登记。
6730
+ // 去掉 DEFAULT 时 _defaults 仍留着旧值,后续 INSERT 继续写入已删除的默认值。
6731
+ if (def && def.default !== undefined) table._defaults[op.column] = def.default;
6732
+ else delete table._defaults[op.column];
6733
+ // #359:MODIFY/CHANGE COLUMN 用新定义整体替换旧定义,旧 CHECK 登记必须
6734
+ // 先清掉再按新定义重建;否则已撤销的约束继续拦截新写入(如去掉
6735
+ // CHECK age >= 0 后插入 -5 仍被拒)。
6736
+ table._checkConstraints = (table._checkConstraints || []).filter(c => c.field !== op.column);
6737
+ const checkTarget = op.newColumn !== op.column ? op.newColumn : op.column;
6738
+ if (typeof table._registerChecks === 'function') table._registerChecks(checkTarget, def);
6684
6739
  if (op.newColumn !== op.column) {
6685
6740
  table._schema[op.newColumn] = def;
6686
6741
  delete table._schema[op.column];
6742
+ if (table._defaults[op.column] !== undefined) {
6743
+ table._defaults[op.newColumn] = table._defaults[op.column];
6744
+ delete table._defaults[op.column];
6745
+ }
6687
6746
  for (const row of table._rows) {
6688
6747
  if (op.column in row) { row[op.newColumn] = row[op.column]; delete row[op.column]; }
6689
6748
  }
6749
+ // #357:CHANGE COLUMN 改名同样要改写 CHECK 表达式
6750
+ if (typeof table._rewriteColumnRefs === 'function') table._rewriteColumnRefs(op.column, op.newColumn);
6690
6751
  }
6691
6752
  break;
6692
6753
  }
@@ -6754,6 +6815,16 @@ class SQLExecutor {
6754
6815
  for (const k of Object.keys(row)) delete row[k];
6755
6816
  Object.assign(row, rebuilt);
6756
6817
  }
6818
+ // #357:列改名后 DEFAULT 登记必须随列一起迁移;否则新行取不到默认值,
6819
+ // 该列被静默写 NULL(对照 Table.renameColumn() 的 defaults 迁移口径)。
6820
+ if (table._defaults[oldCol] !== undefined) {
6821
+ table._defaults[newCol] = table._defaults[oldCol];
6822
+ delete table._defaults[oldCol];
6823
+ }
6824
+ // #357:ALTER ... RENAME COLUMN 直接重建 _schema,既没同步 CHECK 的
6825
+ // 列归属,也没改写表达式文本 —— 约束继续检查旧列名(该列已不存在)→ 静默失效。
6826
+ for (const c of table._checkConstraints || []) if (c.field === oldCol) c.field = newCol;
6827
+ if (typeof table._rewriteColumnRefs === 'function') table._rewriteColumnRefs(oldCol, newCol);
6757
6828
  break;
6758
6829
  }
6759
6830
  case 'dropIndex': {
@@ -6848,7 +6919,10 @@ class SQLExecutor {
6848
6919
  if (res.columns.length !== targetCols.length) {
6849
6920
  throw createError('ER_WRONG_VALUE_COUNT_ON_ROW', 1);
6850
6921
  }
6851
- const cols = statement.columns && statement.columns.length ? statement.columns : res.columns;
6922
+ // #390:无显式目标列清单时,SELECT 输出按**位置**依次赋给目标表列,
6923
+ // 而不是按 SELECT 别名/表达式名键控(表达式投影列在目标 schema 中
6924
+ // 不存在,此前被静默写成 NULL)。
6925
+ const cols = statement.columns && statement.columns.length ? statement.columns : targetCols;
6852
6926
  dataRows = res.rows.map(arr => {
6853
6927
  const row = {};
6854
6928
  cols.forEach((c, i) => { row[c] = arr[i]; });
@@ -9396,7 +9470,15 @@ class SQLExecutor {
9396
9470
  case 'NTILE': {
9397
9471
  const n = w.spec && w.spec.args && w.spec.args[0] ? Number(resolveOperand(w.spec.args[0], rows[rowIdx], this.ctx)) : 1;
9398
9472
  const bucketsN = Math.max(1, Math.floor(n) || 1);
9399
- v = Math.min(bucketsN, Math.floor((pos * bucketsN) / ordered.length) + 1);
9473
+ // #343:标准 NTILE 是「前 len % n 桶各多一行」,不是等比例切分。
9474
+ // 等比例在 n > len 时会把桶号跳着用完(5 行分 10 桶 → 1,3,5,7,9)。
9475
+ const rowsN = ordered.length;
9476
+ const base = Math.floor(rowsN / bucketsN);
9477
+ const rem = rowsN % bucketsN;
9478
+ const wide = base + 1;
9479
+ if (pos < rem * wide) v = Math.floor(pos / wide) + 1;
9480
+ else v = base === 0 ? rowsN : rem + Math.floor((pos - rem * wide) / base) + 1;
9481
+ v = Math.min(bucketsN, v);
9400
9482
  break;
9401
9483
  }
9402
9484
  case 'LAG':
@@ -10194,6 +10276,16 @@ class SQLExecutor {
10194
10276
  return (a && String(a).includes('.')) ? String(a) : `${fi.alias || fi.table}.${a}`;
10195
10277
  });
10196
10278
  }
10279
+ // #419:限定星号 o.* 只展开该表(或其别名)的列;行键带前缀时按前缀过滤。
10280
+ const starTable0 = statement.columns[0].starTable;
10281
+ if (starTable0) {
10282
+ const q0 = String(starTable0).toLowerCase();
10283
+ const dotted0 = cols.filter(k => String(k).includes('.'));
10284
+ if (dotted0.length) {
10285
+ cols = cols.filter(k => !String(k).includes('.') ||
10286
+ String(k).slice(0, String(k).indexOf('.')).toLowerCase() === q0);
10287
+ }
10288
+ }
10197
10289
  return { ok: true, type: 'select', table: tableName, columns: cols, rows: rows.map(r => cols.map(c => (r[c] !== undefined ? r[c] : r[String(c).slice(String(c).indexOf('.') + 1)]))), raw: rows };
10198
10290
  }
10199
10291
 
@@ -10222,9 +10314,26 @@ class SQLExecutor {
10222
10314
  }
10223
10315
  }
10224
10316
  }
10317
+ // #419:限定星号 o.* 只取前缀为该表/别名的行键
10318
+ const qualifiedKeys = (q) => {
10319
+ const ql = String(q).toLowerCase();
10320
+ const seenQ = new Set();
10321
+ const outQ = [];
10322
+ for (const r of rows) {
10323
+ for (const k of Object.keys(r)) {
10324
+ if (!k.includes('.')) continue;
10325
+ if (k.slice(0, k.indexOf('.')).toLowerCase() === ql && !seenQ.has(k)) {
10326
+ seenQ.add(k); outQ.push(k);
10327
+ }
10328
+ }
10329
+ }
10330
+ return outQ;
10331
+ };
10332
+ const starKeyLists = statement.columns.map(c =>
10333
+ c.expr === '*' ? (c.starTable ? qualifiedKeys(c.starTable) : starKeys) : null);
10225
10334
  const cols = [];
10226
10335
  for (const c of statement.columns) {
10227
- if (c.expr === '*') { for (const k of starKeys) cols.push(k.includes('.') ? k.slice(k.indexOf('.') + 1) : k); }
10336
+ if (c.expr === '*') { for (const k of (c.starTable ? qualifiedKeys(c.starTable) : starKeys)) cols.push(k.includes('.') ? k.slice(k.indexOf('.') + 1) : k); }
10228
10337
  else cols.push(scalarColumnName(c));
10229
10338
  }
10230
10339
  /*
@@ -10261,7 +10370,7 @@ class SQLExecutor {
10261
10370
  for (let ci = 0; ci < colGetters.length; ci++) {
10262
10371
  const g = colGetters[ci];
10263
10372
  if (g === null) {
10264
- for (const k of starKeys) out.push(r[k] !== undefined ? r[k] : r[String(k).slice(String(k).indexOf('.') + 1)]);
10373
+ for (const k of starKeyLists[ci]) out.push(r[k] !== undefined ? r[k] : r[String(k).slice(String(k).indexOf('.') + 1)]);
10265
10374
  } else out.push(g(r));
10266
10375
  }
10267
10376
  return out;
@@ -10332,7 +10441,7 @@ function splitStatements(sql, opts = {}) {
10332
10441
  while (i < n) {
10333
10442
  const c = sql[i];
10334
10443
  if (c === "'" || c === '"' || c === '`') { i = skipQuoted(sql, i, c); continue; }
10335
- if (c === '-' && sql[i + 1] === '-') {
10444
+ if (c === '-' && sql[i + 1] === '-' && dashDashStartsComment(sql, i)) {
10336
10445
  // 行注释:丢弃注释文本本身(与原实现一致),保留其后的换行
10337
10446
  take(i);
10338
10447
  while (i < n && sql[i] !== '\n') i++;
@@ -10388,7 +10497,7 @@ function hasComments(sql) {
10388
10497
  }
10389
10498
  if (c === "'" || c === '"') { inStr = c; i++; continue; }
10390
10499
  if (c === '`') { i++; while (i < sql.length && sql[i] !== '`') i++; i++; continue; }
10391
- if (c === '-' && sql[i + 1] === '-') return true;
10500
+ if (c === '-' && sql[i + 1] === '-' && dashDashStartsComment(sql, i)) return true;
10392
10501
  if (c === '#' && sql[i + 1] !== '>') return true; // '#>' / '#>>' 是 JSON 操作符,不是注释
10393
10502
  if (c === '/' && sql[i + 1] === '*') return true;
10394
10503
  i++;
@@ -10782,6 +10891,10 @@ async function executeSQL(engine, sql, paramsOrOpts, opts = {}) {
10782
10891
  }
10783
10892
  }
10784
10893
  let statements = splitStatements(sql, { maxLength: opts.maxSqlLength });
10894
+ // #345:只有注释(/* */、--、#)的片断 tokenize 后为空,此前会走进 Parser 返回 null,
10895
+ // 再被 buildResultEnvelope 读 .type 抛裸 TypeError。纯空白语句早就是空结果,
10896
+ // 这里把纯注释统一成同一条路。
10897
+ statements = statements.filter((s0) => tokenize(s0).some((t) => t.type !== 'eof'));
10785
10898
  if (opts.maxStatements != null && statements.length > opts.maxStatements) {
10786
10899
  throw new Error(`too many statements (${statements.length} > ${opts.maxStatements})`);
10787
10900
  }
@@ -97,6 +97,9 @@ class Database {
97
97
 
98
98
  prepare(sql) {
99
99
  if (typeof sql !== 'string') throw new TypeError('The "sql" argument must be a string');
100
+ // #329:与 exec() 对齐 —— 空串/纯空白统一视为「无语句」,不再走到 executeSQL 的参数守卫抛错。
101
+ // 用一条恒空结果集占位,保证 all()/get() 返回 []/(undefined)、run() 报 0 变更。
102
+ if (sql.trim() === '') sql = 'SELECT 1 WHERE 0';
100
103
  return new Statement(this, sql);
101
104
  }
102
105
 
package/lib/table.js CHANGED
@@ -1230,6 +1230,55 @@ class Table {
1230
1230
  return this;
1231
1231
  }
1232
1232
 
1233
+ /**
1234
+ * #357:列改名后,CHECK 约束里写死的列名必须一起改写并重编译。
1235
+ * 此前只改了 _checkConstraints[].field(列归属),表达式文本仍是旧列名,
1236
+ * 于是 `CHECK (a > 0)` 在 a 改名成 b 之后开始求值 null/旧字段 → 约束静默失效。
1237
+ */
1238
+ _rewriteColumnRefs(oldName, newName) {
1239
+ const esc = String(oldName).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1240
+ const re = new RegExp(`\\b${esc}\\b`, 'g');
1241
+ const rewrite = (txt) => String(txt).replace(re, newName);
1242
+ for (const [col, def] of Object.entries(this._schema || {})) {
1243
+ if (!def || typeof def !== 'object') continue;
1244
+ let changed = false;
1245
+ if (typeof def.checkSql === 'string' && def.checkSql) {
1246
+ const next = rewrite(def.checkSql);
1247
+ if (next !== def.checkSql) { def.checkSql = next; changed = true; }
1248
+ }
1249
+ if (typeof def.check === 'string') {
1250
+ const next = rewrite(def.check);
1251
+ if (next !== def.check) { def.check = next; changed = true; }
1252
+ }
1253
+ if (changed && typeof def.checkSql === 'string' && def.checkSql) {
1254
+ // _checkConstraints 里存的是编译后的 fn,光改文本不会生效,必须重编译替换
1255
+ const fn = compileCheckSql(def.checkSql);
1256
+ if (fn) {
1257
+ const entry = this._checkConstraints.find(c => c.field === col);
1258
+ if (entry) entry.fn = fn;
1259
+ else this._checkConstraints.push({ field: col, fn });
1260
+ }
1261
+ }
1262
+ if (Array.isArray(def.checks)) {
1263
+ for (const entry of def.checks) {
1264
+ if (!entry || typeof entry.sql !== 'string') continue;
1265
+ const next = rewrite(entry.sql);
1266
+ if (next === entry.sql) continue;
1267
+ entry.sql = next;
1268
+ if (typeof entry.fn === 'function') entry.fn = compileCheckSql(next);
1269
+ }
1270
+ }
1271
+ }
1272
+ // 表级 CHECK 若带独立文本也一并改写
1273
+ for (const c of (this._checkConstraints || [])) {
1274
+ if (!c || typeof c.sql !== 'string') continue;
1275
+ const next = rewrite(c.sql);
1276
+ if (next === c.sql) continue;
1277
+ c.sql = next;
1278
+ try { c.fn = compileCheckSql(next); } catch (_) { /* 保存路径会报错 */ }
1279
+ }
1280
+ }
1281
+
1233
1282
  renameColumn(oldName, newName) {
1234
1283
  if (!this._schema[oldName]) throw createError('ER_BAD_FIELD_ERROR', oldName, this._name);
1235
1284
  if (this._schema[newName]) throw createError('ER_DUP_FIELDNAME', newName);
@@ -1272,6 +1321,7 @@ class Table {
1272
1321
  }
1273
1322
  if (this._primaryKey === oldName) this._primaryKey = newName;
1274
1323
  if (this._autoIncrementField === oldName) this._autoIncrementField = newName;
1324
+ this._rewriteColumnRefs(oldName, newName);
1275
1325
  this._refreshSchemaCache();
1276
1326
  this._dirty = true;
1277
1327
  this._db._markDirty(this._name);
package/lib/web_ui.js CHANGED
@@ -144,15 +144,11 @@ class WebUI {
144
144
  .filter(f => f.endsWith('.json'))
145
145
  .map(f => {
146
146
  try {
147
- const stat = fs.statSync(path.join(this.dataDir, f));
148
- // 只读前 4KB:schema 头部包含 __schema__ 定义,尾部数据不需要
149
- const fd = fs.openSync(path.join(this.dataDir, f), 'r');
150
- const buf = Buffer.alloc(4096);
151
- fs.readSync(fd, buf, 0, 4096, 0);
152
- fs.closeSync(fd);
153
- const match = buf.toString('utf8').match(/"__schema__"\s*:\s*\{([^}]*)\}/);
154
- const tables = match ? (match[1].match(/"/g) || []).length / 2 : 0;
155
- return { name: f.slice(0, -5), tables };
147
+ // #365:旧实现只看前 4KB 并用引号数估算表数,schema 头不在前 4KB 或
148
+ // 有嵌套定义时结果完全失真(实测单表被报成 5 张)。改为完整解析并取 __schema__ 的键数。
149
+ const parsed = JSON.parse(fs.readFileSync(path.join(this.dataDir, f), 'utf8'));
150
+ const schema = parsed && parsed.__schema__ && typeof parsed.__schema__ === 'object' ? parsed.__schema__ : {};
151
+ return { name: f.slice(0, -5), tables: Object.keys(schema).length };
156
152
  } catch (_) { return { name: f.slice(0, -5), tables: 0 }; }
157
153
  });
158
154
  }
@@ -223,13 +219,20 @@ class WebUI {
223
219
  return send(200, this.listDatabases());
224
220
  }
225
221
  if (url.pathname === '/api/tables' && req.method === 'GET') {
226
- const db = await this.db(url.searchParams.get("db"));
222
+ // #366:缺参/非法库名此前一路抛到外层变 500,客户端分不清「请求错了」和「服务坏了」。
223
+ const dbName = url.searchParams.get('db');
224
+ if (!dbName) return send(400, { ok: false, error: 'db is required' });
225
+ let db;
226
+ try { db = await this.db(dbName); } catch (e) { return send(404, { ok: false, error: String(e.message || e) }); }
227
227
  return send(200, { tables: this.tableList(db) });
228
228
  }
229
229
  if (url.pathname === '/api/query' && req.method === 'POST') {
230
230
  let body = '';
231
231
  for await (const chunk of req) body += chunk;
232
- const { db: dbName, sql } = JSON.parse(body || '{}');
232
+ let parsed;
233
+ // #364:请求体不是合法 JSON 属于客户端错误,必须是 400 而不是落到外层 catch 的 500。
234
+ try { parsed = JSON.parse(body || '{}'); } catch (e) { return send(400, { ok: false, error: 'invalid JSON body' }); }
235
+ const { db: dbName, sql } = parsed || {};
233
236
  if (!dbName || !sql) return send(400, { ok: false, error: 'db and sql are required' });
234
237
  const db = await this.db(dbName);
235
238
  const t0 = Date.now();
@@ -248,7 +251,8 @@ class WebUI {
248
251
  }
249
252
  return send(200, out);
250
253
  } catch (e) {
251
- return send(200, { ok: false, error: String(e.message || e) });
254
+ // #363:SQL 执行失败是服务端语义错误,回 200 会让 SDK/监控把失败当成功。
255
+ return send(500, { ok: false, error: String(e.message || e) });
252
256
  }
253
257
  }
254
258
  return send(404, { ok: false, error: 'not found' });
package/lib/xql/index.js CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.8.25",
3
+ "version": "6.8.26",
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",
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",
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",
@@ -269,7 +269,7 @@ async function t(name, fn) {
269
269
  await exec('ALTER TABLE t2 RENAME COLUMN a TO name');
270
270
  await db.save();
271
271
 
272
- const db2 = new Database(file, { wal: true });
272
+ const db2 = new Database(file, { wal: true, fileLock: false });
273
273
  const exec2 = (sql) => executeSQL(db2, sql, OPTS);
274
274
  const tables = (await db2.getTables()).slice().sort();
275
275
  const cols = (await exec2('SELECT * FROM t2')).columns;
@@ -384,14 +384,17 @@ async function mysqlCases() {
384
384
  const { createMysqlServer } = require(path.join(ROOT, 'lib', 'mysql_server.js'));
385
385
  const srv = createMysqlServer({ port: 0, host: '127.0.0.1', dataDir: ':memory:', noAuth: true });
386
386
  await new Promise((r) => srv.listen(r));
387
- const conn = await mysql.createConnection({ host: '127.0.0.1', port: srv.address.port, user: 'root', database: 'app', multipleStatements: true });
387
+ const conn = await mysql.createConnection({ host: '127.0.0.1', port: srv.address.port, user: 'root', multipleStatements: true });
388
+ // #394:握手阶段未知库现在正确回 1049,因此先连接再显式建库/切库
389
+ await conn.query('CREATE DATABASE app');
390
+ await conn.query('USE app');
388
391
  await conn.query('CREATE TABLE t (id BIGINT, name VARCHAR(50))');
389
392
  await conn.query("INSERT INTO t VALUES (4000000000, '张三 😀')");
390
393
  const [text, tf] = await conn.query('SELECT id,name FROM t');
391
394
  const [bin, bf] = await conn.execute('SELECT id,name FROM t');
392
395
  ok('#209 BIGINT text/binary protocol', text[0].id === 4000000000 && bin[0].id === 4000000000 && tf[0].type === 8 && bf[0].type === 8, { text, bin, type: tf[0].type });
393
396
  ok('#211 execute without params matches query', JSON.stringify(bin) === JSON.stringify(text), { text, bin });
394
- ok('#212 utf8mb4 emoji round-trip', text[0].name === '张三 😀' && tf[1].characterSet === 45, { name: text[0].name, cs: tf[1].characterSet });
397
+ ok('#212 utf8mb4 emoji round-trip', text[0].name === '张三 😀' && [45, 224, 255].includes(tf[1].characterSet), { name: text[0].name, cs: tf[1].characterSet });
395
398
  const [multi] = await conn.query('SELECT 1 AS a; SELECT 2 AS b');
396
399
  ok('#210 multi-result sets preserved', multi.length === 2 && multi[1][0].b === 2, multi);
397
400
  await conn.end();
@@ -21,7 +21,8 @@ function ok(name, cond, extra) {
21
21
  const { createMysqlServer } = require(path.join(ROOT, 'lib', 'mysql_server.js'));
22
22
  const srv = createMysqlServer({ port: 0, host: '127.0.0.1', dataDir: ':memory:', noAuth: true });
23
23
  await new Promise((r) => srv.listen(r));
24
- const c = await mysql.createConnection({ host: '127.0.0.1', port: srv.address.port, user: 'root', database: 'app' });
24
+ const c = await mysql.createConnection({ host: '127.0.0.1', port: srv.address.port, user: 'root' });
25
+ await c.query('CREATE DATABASE IF NOT EXISTS app'); await c.query('USE app');
25
26
  await c.query('CREATE TABLE t (id INT PRIMARY KEY AUTO_INCREMENT, v VARCHAR(10) NOT NULL)');
26
27
  const [, f] = await c.query('SELECT id, v FROM t');
27
28
  ok('#271 column flags expose PK/NOT NULL/AUTO_INCREMENT', (f[0].flags & 0x0002) !== 0 && (f[0].flags & 0x0200) !== 0 && (f[1].flags & 0x0001) !== 0, f.map(x => x.flags));
@@ -66,8 +67,11 @@ function ok(name, cond, extra) {
66
67
  {
67
68
  const mongo = createMongoServer({ dataDir: ':memory:' });
68
69
  await mongo._dispatch('insert', { insert: 'c', documents: [{ a: 1 }], $db: 'test' });
69
- const r = await mongo._dispatch('aggregate', { aggregate: 'c', pipeline: [{ $addFields: { b: 2 } }], cursor: {}, $db: 'test' });
70
+ // #328 起 $addFields/$set 已是文档承诺的受支持 stage,未知 stage 改用真正不存在的名字
71
+ const r = await mongo._dispatch('aggregate', { aggregate: 'c', pipeline: [{ $bogusStage: { b: 2 } }], cursor: {}, $db: 'test' });
70
72
  ok('#283 unknown pipeline stage errors', r.ok === 0 && r.code === 40324, r);
73
+ const okAdd = await mongo._dispatch('aggregate', { aggregate: 'c', pipeline: [{ $addFields: { b: 2 } }], cursor: {}, $db: 'test' });
74
+ ok('#283 $addFields 受支持(#328)', okAdd.ok === 1 && okAdd.cursor.firstBatch[0].b === 2, okAdd);
71
75
  }
72
76
 
73
77
  // #278 batchSize + getMore
@@ -17,7 +17,8 @@ function ok(name, cond, extra) {
17
17
  const { createMysqlServer } = require(path.join(ROOT, 'lib', 'mysql_server.js'));
18
18
  const srv = createMysqlServer({ port: 0, host: '127.0.0.1', dataDir: ':memory:', noAuth: true });
19
19
  await new Promise((r) => srv.listen(r));
20
- const conn = await mysql.createConnection({ host: '127.0.0.1', port: srv.address.port, user: 'root', database: 'app' });
20
+ const conn = await mysql.createConnection({ host: '127.0.0.1', port: srv.address.port, user: 'root' });
21
+ await conn.query('CREATE DATABASE IF NOT EXISTS app'); await conn.query('USE app');
21
22
  // #274
22
23
  let missing = null;
23
24
  try { await conn.query('SELECT * FROM no_such_table'); } catch (e) { missing = e; }