jsql-neo 6.8.27 → 6.10.2

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.
Files changed (139) hide show
  1. package/README.md +9 -4
  2. package/bin/jsql-server-control.js +58 -14
  3. package/index.d.ts +3 -0
  4. package/index.js +1 -1
  5. package/lib/bigint_json.js +13 -1
  6. package/lib/btree.js +12 -3
  7. package/lib/cache.js +12 -1
  8. package/lib/database.js +272 -36
  9. package/lib/jsql_format.js +22 -9
  10. package/lib/migrate.js +184 -98
  11. package/lib/mod.js +48 -13
  12. package/lib/mongo_server.js +652 -246
  13. package/lib/mysql_compat.js +54 -11
  14. package/lib/mysql_server.js +248 -65
  15. package/lib/nedb_compat.js +7 -1
  16. package/lib/objectid.js +14 -6
  17. package/lib/pg_server.js +385 -9
  18. package/lib/plugin.js +34 -3
  19. package/lib/query.js +12 -6
  20. package/lib/redis_server.js +102 -42
  21. package/lib/sql.js +446 -48
  22. package/lib/table.js +111 -41
  23. package/lib/tui.js +28 -9
  24. package/lib/web_ui.js +33 -2
  25. package/package.json +4 -4
  26. package/test/alter-table.test.js +11 -5
  27. package/test/compat-v1.test.js +1 -1
  28. package/test/extra-coverage.test.js +6 -7
  29. package/test/issue-258-300.test.js +6 -0
  30. package/test/issue-312-320.test.js +11 -4
  31. package/test/issue-326.test.js +42 -0
  32. package/test/issue-327-418.test.js +1 -1
  33. package/test/issue-336.test.js +56 -0
  34. package/test/issue-353.test.js +34 -0
  35. package/test/issue-356.test.js +27 -0
  36. package/test/issue-357-365.test.js +1 -1
  37. package/test/issue-361.test.js +55 -0
  38. package/test/issue-370.test.js +43 -0
  39. package/test/issue-373.test.js +40 -0
  40. package/test/issue-374.test.js +62 -0
  41. package/test/issue-378.test.js +39 -0
  42. package/test/issue-379.test.js +39 -0
  43. package/test/issue-38.test.js +2 -2
  44. package/test/issue-380.test.js +27 -0
  45. package/test/issue-383-402.test.js +4 -3
  46. package/test/issue-384.test.js +41 -0
  47. package/test/issue-392.test.js +25 -0
  48. package/test/issue-397.test.js +44 -0
  49. package/test/issue-403.test.js +47 -0
  50. package/test/issue-404.test.js +58 -0
  51. package/test/issue-407.test.js +40 -0
  52. package/test/issue-408.test.js +92 -0
  53. package/test/issue-409.test.js +32 -0
  54. package/test/issue-410.test.js +36 -0
  55. package/test/issue-411.test.js +38 -0
  56. package/test/issue-412.test.js +50 -0
  57. package/test/issue-414.test.js +46 -0
  58. package/test/issue-417.test.js +56 -0
  59. package/test/issue-420.test.js +87 -0
  60. package/test/issue-421.test.js +30 -0
  61. package/test/issue-422.test.js +33 -0
  62. package/test/issue-424.test.js +44 -0
  63. package/test/issue-425.test.js +22 -0
  64. package/test/issue-426.test.js +22 -0
  65. package/test/issue-427.test.js +36 -0
  66. package/test/issue-429.test.js +38 -0
  67. package/test/issue-431.test.js +41 -0
  68. package/test/issue-432.test.js +37 -0
  69. package/test/issue-436.test.js +47 -0
  70. package/test/issue-445-449.test.js +14 -7
  71. package/test/issue-455-459.test.js +6 -3
  72. package/test/issue-474.test.js +59 -0
  73. package/test/issue-475.test.js +38 -0
  74. package/test/issue-476.test.js +50 -0
  75. package/test/issue-477.test.js +54 -0
  76. package/test/issue-478.test.js +52 -0
  77. package/test/issue-479.test.js +44 -0
  78. package/test/issue-480.test.js +42 -0
  79. package/test/issue-481.test.js +51 -0
  80. package/test/issue-482.test.js +36 -0
  81. package/test/issue-483.test.js +57 -0
  82. package/test/issue-485.test.js +47 -0
  83. package/test/issue-486.test.js +69 -0
  84. package/test/issue-487.test.js +54 -0
  85. package/test/issue-488.test.js +69 -0
  86. package/test/issue-490.test.js +20 -0
  87. package/test/issue-491.test.js +21 -0
  88. package/test/issue-492.test.js +19 -0
  89. package/test/issue-493.test.js +30 -0
  90. package/test/issue-494.test.js +82 -0
  91. package/test/issue-495.test.js +86 -0
  92. package/test/issue-496.test.js +98 -0
  93. package/test/issue-497.test.js +29 -0
  94. package/test/issue-498.test.js +32 -0
  95. package/test/issue-499.test.js +41 -0
  96. package/test/issue-500.test.js +39 -0
  97. package/test/issue-501-506.test.js +29 -0
  98. package/test/issue-502.test.js +18 -0
  99. package/test/issue-503.test.js +43 -0
  100. package/test/issue-504.test.js +83 -0
  101. package/test/issue-505.test.js +29 -0
  102. package/test/issue-529.test.js +39 -0
  103. package/test/issue-530.test.js +69 -0
  104. package/test/issue-536.test.js +46 -0
  105. package/test/issue-537.test.js +52 -0
  106. package/test/issue-539.test.js +65 -0
  107. package/test/issue-540.test.js +31 -0
  108. package/test/issue-545.test.js +38 -0
  109. package/test/issue-546.test.js +68 -0
  110. package/test/issue-547.test.js +27 -0
  111. package/test/issue-548.test.js +68 -0
  112. package/test/issue-549.test.js +26 -0
  113. package/test/issue-550.test.js +52 -0
  114. package/test/issue-551.test.js +34 -0
  115. package/test/issue-552.test.js +30 -0
  116. package/test/issue-553.test.js +29 -0
  117. package/test/issue-554.test.js +29 -0
  118. package/test/issue-555.test.js +22 -0
  119. package/test/issue-556.test.js +25 -0
  120. package/test/issue-565.test.js +32 -0
  121. package/test/issue-566.test.js +30 -0
  122. package/test/issue-567.test.js +56 -0
  123. package/test/issue-568.test.js +46 -0
  124. package/test/issue-569.test.js +25 -0
  125. package/test/issue-570.test.js +30 -0
  126. package/test/issue-571.test.js +32 -0
  127. package/test/issue-572.test.js +64 -0
  128. package/test/issue-573.test.js +71 -0
  129. package/test/issue-574.test.js +63 -0
  130. package/test/issue-581.test.js +46 -0
  131. package/test/issue-59.test.js +17 -4
  132. package/test/issue-69-70.test.js +1 -1
  133. package/test/issue-mysql-harness.js +260 -0
  134. package/test/issue-pg5-helper.js +135 -0
  135. package/test/mongo-arrays.test.js +63 -0
  136. package/test/mongo-objectid.test.js +2 -2
  137. package/test/mongo-persistence.test.js +3 -3
  138. package/test/mongo-update-dates.test.js +128 -0
  139. package/test/wal-recovery.test.js +17 -9
