jsql-neo 6.3.10 → 6.4.0-beta.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.
@@ -19,7 +19,7 @@ function toResultPacket(r, table, rowsAsArray) {
19
19
  // P3-9: fields 类型全 253——根据实际类型设置
20
20
  const fields = columns.map(name => {
21
21
  let type = 253; // VAR_STRING
22
- const val = values[0] ? values[0][name] : null;
22
+ const val = rawRows[0] ? rawRows[0][columns.indexOf(name)] : null;
23
23
  if (typeof val === 'number') type = 8; // LONGLONG
24
24
  else if (typeof val === 'boolean') type = 1; // TINY
25
25
  else if (val instanceof Date) type = 12; // DATETIME
@@ -73,6 +73,7 @@ class Connection extends EventEmitter {
73
73
  this.filename = options.filename || null;
74
74
  this.engine = null;
75
75
  this._ownEngine = false;
76
+ this._connectEmitted = false;
76
77
  this.state = 'disconnected';
77
78
  this.stream = {
78
79
  destroyed: false,
@@ -131,6 +131,12 @@ function parseLenenc(buf, offset) {
131
131
  if (first === 0xfb) return { value: null, size: 1 };
132
132
  if (first === 0xfc) return { value: buf.readUInt16LE(offset + 1), size: 3 };
133
133
  if (first === 0xfd) return { value: buf.readUIntLE(offset + 1, 3), size: 4 };
134
+ // 0xfe: 8-byte int64
135
+ if (first === 0xfe) {
136
+ const low = buf.readUInt32LE(offset + 1);
137
+ const high = buf.readUInt32LE(offset + 5);
138
+ return { value: low + high * 4294967296, size: 9 };
139
+ }
134
140
  return { value: buf.readUInt32LE(offset + 1), size: 5 };
135
141
  }
136
142
 
@@ -17,6 +17,35 @@ function safeParse(str, fallback) {
17
17
  try { return JSON.parse(str); } catch (e) { return fallback; }
18
18
  }
19
19
 
20
+ /**
21
+ * 深度相等比较两个行对象(用于无主键表行匹配)。
22
+ * 剥离内部字段(_rid, _deleted)后逐字段比较。
23
+ */
24
+ function _nativeRowDeepEqual(a, b) {
25
+ if (a === b) return true;
26
+ if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false;
27
+ const strip = (obj) => {
28
+ const out = {};
29
+ for (const [k, v] of Object.entries(obj)) {
30
+ if (k === '_rid' || k === '_deleted') continue;
31
+ out[k] = v;
32
+ }
33
+ return out;
34
+ };
35
+ const sa = strip(a), sb = strip(b);
36
+ const ka = Object.keys(sa), kb = Object.keys(sb);
37
+ if (ka.length !== kb.length) return false;
38
+ for (const k of ka) {
39
+ if (!Object.prototype.hasOwnProperty.call(sb, k)) return false;
40
+ const va = sa[k], vb = sb[k];
41
+ if (va === vb) continue;
42
+ if (va === null || va === undefined || vb === null || vb === undefined) return false;
43
+ if (typeof va === 'number' && typeof vb === 'number' && va === vb) continue;
44
+ if (String(va) !== String(vb)) return false;
45
+ }
46
+ return true;
47
+ }
48
+
20
49
  /**
21
50
  * 序列化对象/数组字段(JSON 列)并给出可读错误。直接 JSON.stringify 遇到循环引用会抛
22
51
  * "Converting circular structure to JSON",指向不到具体列,这里补上表/列信息。
@@ -443,7 +472,21 @@ class JSQL {
443
472
  if (Array.isArray(r) && r.length > 0) return r[0].id;
444
473
  return null;
445
474
  }
446
- return Number(id);
475
+ // 无主键表:id 应是 1-based 行号(数字)。
476
+ // 但 sql.js DELETE 对无主键表传的是行对象(find() 返回的浅拷贝),
477
+ // Number(obj) = NaN → JSON.stringify([NaN]) = "[null]" → 静默失效。
478
+ // 这里对对象 id 做深度相等匹配,找到对应行的序列号。
479
+ if (typeof id === 'number') return id;
480
+ if (id && typeof id === 'object') {
481
+ const all = safeParse(this._n('jsqlFind', table, '{}', 1000000, 0));
482
+ if (Array.isArray(all)) {
483
+ for (const r of all) {
484
+ const row = r.fields ? { ...r.fields, id: r.id } : r;
485
+ if (_nativeRowDeepEqual(row, id)) return r.id;
486
+ }
487
+ }
488
+ }
489
+ return null;
447
490
  }
448
491
 
449
492
  async _insertBatch(table, rows) {
@@ -53,7 +53,7 @@ function arraysEqual(a, b) {
53
53
  function looseEqual(a, b) {
54
54
  if (a === b) return true;
55
55
  if (a === null || b === null || a === undefined || b === undefined) return false;
56
- if (typeof a === 'number' || typeof b === 'number') {
56
+ if (typeof a === 'number' && typeof b === 'number') {
57
57
  const na = Number(a), nb = Number(b);
58
58
  if (!Number.isNaN(na) && !Number.isNaN(nb)) return na === nb;
59
59
  }
@@ -63,17 +63,17 @@ function looseEqual(a, b) {
63
63
  if (ka.length !== kb.length) return false;
64
64
  return ka.every(k => looseEqual(a[k], b[k]));
65
65
  }
66
- return String(a) === String(b);
66
+ return false;
67
67
  }
68
68
 
69
69
  function matchOperator(value, op, expected) {
70
70
  switch (op) {
71
71
  case '$eq': return looseEqual(value, expected);
72
72
  case '$ne': return !looseEqual(value, expected);
73
- case '$lt': return value !== undefined && (value === null ? expected !== null && expected !== undefined && 0 < expected : value < expected);
74
- case '$lte': return value !== undefined && (value === null ? expected !== null && expected !== undefined && 0 <= expected : value <= expected);
75
- case '$gt': return value !== undefined && (value === null ? expected !== null && expected !== undefined && 0 > expected : value > expected);
76
- case '$gte': return value !== undefined && (value === null ? expected !== null && expected !== undefined && 0 >= expected : value >= expected);
73
+ case '$lt': return value !== undefined && (value === null ? 0 < expected : value < expected);
74
+ case '$lte': return value !== undefined && (value === null ? 0 <= expected : value <= expected);
75
+ case '$gt': return value !== undefined && (value === null ? 0 > expected : value > expected);
76
+ case '$gte': return value !== undefined && (value === null ? 0 >= expected : value >= 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;
package/lib/query.js CHANGED
@@ -232,7 +232,8 @@ class Query {
232
232
  return this._cache.result;
233
233
  }
234
234
 
235
- let rows = this._table._applyFilterOptimized(this._table._rows, this._conditions);
235
+ // P1-4: 软删除模式下 QueryBuilder 也不得泄露已删除行
236
+ let rows = this._table._applyFilterOptimized(this._table._getVisibleRows(), this._conditions);
236
237
 
237
238
  // JOIN
238
239
  for (const join of this._joins) {
@@ -26,7 +26,7 @@ const TYPE_SIGNATURES = {
26
26
  INCR: 1, DECR: 1, INCRBY: 2, DECRBY: 2, APPEND: 2, STRLEN: 1,
27
27
  MSET: -2, MGET: -1,
28
28
  HSET: -3, HGET: 2, HGETALL: 1, HDEL: -2, HEXISTS: 2, HLEN: 1, HKEYS: 1, HVALS: 1,
29
- LPUSH: -2, RPUSH: -2, LPOP: 1, RPOP: 1, LLEN: 1, LRANGE: 3, LINDEX: 2, LREM: 3,
29
+ LPUSH: -2, RPUSH: -2, LPOP: -1, RPOP: -1, LLEN: 1, LRANGE: 3, LINDEX: 2, LREM: 3,
30
30
  SADD: -2, SREM: -2, SMEMBERS: 1, SISMEMBER: 2, SCARD: 1,
31
31
  ZADD: -3, ZRANGE: 3, ZREVRANGE: 3, ZSCORE: 2, ZCARD: 1, ZREM: -2, ZINCRBY: 3,
32
32
  DBSIZE: 0, FLUSHALL: 0, FLUSHDB: 0, SELECT: 1, INFO: 0, AUTH: 1, QUIT: 0,
@@ -167,17 +167,22 @@ class RedisServer {
167
167
  return v.val;
168
168
  }
169
169
  case 'APPEND': {
170
+ const argCount = args.length;
171
+ if (argCount > 2) throw new Error(`ERR wrong number of arguments for 'append' command`);
170
172
  const v = this._get(args[0]);
171
- const prev = v && v.type === 'string' ? v.val : '';
173
+ // N2-fix: 对非 string 类型的 key(list/hash/set/zset)必须报 WRONGTYPE,
174
+ // 此前静默把整值覆盖成 string,丢数据且与真 Redis 行为不符。
175
+ if (v && v.type !== 'string') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
176
+ const prev = v ? v.val : '';
172
177
  this.db.set(args[0], { type: 'string', val: prev + args[1], ttl: v ? v.ttl : null });
173
178
  this._scheduleSnapshot();
174
- return this.db.get(args[0]).val.length;
179
+ return Buffer.byteLength(this.db.get(args[0]).val, 'utf8');
175
180
  }
176
181
  case 'STRLEN': {
177
182
  const v = this._get(args[0]);
178
183
  if (!v) return 0;
179
184
  if (v.type !== 'string') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
180
- return v.val.length;
185
+ return Buffer.byteLength(v.val, 'utf8');
181
186
  }
182
187
  case 'INCR': case 'DECR': case 'INCRBY': case 'DECRBY': {
183
188
  const by = cmd === 'INCRBY' || cmd === 'DECRBY' ? parseInt(args[1], 10) : 1;
@@ -241,7 +246,8 @@ class RedisServer {
241
246
  case 'HSET': {
242
247
  if (args.length % 2 !== 1) throw new Error(`ERR wrong number of arguments for 'hset' command`);
243
248
  const v = this._get(args[0]);
244
- const h = (v && v.type === 'hash') ? { ...v.val } : {};
249
+ if (v && v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
250
+ const h = v ? { ...v.val } : {};
245
251
  let n = 0;
246
252
  for (let i = 1; i < args.length; i += 2) {
247
253
  if (!(args[i] in h)) n++;
@@ -290,7 +296,8 @@ class RedisServer {
290
296
  }
291
297
  case 'LPUSH': case 'RPUSH': {
292
298
  const v = this._get(args[0]);
293
- const list = (v && v.type === 'list') ? [...v.val] : [];
299
+ if (v && v.type !== 'list') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
300
+ const list = v ? [...v.val] : [];
294
301
  if (cmd === 'LPUSH') {
295
302
  for (const val of args.slice(1)) list.unshift(val);
296
303
  } else {
@@ -301,16 +308,32 @@ class RedisServer {
301
308
  return list.length;
302
309
  }
303
310
  case 'LPOP': case 'RPOP': {
311
+ // N3-fix: 支持可选 count 参数(Redis 6.2+)。旧实现忽略 count,LPOP key 2 只弹 1 个。
312
+ // 无 count:弹 1 个,key 不存在时返回 nil(bulk null)。
313
+ // 有 count:返回数组(最多 count 个元素),key 不存在时返回空数组;count<0 报错。
314
+ const hasCount = args.length >= 2;
315
+ let count = 1;
316
+ if (hasCount) {
317
+ count = parseInt(args[1], 10);
318
+ if (isNaN(count) || count < 0) throw new Error('ERR value is out of range, must be positive');
319
+ }
304
320
  const v = this._get(args[0]);
305
- if (!v) return null;
321
+ if (!v) return hasCount ? [] : null;
306
322
  if (v.type !== 'list') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
307
- const el = cmd === 'LPOP' ? v.val.shift() : v.val.pop();
323
+ const popped = [];
324
+ for (let i = 0; i < count && v.val.length > 0; i++) {
325
+ popped.push(cmd === 'LPOP' ? v.val.shift() : v.val.pop());
326
+ }
327
+ if (v.val.length === 0) this.db.delete(args[0]);
308
328
  this._scheduleSnapshot();
309
- return el === undefined ? null : el;
329
+ if (hasCount) return popped;
330
+ return popped.length ? popped[0] : null;
310
331
  }
311
332
  case 'LLEN': {
312
333
  const v = this._get(args[0]);
313
- return v && v.type === 'list' ? v.val.length : 0;
334
+ if (!v) return 0;
335
+ if (v.type !== 'list') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
336
+ return v.val.length;
314
337
  }
315
338
  case 'LRANGE': {
316
339
  const v = this._get(args[0]);
@@ -366,7 +389,8 @@ class RedisServer {
366
389
  }
367
390
  case 'SADD': case 'SREM': {
368
391
  const v = this._get(args[0]);
369
- const set = (v && v.type === 'set') ? new Set(v.val) : new Set();
392
+ if (v && v.type !== 'set') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
393
+ const set = v ? new Set(v.val) : new Set();
370
394
  let n = 0;
371
395
  for (const m of args.slice(1)) {
372
396
  if (cmd === 'SADD') { if (!set.has(m)) { set.add(m); n++; } }
@@ -495,8 +519,9 @@ class RedisServer {
495
519
  case 'DBSIZE': {
496
520
  let count = 0;
497
521
  const now = Date.now();
498
- for (const v of this.db.values()) {
499
- if (!v.ttl || v.ttl > now) count++;
522
+ for (const [k, v] of this.db) {
523
+ if (v.ttl && v.ttl <= now) { this.db.delete(k); continue; }
524
+ count++;
500
525
  }
501
526
  return count;
502
527
  }
package/lib/sql.js CHANGED
@@ -1,3 +1,6 @@
1
+ // N1-fix: createError 此前未导入,UPDATE 无主键表时抛 ReferenceError(而非预期的 SQL 错误)
2
+ const { createError } = require('./errors');
3
+
1
4
  const DANGEROUS_SQL = [
2
5
  { re: /^INTO$/, next: /^(OUTFILE|DUMPFILE)$/, name: 'INTO OUTFILE/DUMPFILE' },
3
6
  { re: /^LOAD$/, next: /^(FILE|DATA)$/, name: 'LOAD_FILE/LOAD DATA' },
@@ -610,22 +613,10 @@ class Parser {
610
613
  } else if (this.isWord('FOREIGN') || this.isWord('CHECK') ||
611
614
  t.type === 'keyword' && (t.value === 'KEY' || t.value === 'INDEX')) {
612
615
  // 表级约束:FOREIGN KEY ... REFERENCES ... / CHECK (...) / KEY name (cols)
613
- // P1-24: CREATE TABLE t (key TEXT) 报错——key 被当作表级约束
614
- // 如果 KEY/INDEX 后面跟着列类型(TEXT/INT/VARCHAR 等),应解析为列定义
615
- if (t.type === 'keyword' && (t.value === 'KEY' || t.value === 'INDEX')) {
616
- const nextTok = this.peek(1);
617
- if (nextTok && (nextTok.type === 'ident' || nextTok.type === 'keyword') &&
618
- ['TEXT', 'INT', 'INTEGER', 'VARCHAR', 'CHAR', 'DATE', 'DATETIME', 'TIMESTAMP', 'BOOLEAN', 'BOOL', 'FLOAT', 'DOUBLE', 'DECIMAL', 'BLOB', 'JSON'].includes(String(nextTok.value).toUpperCase())) {
619
- const col = this.parseTableName();
620
- const def = this.parseColumnDef();
621
- schema[col] = def;
622
- if (def.primaryKey) hasPk = true;
623
- } else {
624
- this._parseTableConstraint(schema);
625
- }
626
- } else {
627
- this._parseTableConstraint(schema);
628
- }
616
+ // KEY/INDEX 是保留字:裸写作列名(如 CREATE TABLE t (key TEXT))必须报错,
617
+ // 由 _parseTableConstraint 消费 KEY 后遇到类型 token 触发
618
+ // "Expected ',' or ')'",见 identifier-keywords 测试。
619
+ this._parseTableConstraint(schema);
629
620
  } else if (t.type === 'eof' || (t.type === 'op' && t.value === ')')) {
630
621
  break;
631
622
  } else {
@@ -983,6 +974,24 @@ class Parser {
983
974
  }
984
975
 
985
976
  parseValue() {
977
+ const atom = this.parseValueAtom();
978
+ return this.parseBinaryFromAtom(atom);
979
+ }
980
+
981
+ /** P2-3 helper: parse binary expression starting from an already-parsed left atom. */
982
+ parseBinaryFromAtom(left) {
983
+ const ops = ['+', '-', '*', '/', '%', '<<', '>>', '&', '|', '^'];
984
+ for (;;) {
985
+ const opTok = this.peek();
986
+ if (opTok.type !== 'op' || !ops.includes(opTok.value)) break;
987
+ this.next();
988
+ const right = this.parseValueAtom();
989
+ left = { type: 'binary', op: opTok.value, left, right };
990
+ }
991
+ return left;
992
+ }
993
+
994
+ parseValueAtom() {
986
995
  const t = this.next();
987
996
  if (t.type === 'number' || t.type === 'string') return t.value;
988
997
  // MySQL: ON DUPLICATE KEY UPDATE col = VALUES(col) —— 引用"本次本应插入的值"
@@ -1007,17 +1016,15 @@ class Parser {
1007
1016
  if (num.type !== 'number') throw new Error('Expected number after +');
1008
1017
  return num.value;
1009
1018
  }
1010
- // P1-19/P2-3: parseValue 不支持表达式 RHS,如 col = col + 1
1011
- // 支持简单的二元表达式:left op right
1012
1019
  if (t.type === 'ident') {
1013
- const left = this.parseColumnRef();
1014
- const opTok = this.peek();
1015
- if (opTok.type === 'op' && ['+', '-', '*', '/', '%', '<<', '>>', '&', '|', '^'].includes(opTok.value)) {
1020
+ // Handle dotted column refs (a.b) without double-consuming the token
1021
+ if (this.peek().type === 'op' && this.peek().value === '.') {
1016
1022
  this.next();
1017
- const right = this.parseValue();
1018
- return { type: 'binary', op: opTok.value, left, right };
1023
+ const col = this.next();
1024
+ if (!isUsableNameToken(col)) throw new Error(`Expected column name after '.', got '${col.value}'`);
1025
+ return nameOfToken(t) + '.' + nameOfToken(col);
1019
1026
  }
1020
- return left;
1027
+ return nameOfToken(t);
1021
1028
  }
1022
1029
  throw new Error(`Expected value, got '${t.value}'`);
1023
1030
  }
@@ -2355,9 +2362,11 @@ class Parser {
2355
2362
  return { type: 'value', value: t.value === '-' ? -num.value : num.value };
2356
2363
  }
2357
2364
  // 负号/正号后面是列名或表达式:解析为 unary 运算符
2358
- if (num.type === 'column' || num.type === 'value') {
2359
- const operand = num.type === 'column' ? { type: 'column', name: num.value } : { type: 'value', value: num.value };
2360
- return { type: 'negate', operand };
2365
+ if (num.type === 'ident') {
2366
+ return { type: 'negate', operand: { type: 'column', name: nameOfToken(num) }, positive: t.value === '+' };
2367
+ }
2368
+ if (num.type === 'string') {
2369
+ return { type: 'negate', operand: { type: 'value', value: num.value }, positive: t.value === '+' };
2361
2370
  }
2362
2371
  throw new Error('Expected number or column after sign');
2363
2372
  }
@@ -2825,7 +2834,9 @@ function resolveOperand(operand, row, ctx) {
2825
2834
  case 'negate': {
2826
2835
  const v = resolveOperand(operand.operand, row, ctx);
2827
2836
  if (v === null || v === undefined) return null;
2828
- return -Number(v);
2837
+ const n = Number(v);
2838
+ if (isNaN(n)) return null;
2839
+ return operand.positive ? n : -n;
2829
2840
  }
2830
2841
  // P1-19: ON DUPLICATE KEY UPDATE 表达式赋值,如 count = count + 1
2831
2842
  case 'binary': {
@@ -3990,8 +4001,14 @@ class SQLExecutor {
3990
4001
  break;
3991
4002
  }
3992
4003
  case 'dropPrimary': {
3993
- for (const def of Object.values(table._schema)) { if (def && typeof def === 'object') { def.primaryKey = false; } }
3994
- // P1-23: 清除主键缓存,否则后续插入仍会检查主键冲突
4004
+ for (const [colName, def] of Object.entries(table._schema)) {
4005
+ if (def && typeof def === 'object' && def.primaryKey) {
4006
+ def.primaryKey = false;
4007
+ // P1-23: 同时清除 unique 标记,否则后续 INSERT 仍会拒绝重复值
4008
+ def.unique = false;
4009
+ }
4010
+ }
4011
+ // 清除主键缓存
3995
4012
  table._primaryKey = null;
3996
4013
  table._pkIndex = null;
3997
4014
  break;
@@ -4086,6 +4103,25 @@ class SQLExecutor {
4086
4103
  ? await this.engine.getTableSchema(statement.name)
4087
4104
  : (this.engine._schemas ? this.engine._schemas[statement.name] : null);
4088
4105
  if (!schema) throw new Error(`Table '${statement.name}' does not exist`);
4106
+ // P2: INSERT 未知列静默接受 → 应报 Unknown column
4107
+ // 检查 statement.columns(INSERT INTO t (col1, col2) VALUES ...)
4108
+ if (statement.columns && statement.columns.length > 0) {
4109
+ for (const col of statement.columns) {
4110
+ if (!Object.prototype.hasOwnProperty.call(schema, col)) {
4111
+ throw new Error(`Unknown column '${col}' in '${statement.name}'`);
4112
+ }
4113
+ }
4114
+ }
4115
+ // 检查 dataRows 的键(INSERT INTO t SET col1=... 或 INSERT INTO t (col1) VALUES ...)
4116
+ if (dataRows) {
4117
+ for (const row of dataRows) {
4118
+ for (const col of Object.keys(row)) {
4119
+ if (!Object.prototype.hasOwnProperty.call(schema, col)) {
4120
+ throw new Error(`Unknown column '${col}' in '${statement.name}'`);
4121
+ }
4122
+ }
4123
+ }
4124
+ }
4089
4125
  const stripDefault = (row) => {
4090
4126
  const out = {};
4091
4127
  for (const [k, v] of Object.entries(row)) {
@@ -4115,6 +4151,15 @@ class SQLExecutor {
4115
4151
  }
4116
4152
  if (dataRows === null && statement.values) {
4117
4153
  const colNames = Object.keys(schema);
4154
+ // P2: INSERT 未知列静默接受 → 应报 Unknown column
4155
+ // 检查 VALUES 数量是否超过列数(无列清单时)
4156
+ if (!statement.columns || statement.columns.length === 0) {
4157
+ for (const vals of statement.values) {
4158
+ if (vals.length > colNames.length) {
4159
+ throw new Error(`Unknown column in '${statement.name}': VALUES has ${vals.length} values but table has ${colNames.length} columns`);
4160
+ }
4161
+ }
4162
+ }
4118
4163
  const skipAuto = statement.values[0].length < colNames.length;
4119
4164
  dataRows = statement.values.map(vals => {
4120
4165
  const row = {};
@@ -6409,24 +6454,24 @@ class SQLExecutor {
6409
6454
  const tableName = statement.from ? (statement.from.tables[0].table || null) : null;
6410
6455
  if (statement.columns.length === 1 && statement.columns[0].expr === '*') {
6411
6456
  const schemaKeys = schema ? Object.keys(schema) : [];
6412
- const pkCols = schemaKeys.filter(k => schema && schema[k] && schema[k].primaryKey);
6413
- const pk = pkCols.length > 0 ? pkCols[0] : (schemaKeys[0] || 'id');
6414
6457
  let cols;
6415
6458
  // 有 JOIN 时,SELECT * 应展开所有表的列(合并后的行包含所有前缀列)
6416
6459
  const hasJoins = statement.from && statement.from.joins && statement.from.joins.length > 0;
6417
6460
  if (schema && !hasJoins) {
6418
- cols = [pk, ...schemaKeys.filter(k => k !== pk)];
6461
+ // P1-17: SELECT * 按列声明顺序输出,不得把主键强制排到首位(MySQL 语义)
6462
+ cols = schemaKeys.filter(k => k !== '_softDelete');
6419
6463
  } else if (rowsAll && rowsAll.columns) {
6420
6464
  cols = rowsAll.columns;
6421
6465
  } else {
6422
- // JOIN 时:只使用带前缀的键,避免同一列重复
6466
+ // JOIN 时:只使用带前缀的键,避免同一列重复。
6467
+ // 不能按裸名去重——右表同名列(如 b.id)会被丢弃,导致右表列全部丢失。
6423
6468
  if (hasJoins) {
6424
6469
  const seen = new Set();
6425
6470
  cols = [];
6426
6471
  for (const r of rows) {
6427
6472
  for (const k of Object.keys(r)) {
6428
- const bare = k.includes('.') ? k.slice(k.indexOf('.') + 1) : k;
6429
- if (!seen.has(bare)) { seen.add(bare); cols.push(k); }
6473
+ if (!k.includes('.')) continue; // 只取带前缀的键
6474
+ if (!seen.has(k)) { seen.add(k); cols.push(k); }
6430
6475
  }
6431
6476
  }
6432
6477
  } else {
@@ -6453,15 +6498,56 @@ class SQLExecutor {
6453
6498
  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 };
6454
6499
  }
6455
6500
 
6501
+ // P1-18: SELECT *, col —— 星号必须展开为全部列,列名与值对齐。
6502
+ // 此前把 '*' 当成单列输出嵌套数组,导致每行值错位重复/输出 null。
6503
+ if (statement.columns.some(c => c.expr === '*')) {
6504
+ const hasJoins2 = statement.from && statement.from.joins && statement.from.joins.length > 0;
6505
+ let starKeys = [];
6506
+ if (schema && !hasJoins2) {
6507
+ starKeys = Object.keys(schema).filter(k => k !== '_softDelete');
6508
+ } else if (hasJoins2) {
6509
+ // JOIN 时:保留所有带前缀的键,不按裸名去重(否则右表同名列丢失)
6510
+ const seenK = new Set();
6511
+ for (const r of rows) {
6512
+ for (const k of Object.keys(r)) {
6513
+ if (!k.includes('.')) continue;
6514
+ if (!seenK.has(k)) { seenK.add(k); starKeys.push(k); }
6515
+ }
6516
+ }
6517
+ } else {
6518
+ const seenK = new Set();
6519
+ for (const r of rows) {
6520
+ for (const k of Object.keys(r)) {
6521
+ const bare = k.includes('.') ? k.slice(k.indexOf('.') + 1) : k;
6522
+ if (!seenK.has(bare)) { seenK.add(bare); starKeys.push(k); }
6523
+ }
6524
+ }
6525
+ }
6526
+ const cols = [];
6527
+ for (const c of statement.columns) {
6528
+ if (c.expr === '*') { for (const k of starKeys) cols.push(k.includes('.') ? k.slice(k.indexOf('.') + 1) : k); }
6529
+ else cols.push(scalarColumnName(c));
6530
+ }
6531
+ const mapped = await this._projectRows(statement, rows, (r) => {
6532
+ const out = [];
6533
+ for (const c of statement.columns) {
6534
+ if (c.expr === '*') {
6535
+ for (const k of starKeys) out.push(r[k] !== undefined ? r[k] : r[String(k).slice(String(k).indexOf('.') + 1)]);
6536
+ } else if (c.over || (c.scalar && c.scalar.over)) out.push(windowColumnValue(c, r));
6537
+ else if (c.scalar) out.push(projectScalar(resolveOperand(c.scalar, r, this.ctx)));
6538
+ else if (c.literal !== undefined) out.push(c.literal);
6539
+ else if (c.caseExpr) out.push(projectScalar(evaluateCaseVal(c.caseExpr, r)));
6540
+ else out.push(projectScalar(resolveOperand({ type: 'column', name: c.expr }, r, this.ctx)));
6541
+ }
6542
+ return out;
6543
+ });
6544
+ return { ok: true, type: 'select', table: tableName, columns: cols, rows: mapped, raw: rows };
6545
+ }
6546
+
6456
6547
  const cols = statement.columns.map(c => scalarColumnName(c));
6457
6548
  const mapped = await this._projectRows(statement, rows, (r) => statement.columns.map(c => {
6458
6549
  if (c.over || (c.scalar && c.scalar.over)) return windowColumnValue(c, r);
6459
6550
  if (c.scalar) return projectScalar(resolveOperand(c.scalar, r, this.ctx));
6460
- // P1-18: SELECT *, col 星号列输出 null——应展开为所有列
6461
- if (c.expr === '*') {
6462
- // 展开星号:返回行的所有值
6463
- return Object.keys(r).map(k => r[k]);
6464
- }
6465
6551
  if (c.literal !== undefined) return c.literal;
6466
6552
  if (c.caseExpr) return projectScalar(evaluateCaseVal(c.caseExpr, r));
6467
6553
  return projectScalar(resolveOperand({ type: 'column', name: c.expr }, r, this.ctx));
@@ -6604,7 +6690,10 @@ function escapeValue(value) {
6604
6690
  }
6605
6691
  return value.map(escapeValue).join(', ');
6606
6692
  }
6607
- if (typeof value === 'object') return "'" + JSON.stringify(value).replace(/'/g, "\\'") + "'";
6693
+ // P1-25: 对象参数先 JSON 序列化,再走与字符串完全相同的转义通道。
6694
+ // 此前只对单引号做替换,反斜杠原样拼进 SQL 文本,解析时丢失/翻倍,
6695
+ // 导致 C:\temp\x 这类值存成两个反斜杠或直接 JSON 解析失败。
6696
+ if (typeof value === 'object') return escapeValue(JSON.stringify(value));
6608
6697
  const str = String(value)
6609
6698
  .replace(/\\/g, '\\\\')
6610
6699
  .replace(/\0/g, '\\0')
@@ -286,7 +286,8 @@ class Statement {
286
286
 
287
287
  run(...params) {
288
288
  const r = this._call('run', params.length > 0 ? params : undefined);
289
- return { changes: r && r.affectedRows, lastInsertRowid: r && r.insertId, _stmt: this };
289
+ // worker 层返回的是 better-sqlite3 风格的 {changes, lastInsertRowid}
290
+ return { changes: r && typeof r.changes === 'number' ? parseInt(r.changes, 10) : 0, lastInsertRowid: r && (r.lastInsertRowid !== undefined && r.lastInsertRowid !== null) ? r.lastInsertRowid : 0, _stmt: this };
290
291
  }
291
292
 
292
293
  get(...params) {