@@ -12,18 +12,61 @@ function isQueryResult(r) {
12
12
  return !!r && typeof r === 'object' && Array.isArray(r.rows) && Array.isArray(r.columns);
13
13
  }
14
14
 
15
- function toResultPacket(r, table, rowsAsArray) {
15
+ // #407:引擎 SQL 类型名 → MySQL 二进制协议类型码
16
+ function sqlTypeToMysqlType(t) {
17
+ const s = String(t || '').toLowerCase();
18
+ if (!s) return null;
19
+ if (s.startsWith('tinyint(1)') || s === 'bool' || s === 'boolean') return 1;
20
+ if (s === 'int' || s === 'integer' || s === 'bigint' || s === 'smallint' || s === 'mediumint') return 8;
21
+ if (s === 'float' || s === 'double' || s === 'real' || s.startsWith('decimal')) return 5;
22
+ if (s === 'datetime' || s === 'date' || s === 'timestamp' || s === 'time') return 12;
23
+ if (s === 'json') return 245;
24
+ if (s.startsWith('varchar') || s === 'text' || s === 'string') return 253;
25
+ return null;
26
+ }
27
+
28
+ // #407:样本值兜底推断;识别 ISO 日期串与 0/1 字面量以外的真实类型
29
+ function valueToMysqlType(val) {
30
+ if (val === null || val === undefined) return null;
31
+ if (typeof val === 'boolean') return 1;
32
+ if (typeof val === 'bigint' || (typeof val === 'number' && Number.isInteger(val))) return 8;
33
+ if (typeof val === 'number') return 5;
34
+ if (val instanceof Date) return 12;
35
+ if (Buffer.isBuffer(val)) return 252;
36
+ if (typeof val === 'string' && /^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?)?$/.test(val)) return 12;
37
+ return 253;
38
+ }
39
+
40
+ // #407:SELECT TRUE/FALSE 被引擎归一成 1/0,只能从 SQL 文本识别布尔列
41
+ function booleanColumnsFromSql(sql) {
42
+ const set = new Set();
43
+ if (!sql) return set;
44
+ const m = String(sql).match(/^\s*SELECT\s+([\s\S]*?)(?:\s+FROM\b|$)/i);
45
+ if (!m) return set;
46
+ for (const part of m[1].split(',')) {
47
+ const bm = part.trim().match(/^(TRUE|FALSE)\b(?:\s+(?:AS\s+)?([A-Za-z_][\w$]*))?$/i);
48
+ if (bm) set.add((bm[2] || bm[1]).toLowerCase());
49
+ }
50
+ return set;
51
+ }
52
+
53
+ function toResultPacket(r, table, rowsAsArray, sql) {
16
54
  if (isQueryResult(r)) {
17
55
  const columns = r.columns || [];
18
56
  const rawRows = r.rows || [];
19
- // P3-9: fields 类型全 253——根据实际类型设置
20
- const fields = columns.map(name => {
21
- let type = 253; // VAR_STRING
22
- const val = rawRows[0] ? rawRows[0][columns.indexOf(name)] : null;
23
- if (typeof val === 'number') type = Number.isInteger(val) ? 8 : 5; // LONGLONG / DOUBLE(Issue #48:浮点列曾被误报为 8)
24
- else if (typeof val === 'boolean') type = 1; // TINY
25
- else if (val instanceof Date) type = 12; // DATETIME
26
- else if (Buffer.isBuffer(val)) type = 252; // BLOB
57
+ // #407:优先用引擎 columnTypes / SQL 布尔字面量,再采样首个非空行
58
+ const boolCols = booleanColumnsFromSql(sql);
59
+ const fields = columns.map((name, ci) => {
60
+ let type = null;
61
+ if (boolCols.has(String(name).toLowerCase())) type = 1;
62
+ if (type === null && Array.isArray(r.columnTypes)) type = sqlTypeToMysqlType(r.columnTypes[ci]);
63
+ if (type === null) {
64
+ for (let i = 0; i < rawRows.length; i++) {
65
+ const sample = valueToMysqlType(rawRows[i] && rawRows[i][ci]);
66
+ if (sample !== null) { type = sample; break; }
67
+ }
68
+ }
69
+ if (type === null) type = 253; // VAR_STRING
27
70
  return {
28
71
  name,
29
72
  table: table || '',
@@ -156,7 +199,7 @@ class Connection extends EventEmitter {
156
199
  if (results.length > 1) {
157
200
  // mysql2 多语句:返回结果数组,每项是 [rows, fields] 或结果包
158
201
  return results.map((res) => {
159
- const pk = toResultPacket(res, res ? res.table : null, rowsAsArray);
202
+ const pk = toResultPacket(res, res ? res.table : null, rowsAsArray, finalSql);
160
203
  if (isQueryResult(res)) {
161
204
  const a = [pk.rows, pk.fields];
162
205
  a.rows = pk.rows;
@@ -170,7 +213,7 @@ class Connection extends EventEmitter {
170
213
  });
171
214
  }
172
215
  const last = results[results.length - 1];
173
- const packet = toResultPacket(last, last ? last.table : null, rowsAsArray);
216
+ const packet = toResultPacket(last, last ? last.table : null, rowsAsArray, finalSql);
174
217
  if (isQueryResult(last)) {
175
218
  const arr = [packet.rows, packet.fields];
176
219
  arr.rows = packet.rows;
@@ -93,6 +93,9 @@ const CLIENT_MULTI_STATEMENTS = 0x00010000;
93
93
  const CLIENT_MULTI_RESULTS = 0x00020000;
94
94
  const CLIENT_LONG_FLAG = 0x00000004;
95
95
  const CLIENT_DEPRECATE_EOF = 0x01000000;
96
+ const CLIENT_SSL = 0x00000800; // #425
97
+ const UNIQUE_KEY_FLAG = 0x0004; // #490
98
+ const BLOB_FLAG = 0x0010; // #491
96
99
  const SERVER_STATUS_AUTOCOMMIT = 0x0002;
97
100
  const SERVER_STATUS_IN_TRANS = 0x0001; // #372
98
101
  const SERVER_MORE_RESULTS_EXISTS = 0x0008;
@@ -107,10 +110,11 @@ function charsetNrByName(name) {
107
110
  return CHARSET_UTF8;
108
111
  }
109
112
 
110
- const MYSQL_TYPE_TINY = 1, MYSQL_TYPE_LONG = 3, MYSQL_TYPE_LONGLONG = 8,
111
- MYSQL_TYPE_DATE = 10, MYSQL_TYPE_DATETIME = 12, MYSQL_TYPE_DOUBLE = 5,
112
- MYSQL_TYPE_STRING = 254, MYSQL_TYPE_VAR_STRING = 253, MYSQL_TYPE_BLOB = 252,
113
- MYSQL_TYPE_JSON = 245, MYSQL_TYPE_NULL = 6;
113
+ const MYSQL_TYPE_TINY = 1, MYSQL_TYPE_SHORT = 2, MYSQL_TYPE_LONG = 3,
114
+ MYSQL_TYPE_LONGLONG = 8, MYSQL_TYPE_INT24 = 9, MYSQL_TYPE_DATE = 10,
115
+ MYSQL_TYPE_YEAR = 13, MYSQL_TYPE_NEWDATE = 14, MYSQL_TYPE_DATETIME = 12,
116
+ MYSQL_TYPE_DOUBLE = 5, MYSQL_TYPE_STRING = 254, MYSQL_TYPE_VAR_STRING = 253,
117
+ MYSQL_TYPE_BLOB = 252, MYSQL_TYPE_JSON = 245, MYSQL_TYPE_NULL = 6;
114
118
 
115
119
  function encodeLenenc(value) {
116
120
  if (typeof value === 'bigint') value = Number(value);
@@ -224,7 +228,7 @@ function eofPacket(status = SERVER_STATUS_AUTOCOMMIT) {
224
228
  function mysqlSqlState(errno) {
225
229
  return ({
226
230
  1048: '23000', 1050: '42S01', 1054: '42S22', 1062: '23000',
227
- 1064: '42000', 1102: '42000', 1136: '21S01', 1146: '42S02',
231
+ 1064: '42000', 1065: '42000', 1102: '42000', 1136: '21S01', 1146: '42S02',
228
232
  1264: '22003', 1406: '22001', 3819: 'HY000',
229
233
  })[errno] || 'HY000';
230
234
  }
@@ -313,34 +317,53 @@ function columnFlags(def) {
313
317
  let flags = 0;
314
318
  if (def.required || def.primaryKey || def.primary_key || def.autoIncrement) flags |= 0x0001; // NOT_NULL
315
319
  if (def.primaryKey || def.primary_key) flags |= 0x0002; // PRI_KEY
320
+ if (def.unique && !def.primaryKey && !def.primary_key) flags |= UNIQUE_KEY_FLAG; // #490 唯一键
316
321
  if (def.autoIncrement) flags |= 0x0200; // AUTO_INCREMENT
317
322
  if (def.unsigned) flags |= 0x0020; // UNSIGNED
323
+ if (isBlobColumn(def)) flags |= BLOB_FLAG; // #491 TEXT/BLOB 列
318
324
  return flags;
319
325
  }
320
326
 
327
+ // #491/#554:引擎把 TEXT/TINYINT/SMALLINT 折叠成 string/integer,
328
+ // 原始声明宽度保存在 rawType/intType 中,按它细分协议类型码。
329
+ function isBlobColumn(def) {
330
+ const raw = def && def.rawType ? String(def.rawType).toLowerCase() : '';
331
+ return raw === 'text' || raw === 'tinytext' || raw === 'mediumtext' || raw === 'longtext'
332
+ || raw === 'blob' || raw === 'tinyblob' || raw === 'mediumblob' || raw === 'longblob'
333
+ || (def && def.type === 'binary');
334
+ }
335
+
321
336
  function columnTypeFromSchema(def) {
322
337
  const type = def && def.type ? String(def.type).toLowerCase() : 'string';
323
- if (type === 'bigint' || (def && def.intType === 'bigint')) return MYSQL_TYPE_LONGLONG;
338
+ const raw = def && def.rawType ? String(def.rawType).toLowerCase() : '';
339
+ if (type === 'bigint' || (def && def.intType === 'bigint') || raw === 'bigint') return MYSQL_TYPE_LONGLONG;
340
+ if (raw === 'tinyint') return MYSQL_TYPE_TINY; // #554
341
+ if (raw === 'smallint') return MYSQL_TYPE_SHORT; // #554
324
342
  if (type === 'integer' || type === 'int') return MYSQL_TYPE_LONG;
325
343
  if (type === 'number' || type === 'float' || type === 'double' || type === 'real' || type === 'numeric' || type === 'decimal') return MYSQL_TYPE_DOUBLE;
326
344
  if (type === 'boolean' || type === 'bool') return MYSQL_TYPE_TINY;
327
345
  if (type === 'date') return MYSQL_TYPE_DATE;
328
346
  if (type === 'datetime' || type === 'timestamp') return MYSQL_TYPE_DATETIME;
329
347
  if (type === 'object' || type === 'array') return MYSQL_TYPE_JSON;
330
- if (type === 'binary') return MYSQL_TYPE_BLOB;
348
+ if (isBlobColumn(def)) return MYSQL_TYPE_BLOB; // #491
331
349
  return MYSQL_TYPE_VAR_STRING;
332
350
  }
333
351
 
334
352
  function resultSetPacket(result, tableSchema, baseSeq, rawRow, status = SERVER_STATUS_AUTOCOMMIT, charsetNr = CHARSET_UTF8) {
335
353
  const packets = [];
336
354
  let sequence = baseSeq || 0;
337
- const push = (buf) => {
338
- const header = Buffer.alloc(4);
339
- header.writeUIntLE(buf.length, 0, 3);
340
- header[3] = sequence;
341
- sequence++;
342
- packets.push(header);
343
- packets.push(buf);
355
+ const push = (buf) => { // #408: 单个包超过 16MB 时切分为 0xffffff 的续传分片
356
+ let off = 0;
357
+ do {
358
+ const part = buf.slice(off, off + 0xffffff);
359
+ const header = Buffer.alloc(4);
360
+ header.writeUIntLE(part.length, 0, 3);
361
+ header[3] = sequence;
362
+ sequence = (sequence + 1) & 0xff;
363
+ packets.push(header);
364
+ packets.push(part);
365
+ off += part.length;
366
+ } while (off < buf.length);
344
367
  };
345
368
 
346
369
  const inferType = (name, value) => {
@@ -396,16 +419,46 @@ function resultSetPacket(result, tableSchema, baseSeq, rawRow, status = SERVER_S
396
419
  return { packets, sequence };
397
420
  }
398
421
 
399
- function binaryResultSetPacket(result, tableSchema, baseSeq, status = SERVER_STATUS_AUTOCOMMIT, charsetNr = CHARSET_UTF8) {
422
+ // #373: 二进制结果行编码,EXECUTE(游标) 与 COM_STMT_FETCH 共用同一套布局
423
+ function pushBinaryRows(push, rows, cols, types, encodeValue, start, count) {
424
+ const end = Math.min(start + count, rows.length);
425
+ for (let i = start; i < end; i++) {
426
+ const row = rows[i];
427
+ const parts = [Buffer.from([0x00])];
428
+ const nb = Buffer.alloc(Math.ceil((cols.length + 2) / 8));
429
+ const encoded = [];
430
+ for (let c = 0; c < cols.length; c++) {
431
+ const v = Array.isArray(row) ? row[c] : row[cols[c]];
432
+ if (v === null || v === undefined) {
433
+ const bit = c + 2; // 二进制协议 NULL bitmap 前两位保留
434
+ nb[Math.floor(bit / 8)] |= (1 << (bit % 8));
435
+ encoded.push(null);
436
+ } else {
437
+ encoded.push(encodeValue(v, types[c]));
438
+ }
439
+ }
440
+ parts.push(nb);
441
+ for (const e of encoded) if (e !== null) parts.push(e);
442
+ push(Buffer.concat(parts));
443
+ }
444
+ return end;
445
+ }
446
+
447
+ function binaryResultSetPacket(result, tableSchema, baseSeq, status = SERVER_STATUS_AUTOCOMMIT, charsetNr = CHARSET_UTF8, cursor = false) {
400
448
  const packets = [];
401
449
  let sequence = baseSeq || 0;
402
- const push = (buf) => {
403
- const header = Buffer.alloc(4);
404
- header.writeUIntLE(buf.length, 0, 3);
405
- header[3] = sequence;
406
- sequence++;
407
- packets.push(header);
408
- packets.push(buf);
450
+ const push = (buf) => { // #408: 单个包超过 16MB 时切分为 0xffffff 的续传分片
451
+ let off = 0;
452
+ do {
453
+ const part = buf.slice(off, off + 0xffffff);
454
+ const header = Buffer.alloc(4);
455
+ header.writeUIntLE(part.length, 0, 3);
456
+ header[3] = sequence;
457
+ sequence = (sequence + 1) & 0xff;
458
+ packets.push(header);
459
+ packets.push(part);
460
+ off += part.length;
461
+ } while (off < buf.length);
409
462
  };
410
463
 
411
464
  const inferType = (name, value) => {
@@ -458,8 +511,19 @@ function binaryResultSetPacket(result, tableSchema, baseSeq, status = SERVER_STA
458
511
  if (bi < INT64_MIN) bi = INT64_MIN;
459
512
  const b = Buffer.alloc(8); b.writeBigInt64LE(bi, 0); return b;
460
513
  }
461
- if (type === MYSQL_TYPE_TINY) {
462
- const b = Buffer.alloc(1); b.writeInt8(v ? 1 : 0, 0); return b;
514
+ if (type === MYSQL_TYPE_TINY) { // #554: TINYINT 可能被声明为 TINY,按数值而非布尔编码
515
+ let n = typeof v === 'boolean' ? (v ? 1 : 0) : Math.trunc(Number(v));
516
+ if (!Number.isFinite(n)) n = 0;
517
+ if (n > 127) n = 127;
518
+ if (n < -128) n = -128;
519
+ const b = Buffer.alloc(1); b.writeInt8(n, 0); return b;
520
+ }
521
+ if (type === MYSQL_TYPE_SHORT) { // #554: SMALLINT 声明为 SHORT,按 2 字节整数编码
522
+ let n = Math.trunc(Number(v));
523
+ if (!Number.isFinite(n)) n = 0;
524
+ if (n > 32767) n = 32767;
525
+ if (n < -32768) n = -32768;
526
+ const b = Buffer.alloc(2); b.writeInt16LE(n, 0); return b;
463
527
  }
464
528
  if (type === MYSQL_TYPE_DATE || type === MYSQL_TYPE_DATETIME) {
465
529
  const s = String(v);
@@ -482,26 +546,12 @@ function binaryResultSetPacket(result, tableSchema, baseSeq, status = SERVER_STA
482
546
  return encodeLenencString(typeof v === 'object' ? JSON.stringify(v) : v);
483
547
  };
484
548
 
485
- for (const row of result.rows || []) {
486
- const parts = [Buffer.from([0x00])];
487
- const nb = Buffer.alloc(Math.ceil((cols.length + 2) / 8));
488
- const encoded = [];
489
- for (let i = 0; i < cols.length; i++) {
490
- const v = Array.isArray(row) ? row[i] : row[cols[i]];
491
- if (v === null || v === undefined) {
492
- // binary protocol 的 NULL bitmap 前两位保留,列从 bit 2 开始
493
- const bit = i + 2;
494
- nb[Math.floor(bit / 8)] |= (1 << (bit % 8));
495
- encoded.push(null);
496
- } else {
497
- encoded.push(encodeValue(v, types[i]));
498
- }
499
- }
500
- parts.push(nb);
501
- for (const e of encoded) if (e !== null) parts.push(e);
502
- push(Buffer.concat(parts));
549
+ if (cursor) {
550
+ // #373: 游标 EXECUTE 只下发列元数据,数据行留给 COM_STMT_FETCH
551
+ return { packets, sequence, cursorData: { result, cols, types, pos: 0, encodeValue } };
503
552
  }
504
- push(eofPacket());
553
+ pushBinaryRows(push, result.rows || [], cols, types, encodeValue, 0, Infinity);
554
+ push(eofPacket(status)); // #426 与文本路径/列定义 EOF 使用同一状态位
505
555
  return { packets, sequence };
506
556
  }
507
557
 
@@ -513,6 +563,10 @@ class MysqlConnection {
513
563
  this.seed = genSeed(20);
514
564
  this.buffer = Buffer.alloc(0);
515
565
  this.sequence = 0;
566
+ this._fragParts = null; // #408 入站分片重组缓冲
567
+ this._fragLen = 0;
568
+ this._skipBytes = 0;
569
+ this._skipFragments = false;
516
570
  this.authenticated = false;
517
571
  this.user = null;
518
572
  this.authFails = 0;
@@ -560,32 +614,66 @@ class MysqlConnection {
560
614
 
561
615
  _send(payload) {
562
616
  if (!this.socket.writable) return;
563
- const header = Buffer.alloc(4);
564
- header.writeUIntLE(payload.length, 0, 3);
565
- header[3] = this.sequence;
566
- this.sequence = (this.sequence + 1) & 0xff;
567
- this.socket.write(Buffer.concat([header, payload]));
617
+ // #408: 出站超过 16MB 时按 0xffffff 分片,避免 3 字节长度字段被截断
618
+ let off = 0;
619
+ do {
620
+ const part = payload.slice(off, off + 0xffffff);
621
+ const header = Buffer.alloc(4);
622
+ header.writeUIntLE(part.length, 0, 3);
623
+ header[3] = this.sequence;
624
+ this.sequence = (this.sequence + 1) & 0xff;
625
+ this.socket.write(Buffer.concat([header, part]));
626
+ off += part.length;
627
+ } while (off < payload.length);
568
628
  }
569
629
 
570
630
  _onData(chunk) {
571
631
  this.buffer = Buffer.concat([this.buffer, chunk]);
572
632
  this._armIdleTimer();
573
- if (this.buffer.length > this.server.maxPacketSize + 4) {
574
- this._malicious('packet exceeds maxPacketSize (' + this.server.maxPacketSize + ')');
575
- return;
576
- }
577
633
  while (true) {
634
+ if (this._skipBytes > 0) { // 丢弃超限包的剩余字节(可能跨多次 data 事件)
635
+ const n = Math.min(this._skipBytes, this.buffer.length);
636
+ this.buffer = this.buffer.slice(n);
637
+ this._skipBytes -= n;
638
+ if (this._skipBytes > 0) return;
639
+ if (!this._skipFragments) continue;
640
+ }
641
+ if (this._skipFragments) { // 丢弃超限消息的后续续片,不再重复报错
642
+ if (this.buffer.length < 4) return;
643
+ const len = this.buffer.readUIntLE(0, 3);
644
+ if (this.buffer.length < 4 + len) return;
645
+ this.buffer = this.buffer.slice(4 + len);
646
+ if (len < 0xffffff) this._skipFragments = false;
647
+ continue;
648
+ }
578
649
  if (this.buffer.length < 4) return;
579
650
  const len = this.buffer.readUIntLE(0, 3);
580
- if (len > this.server.maxPacketSize) {
581
- this._malicious('packet length ' + len + ' exceeds maxPacketSize');
582
- return;
651
+ const seq = this.buffer[3];
652
+ const accumulated = this._fragLen + len;
653
+ // #408: 超限先回 1153 ERR_Packet,不直接销毁连接;丢弃整条(含续片)消息
654
+ if (len > this.server.maxPacketSize || accumulated > this.server.maxPacketSize) {
655
+ this.sequence = (seq + 1) & 0xff;
656
+ this._send(errPacket(1153, 'Got a packet bigger than \'max_allowed_packet\' bytes'));
657
+ this._fragParts = null;
658
+ this._fragLen = 0;
659
+ this._skipFragments = (len === 0xffffff);
660
+ this._skipBytes = len + 4;
661
+ continue;
583
662
  }
584
663
  if (this.buffer.length < 4 + len) return;
585
- const seq = this.buffer[3];
586
664
  const payload = this.buffer.slice(4, 4 + len);
587
665
  this.buffer = this.buffer.slice(4 + len);
588
- this._handlePacket(payload, seq);
666
+ if (len === 0xffffff) { // 续传分片,等后续包重组
667
+ if (!this._fragParts) { this._fragParts = []; this._fragLen = 0; }
668
+ this._fragParts.push(payload);
669
+ this._fragLen += payload.length;
670
+ continue;
671
+ }
672
+ const full = this._fragParts && this._fragParts.length
673
+ ? Buffer.concat(this._fragParts.concat([payload])) : payload;
674
+ this._fragParts = null;
675
+ this._fragLen = 0;
676
+ this._handlePacket(full, seq);
589
677
  if (this.socket.destroyed) return;
590
678
  }
591
679
  }
@@ -630,6 +718,20 @@ class MysqlConnection {
630
718
  }
631
719
  case 0x11: this._handleChangeUser(body, cmdSeq); break; // COM_CHANGE_USER
632
720
  case 0x0e: this._send(okPacket()); break; // COM_PING
721
+ case 0x0d: { // #392 COM_PROCESS_KILL:按 connection_id 终止会话
722
+ if (body.length < 4) { this._send(errPacket(1105, 'malformed COM_PROCESS_KILL')); break; }
723
+ const targetId = body.readUInt32LE(0);
724
+ const target = this.server._connections.get(targetId);
725
+ if (!target) { this._send(errPacket(1094, `Unknown thread id: ${targetId}`)); break; }
726
+ if (this.server.auth && target.user !== this.user) {
727
+ this._send(errPacket(1045, 'Access denied; you need the SUPER privilege for this operation'));
728
+ break;
729
+ }
730
+ this._send(okPacket());
731
+ if (target === this) target.socket.end(); // 先冲刷 OK 再关闭自身
732
+ else target.socket.destroy();
733
+ break;
734
+ }
633
735
  case 0x1f: { // COM_RESET_CONNECTION —— #457:释放预处理句柄并复位会话状态
634
736
  this._stmts.clear();
635
737
  this._stmtSeq = 0;
@@ -648,6 +750,22 @@ class MysqlConnection {
648
750
  case 0x18: this._handleStmtSendLongData(body); break; // COM_STMT_SEND_LONG_DATA
649
751
  case 0x19: this._handleStmtClose(body); break; // COM_STMT_CLOSE
650
752
  case 0x1a: this._handleStmtReset(body); break; // COM_STMT_RESET
753
+ case 0x1c: { // #373 COM_STMT_FETCH:从游标句柄批量取行
754
+ if (body.length < 8) { this._send(errPacket(1105, 'malformed COM_STMT_FETCH')); break; }
755
+ const stmtId = body.readUInt32LE(0);
756
+ const numRows = body.readUInt32LE(4);
757
+ const stmt = this._stmts.get(stmtId);
758
+ if (!stmt) {
759
+ this._send(errPacket(1243, 'Unknown prepared statement handler (' + stmtId + ') given to mysqld_stmt_fetch'));
760
+ break;
761
+ }
762
+ const cur = stmt.cursor;
763
+ if (!cur) { this._send(errPacket(1105, 'No cursor is open for this statement')); break; }
764
+ const rows = Array.isArray(cur.result.rows) ? cur.result.rows : [];
765
+ cur.pos = pushBinaryRows((buf) => this._send(buf), rows, cur.cols, cur.types, cur.encodeValue, cur.pos, numRows);
766
+ this._send(eofPacket(SERVER_STATUS_AUTOCOMMIT | (this._inTransaction ? SERVER_STATUS_IN_TRANS : 0)));
767
+ break;
768
+ }
651
769
  case 0x0a: { // COM_PROCESS_INFO
652
770
  const seq = this.sequence;
653
771
  this.sequence = (this.sequence + 1) & 0xff;
@@ -660,7 +778,14 @@ class MysqlConnection {
660
778
  this._send(eofPacket());
661
779
  break;
662
780
  }
663
- case 0x09: this._send(okPacket(0, 0, SERVER_STATUS_AUTOCOMMIT)); break; // COM_STATISTICS
781
+ case 0x09: { // COM_STATISTICS —— 回统计字符串包,非 OK 包
782
+ const stats = 'Uptime: ' + Math.floor(process.uptime()) +
783
+ ' Threads: ' + this.server._sockets.size +
784
+ ' Questions: ' + this.session.foundRows +
785
+ ' Slow queries: 0 Opens: 0 Flush tables: 1 Open tables: 0 Queries per second avg: 0.000';
786
+ this._send(Buffer.from(stats, 'utf8'));
787
+ break;
788
+ }
664
789
  case 0x04: { // #307 COM_FIELD_LIST
665
790
  (async () => {
666
791
  try {
@@ -737,11 +862,21 @@ class MysqlConnection {
737
862
 
738
863
  async _handleAuth(payload) {
739
864
  try {
865
+ if (payload.length < 32) throw new Error('malformed handshake response');
740
866
  const caps = payload.readUInt32LE(0);
867
+ // #425:SSLRequest 是仅含 32 字节固定头、无用户名/认证响应的包,
868
+ // 不能按登录包解析。服务端未启用 TLS,回 ERR 并结束握手。
869
+ if ((caps & CLIENT_SSL) && payload.length <= 32) {
870
+ this.server._onSecurityEvent({ type: 'ssl-unsupported', remote: this.socket.remoteAddress });
871
+ this._send(errPacket(1043, 'SSL is not supported by this server'));
872
+ this.socket.end();
873
+ return;
874
+ }
741
875
  let pos = 32; // 4 caps + 4 maxpacket + 1 charset + 23 reserved
742
876
  // #393:登录包字符集字节(偏移 8)记入会话,作为初始结果集 charsetNr
743
877
  if (payload.length > 8) this.session.charsetNr = payload[8] || CHARSET_UTF8;
744
878
  const userEnd = payload.indexOf(0, pos);
879
+ if (userEnd === -1) throw new Error('malformed handshake response: missing username');
745
880
  this.user = payload.slice(pos, userEnd).toString('utf8');
746
881
  pos = userEnd + 1;
747
882
  let authResponse = Buffer.alloc(0);
@@ -879,7 +1014,7 @@ class MysqlConnection {
879
1014
  } catch (e) { /* 无法解析的 SQL 仍可 prepare */ }
880
1015
  const numColumns = colDefs.length;
881
1016
  const stmtId = ++this._stmtSeq;
882
- this._stmts.set(stmtId, { sql, numParams, numColumns, columnDefs: colDefs, types: null, longData: new Map() });
1017
+ this._stmts.set(stmtId, { sql, numParams, numColumns, columnDefs: colDefs, types: null, longData: new Map(), cursor: null });
883
1018
 
884
1019
  const pkt = Buffer.alloc(12);
885
1020
  let off = 0;
@@ -932,6 +1067,7 @@ class MysqlConnection {
932
1067
  if (stmt) {
933
1068
  stmt.types = null;
934
1069
  stmt.longData.clear();
1070
+ stmt.cursor = null; // #373
935
1071
  }
936
1072
  }
937
1073
  this._send(okPacket());
@@ -947,6 +1083,8 @@ class MysqlConnection {
947
1083
  return;
948
1084
  }
949
1085
  const flags = body[4];
1086
+ const useCursor = (flags & 0x03) !== 0; // #373: CURSOR_TYPE_READ_ONLY / FOR_UPDATE
1087
+ if (!useCursor) stmt.cursor = null;
950
1088
  const iteration = body.readUInt32LE(5);
951
1089
  let values = null;
952
1090
  if (stmt.numParams > 0) {
@@ -990,7 +1128,7 @@ class MysqlConnection {
990
1128
  }
991
1129
  }
992
1130
  // #211:COM_STMT_EXECUTE 的结果集恒为二进制格式,即使没有占位符
993
- this._handleQuery(stmt.sql, values !== null && values.length > 0 ? values : undefined, true);
1131
+ this._handleQuery(stmt.sql, values !== null && values.length > 0 ? values : undefined, true, useCursor ? stmt : null);
994
1132
  } catch (e) {
995
1133
  this._send(errPacket(toMysqlErrno(e), e.message));
996
1134
  }
@@ -1011,6 +1149,21 @@ class MysqlConnection {
1011
1149
  const v = unsigned ? buf.readUInt32LE(off) : buf.readInt32LE(off);
1012
1150
  return { value: v, off: off + 4 };
1013
1151
  }
1152
+ case MYSQL_TYPE_INT24: { // #424: MEDIUMINT,3 字节小端
1153
+ const v = buf.readUIntLE(off, 3);
1154
+ return { value: v, off: off + 3 };
1155
+ }
1156
+ case MYSQL_TYPE_YEAR: { // #424: YEAR,2 字节小端
1157
+ return { value: buf.readUInt16LE(off), off: off + 2 };
1158
+ }
1159
+ case MYSQL_TYPE_NEWDATE: { // #424: NEWDATE,7 字节日期时间结构
1160
+ const year = buf.readUInt16LE(off);
1161
+ const mo = buf[off + 2], day = buf[off + 3];
1162
+ const hh = buf[off + 4], mi = buf[off + 5], ss = buf[off + 6];
1163
+ const value = String(year).padStart(4, '0') + '-' + String(mo).padStart(2, '0') + '-' + String(day).padStart(2, '0')
1164
+ + ' ' + String(hh).padStart(2, '0') + ':' + String(mi).padStart(2, '0') + ':' + String(ss).padStart(2, '0');
1165
+ return { value, off: off + 7 };
1166
+ }
1014
1167
  case 0x08: { // LONGLONG
1015
1168
  const v = unsigned ? buf.readBigUInt64LE(off) : buf.readBigInt64LE(off);
1016
1169
  return { value: Number(v), off: off + 8 };
@@ -1059,7 +1212,7 @@ class MysqlConnection {
1059
1212
  }
1060
1213
  }
1061
1214
 
1062
- _handleQuery(sql, values, binary = false) {
1215
+ _handleQuery(sql, values, binary = false, cursorStmt = null) {
1063
1216
  (async () => {
1064
1217
  try {
1065
1218
  // #393:SET NAMES <charset> [COLLATE ...] 同时切换 client/connection/results 字符集
@@ -1086,6 +1239,30 @@ class MysqlConnection {
1086
1239
  const status = SERVER_STATUS_AUTOCOMMIT
1087
1240
  | (this._inTransaction ? SERVER_STATUS_IN_TRANS : 0)
1088
1241
  | (si < statements.length - 1 ? SERVER_MORE_RESULTS_EXISTS : 0);
1242
+ // #497: mysql.user 虚拟表 —— doc/mysql.md 承诺的内部认证元数据,
1243
+ // 引擎没有该物理表,在协议层直接构造结果集,避免误报 1146。
1244
+ const mysqlUserMatch = /\bfrom\s+mysql\.user\b/i.exec(stmtSql);
1245
+ if (mysqlUserMatch) {
1246
+ const selectPart = /^\s*select\s+([\s\S]+)$/i.exec(stmtSql.slice(0, mysqlUserMatch.index));
1247
+ const allCols = ['User', 'Host', 'authentication_string'];
1248
+ const selected = selectPart && selectPart[1].trim() !== '*'
1249
+ ? selectPart[1].split(',').map(s => s.trim().replace(/^`|`$/g, ''))
1250
+ : allCols;
1251
+ const auth = this.server.auth;
1252
+ const users = auth && typeof auth === 'object' ? Object.keys(auth) : [];
1253
+ const rows = users.map(u => [u, '%', '']);
1254
+ const pickedRows = rows.map(r => selected.map(c => {
1255
+ const idx = allCols.findIndex(x => x.toLowerCase() === String(c).toLowerCase());
1256
+ return idx >= 0 ? r[idx] : null;
1257
+ }));
1258
+ const virtual = { type: 'select', columns: selected, rows: pickedRows };
1259
+ const { packets, sequence } = binary
1260
+ ? binaryResultSetPacket(virtual, null, this.sequence, status, this.session.charsetNr)
1261
+ : resultSetPacket(virtual, null, this.sequence, null, status, this.session.charsetNr);
1262
+ this.sequence = sequence;
1263
+ this.socket.write(Buffer.concat(packets));
1264
+ continue;
1265
+ }
1089
1266
  const stmt = parseSQL(stmtSql);
1090
1267
  switch (stmt.type) {
1091
1268
  case 'use': {
@@ -1163,10 +1340,11 @@ class MysqlConnection {
1163
1340
  ? await engine.getTableSchema(r.table)
1164
1341
  : (engine._schemas ? engine._schemas[r.table] : null);
1165
1342
  }
1166
- const { packets, sequence } = binary
1167
- ? binaryResultSetPacket(r, schema, this.sequence, status, this.session.charsetNr)
1343
+ const { packets, sequence, cursorData } = binary
1344
+ ? binaryResultSetPacket(r, schema, this.sequence, status, this.session.charsetNr, !!cursorStmt)
1168
1345
  : resultSetPacket(r, schema, this.sequence, null, status, this.session.charsetNr);
1169
1346
  this.sequence = sequence;
1347
+ if (cursorData) cursorStmt.cursor = cursorData; // #373: 保存游标句柄供 FETCH 使用
1170
1348
  this.socket.write(Buffer.concat(packets));
1171
1349
  } else {
1172
1350
  // #372:BEGIN 之后置位,COMMIT/ROLLBACK 之后清零;OK 包按执行后的状态回
@@ -1213,6 +1391,7 @@ class MysqlServer {
1213
1391
  this._defaultDbName = options.defaultDatabase || 'default';
1214
1392
  this._connectionCounter = 0;
1215
1393
  this._sockets = new Set();
1394
+ this._connections = new Map(); // #392: connectionId → MysqlConnection
1216
1395
  this._securityHandler = typeof options.onSecurityEvent === 'function' ? options.onSecurityEvent : null;
1217
1396
  }
1218
1397
 
@@ -1491,8 +1670,12 @@ class MysqlServer {
1491
1670
  return;
1492
1671
  }
1493
1672
  this._sockets.add(socket);
1494
- socket.on('close', () => this._sockets.delete(socket));
1495
- new MysqlConnection(socket, this);
1673
+ const conn = new MysqlConnection(socket, this);
1674
+ this._connections.set(conn.connectionId, conn);
1675
+ socket.on('close', () => {
1676
+ this._sockets.delete(socket);
1677
+ this._connections.delete(conn.connectionId);
1678
+ });
1496
1679
  });
1497
1680
  this._server.once('error', err => {
1498
1681
  if (err && err.code === 'EADDRINUSE') {
@@ -169,9 +169,15 @@ function applyModifier(doc, update, opts = {}) {
169
169
  } else if (op === '$unset') {
170
170
  for (const k of Object.keys(payload)) unsetPath(doc, k);
171
171
  } else if (op === '$inc') {
172
+ // #412:$inc 的现有值与操作数都必须是数值,否则按 Mongo 协议报错
173
+ const isNumeric = (x) => typeof x === 'number' && Number.isFinite(x);
172
174
  for (const [k, v] of Object.entries(payload)) {
175
+ if (!isNumeric(v)) throw new Error('Cannot apply $inc to a value of non-numeric type');
173
176
  const cur = getPath(doc, k);
174
- setPath(doc, k, (Number(cur) || 0) + v);
177
+ if (cur !== undefined && !isNumeric(cur)) {
178
+ throw new Error('Cannot apply $inc to a value of non-numeric type');
179
+ }
180
+ setPath(doc, k, (cur === undefined ? 0 : cur) + v);
175
181
  }
176
182
  } else if (op === '$mul') {
177
183
  for (const [k, v] of Object.entries(payload)) {
package/lib/objectid.js CHANGED
@@ -78,22 +78,30 @@ class ObjectId {
78
78
  }
79
79
 
80
80
  /**
81
- * 严格 === 语义的 ObjectId 扩展:
81
+ * 严格 === 语义的 ObjectId / Date / Buffer / 数组扩展:
82
82
  * 同字节 ObjectId 相等;ObjectId 与 String 永不相等(这正是本修复点);
83
- * 其余保持 === 。热路径先走 ===,零开销。
83
+ * Date 按 getTime() 相等;Buffer 按字节内容相等(a.equals);
84
+ * 数组逐元素递归(长度先比)——{a:[1,2]} 整数组等值 / $in:[[$elem]] /
85
+ * $ne / $all 全靠这一处。shortcut: 数组内嵌套普通对象仍是引用严格相等,
86
+ * 需要子文档深度等值时再升级(wire 端子文档条件已由 deepEqualMongo 覆盖)。
87
+ * 热路径先走 ===,标量零额外开销。
84
88
  */
85
89
  function valuesEqual(a, b) {
86
90
  if (a === b) return true;
87
91
  if (a instanceof ObjectId && b instanceof ObjectId) return a.equals(b);
92
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
93
+ if (Buffer.isBuffer(a) && Buffer.isBuffer(b)) return a.equals(b);
94
+ if (Array.isArray(a) && Array.isArray(b)) {
95
+ return a.length === b.length && a.every((x, i) => valuesEqual(x, b[i]));
96
+ }
88
97
  return false;
89
98
  }
90
99
 
91
- /** $in/$nin:普通值用 includes 快路径,仅当查询值是 ObjectId 时才逐项比较。 */
100
+ /** $in/$nin:普通值用 includes 快路径,未命中再走 valuesEqual(ObjectId 按字节、
101
+ * Date/Buffer/数组按内容——$in: [[1,2]] 这类整数组元素靠这里)。 */
92
102
  function arrayIncludesValue(arr, v) {
93
103
  if (arr.includes(v)) return true;
94
- if (v instanceof ObjectId) {
95
- for (const t of arr) if (t instanceof ObjectId && t.equals(v)) return true;
96
- }
104
+ for (const t of arr) if (valuesEqual(t, v)) return true;
97
105
  return false;
98
106
  }
99
107