jsql-neo 6.8.13 → 6.8.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  > **One engine to rule them all** — a Rust-powered embedded database that speaks your language:
4
4
  > MySQL, PostgreSQL, MongoDB, Redis, SQL, TypeScript, **and the browser**.
5
5
 
6
- > **v6.8.13** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
6
+ > **v6.8.15** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
7
7
 
8
8
  ![Engines](https://img.shields.io/badge/engines-Native%20%7C%20WASM%20%7C%20Pure%20JS-7ee787)
9
9
  ![MySQL](https://img.shields.io/badge/protocol-MySQL%20compatible-1f6feb)
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.8.13 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.8.15 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
package/lib/database.js CHANGED
@@ -190,6 +190,15 @@ class Database {
190
190
  this._walPath = this._filePath ? this._filePath + '.wal' : null;
191
191
  this._walOps = []; // WAL 操作日志(内存镜像)
192
192
  this._walFlushedCount = 0; // 已落盘记录数(append-only 增量追加用)
193
+ this._walError = null; // #263:最近一次 WAL 落盘失败(供上层查询)
194
+ // #260:目录模式的静态加密(与 legacy 单文件模式语义一致)。
195
+ // _aesKey 是由用户密钥派生的 32 字节 AES-256 密钥。
196
+ this._aesKey = this._encryptKey
197
+ ? crypto.scryptSync(
198
+ Buffer.from(String(this._encryptKey), 'utf8'),
199
+ Buffer.from('jsql-neo-static-encryption-v1', 'utf8'),
200
+ 32)
201
+ : null;
193
202
  this._walReplaying = false; // 回放中:抑制再次写日志
194
203
  this._walReplaySummary = null;
195
204
  this._walOpCount = 0; // 自上次检查点以来的操作数
@@ -201,7 +210,7 @@ class Database {
201
210
 
202
211
  // JSql 格式 (binary block-based)
203
212
  this._jsqlMode = this._filePath && this._filePath.endsWith('.jsql');
204
- this._jsqlFormat = this._jsqlMode ? new JSQLFormat(this._filePath) : null;
213
+ this._jsqlFormat = this._jsqlMode ? new JSQLFormat(this._filePath, this._encryptKey) : null;
205
214
 
206
215
  // 文件锁
207
216
  this._fileLockEnabled = options.fileLock === true && !this._memoryMode;
@@ -247,7 +256,26 @@ class Database {
247
256
  this._meta = { version: 1, tables: {} };
248
257
  try {
249
258
  if (fs.existsSync(this._metaPath)) {
250
- const parsed = JSON.parse(fs.readFileSync(this._metaPath, 'utf8'));
259
+ // #260:meta.json 在启用 encryptKey 时也是密文。
260
+ // 格式:{"__enc":"v1","data":"<base64>"};无密钥时按明文 JSON 读(兼容旧库)。
261
+ const rawMeta = fs.readFileSync(this._metaPath, 'utf8');
262
+ let parsed;
263
+ try {
264
+ parsed = JSON.parse(rawMeta);
265
+ } catch (e) {
266
+ parsed = null;
267
+ }
268
+ if (parsed && parsed.__enc === 'v1' && typeof parsed.data === 'string') {
269
+ if (!this._encryptKey) {
270
+ throw new Error('meta.json is encrypted but no encryptKey was provided');
271
+ }
272
+ const dec = crypto.createDecipheriv('aes-256-cbc', this._aesKey, Buffer.from(parsed.iv, 'base64'));
273
+ const plain = Buffer.concat([
274
+ dec.update(Buffer.from(parsed.data, 'base64')),
275
+ dec.final(),
276
+ ]).toString('utf8');
277
+ parsed = JSON.parse(plain);
278
+ }
251
279
  if (parsed && parsed.tables) {
252
280
  this._meta = parsed;
253
281
  // 清洗 meta 中的 file 字段:拒绝绝对路径/.. 穿越,防恶意 meta.json 写任意位置
@@ -273,6 +301,19 @@ class Database {
273
301
  });
274
302
  }
275
303
  }
304
+ // #259:目录模式(hybrid/disk)显式开启 wal:true 后,写入路径会往
305
+ // `<dir>.wal` 追加并 fsync,但此前**从不回放** —— 只写不读,
306
+ // 崩溃时尚未刷入 .jsql 的提交全部丢失。
307
+ // 这里在启动时回放 WAL,把已 fsync 的提交恢复出来。
308
+ if (this._walEnabled && this._walPath && fs.existsSync(this._walPath)) {
309
+ try {
310
+ this._recoverFromWAL();
311
+ } catch (e) {
312
+ // 回放失败不能静默:记录下来供 getWALInfo() 排障
313
+ this._walReplaySummary = { replayed: 0, failed: 1, error: e.message, at: Date.now() };
314
+ try { this._emit('error', e); } catch (_) { /* ignore */ }
315
+ }
316
+ }
276
317
  this._startMonitor();
277
318
  }
278
319
 
@@ -298,12 +339,49 @@ class Database {
298
339
  _saveMeta() {
299
340
  if (!this._dirMode) return;
300
341
  try {
301
- fs.writeFileSync(this._metaPath, JSON.stringify(this._meta, null, 2), 'utf8');
342
+ // #260:启用 encryptKey 时 meta.json 也落密文(表结构/字段名不外泄)
343
+ if (this._encryptKey) {
344
+ const iv = crypto.randomBytes(16);
345
+ const cipher = crypto.createCipheriv('aes-256-cbc', this._aesKey, iv);
346
+ const enc = Buffer.concat([
347
+ cipher.update(JSON.stringify(this._meta, null, 2), 'utf8'),
348
+ cipher.final(),
349
+ ]);
350
+ const payload = JSON.stringify({
351
+ __enc: 'v1',
352
+ iv: iv.toString('base64'),
353
+ data: enc.toString('base64'),
354
+ });
355
+ fs.writeFileSync(this._metaPath, payload, 'utf8');
356
+ } else {
357
+ fs.writeFileSync(this._metaPath, JSON.stringify(this._meta, null, 2), 'utf8');
358
+ }
302
359
  } catch (e) {
303
360
  // 忽略 meta 写入失败
304
361
  }
305
362
  }
306
363
 
364
+ /**
365
+ * 统一的「表不可用」错误。
366
+ *
367
+ * #262:区分「表不存在」与「表文件损坏」。损坏的表文件加载失败后,
368
+ * 若一律报 ER_NO_SUCH_TABLE,运维看到的是「表没了」,而 meta.json 里
369
+ * 明明还登记着它 —— 极易被误判为「数据被删」。现在报 ER_TABLE_CORRUPT
370
+ * 并带上原始原因。
371
+ */
372
+ _noSuchTable(name) {
373
+ const corrupt = this._corruptTables && this._corruptTables[name];
374
+ if (corrupt) {
375
+ const err = new Error(corrupt.message);
376
+ err.code = 'ER_TABLE_CORRUPT';
377
+ err.errno = corrupt.errno || 1815;
378
+ err.sqlState = 'HY000';
379
+ err.cause = corrupt.cause;
380
+ return err;
381
+ }
382
+ return createError('ER_NO_SUCH_TABLE', name);
383
+ }
384
+
307
385
  _touchTable(name) {
308
386
  this._lastAccess[name] = Date.now();
309
387
  }
@@ -316,7 +394,7 @@ class Database {
316
394
  const file = this._tableFile(name);
317
395
  if (!fs.existsSync(file)) return null;
318
396
  try {
319
- const fmt = new JSQLFormat(file);
397
+ const fmt = new JSQLFormat(file, this._encryptKey);
320
398
  fmt._open();
321
399
  const table = new Table(name, meta.schema, this);
322
400
  // 行级懒加载:只在内存里保留 {block, off},被访问的行才读盘。
@@ -333,6 +411,21 @@ class Database {
333
411
  this._touchTable(name);
334
412
  return table;
335
413
  } catch (e) {
414
+ // #262:加载失败不能静默吞掉。
415
+ // 此前 catch 里直接 return null —— 表文件损坏时表「从查询中消失」,
416
+ // 而 meta.json 仍登记着它,getTables()/hasTable() 报存在、
417
+ // count()/find() 全报缺表,形成自相矛盾的「幽灵表」且无任何告警。
418
+ // 现在:记录损坏状态、发出 error 事件,并让后续查询明确报出损坏原因。
419
+ const err = new Error(
420
+ `Table '${name}' failed to load from '${file}': ${e.message}`
421
+ );
422
+ err.code = 'ER_TABLE_CORRUPT';
423
+ err.errno = 1815;
424
+ err.sqlState = 'HY000';
425
+ err.cause = e;
426
+ this._corruptTables = this._corruptTables || {};
427
+ this._corruptTables[name] = err;
428
+ try { this._emit('error', err); } catch (_) { /* 监听器自身抛错不影响主流程 */ }
336
429
  return null;
337
430
  }
338
431
  }
@@ -410,7 +503,7 @@ class Database {
410
503
 
411
504
  const meta = this._meta.tables[name];
412
505
  const file = meta && meta.file ? meta.file : encodeURIComponent(name) + '.jsql';
413
- const fmt = new JSQLFormat(path.join(this._filePath, file));
506
+ const fmt = new JSQLFormat(path.join(this._filePath, file), this._encryptKey);
414
507
  let appendBlocks = 0;
415
508
  try {
416
509
  const written = fmt.writeRows(name, table._schema, dirty.upserts, dirty.deletes, table._primaryKey);
@@ -440,7 +533,7 @@ class Database {
440
533
  if (!table) return;
441
534
  const meta = this._meta.tables[name];
442
535
  let file = meta && meta.file ? meta.file : encodeURIComponent(name) + '.jsql';
443
- const fmt = new JSQLFormat(path.join(this._filePath, file));
536
+ const fmt = new JSQLFormat(path.join(this._filePath, file), this._encryptKey);
444
537
  let keepHandleOpen = false;
445
538
  try {
446
539
  const pkField = Object.keys(table._schema).find(f => table._schema[f].primaryKey) || null;
@@ -664,8 +757,16 @@ class Database {
664
757
  fs.closeSync(fd);
665
758
  }
666
759
  this._walFlushedCount = this._walOps.length;
760
+ this._walError = null;
667
761
  } catch (e) {
668
- // WAL 写入失败不应阻塞主流程
762
+ // #263:WAL 追加失败不能静默吞掉。
763
+ // WAL 是崩溃安全的前提(README 承诺「kill -9 不会丢已提交的写入」):
764
+ // 磁盘满 / 权限不足 / inode 耗尽时若继续返回成功,
765
+ // 进程崩溃后这批提交就彻底丢失,且事后没有任何线索。
766
+ // 现在至少通过 error 事件暴露出来(与 _flushDirty 的处理一致),
767
+ // 并记入 _walError 供上层查询。
768
+ this._walError = e;
769
+ try { this._emit('error', e); } catch (_) { /* 事件监听器自身抛错不影响主流程 */ }
669
770
  }
670
771
  }
671
772
 
@@ -720,6 +821,25 @@ class Database {
720
821
  return defs;
721
822
  }
722
823
 
824
+ /**
825
+ * WAL 回放时定位目标表(#259)。
826
+ *
827
+ * 目录模式(hybrid/disk)的表是**懒加载**的:meta.json 里登记了表名,
828
+ * 但 `this._tables` 里要等第一次访问才通过 _ensureTable 加载。
829
+ * 回放直接取 `this._tables[op.table]` 会拿到 undefined,
830
+ * 于是 WAL 里的行被写进一个凭空新建的空表(原表数据被覆盖)。
831
+ * 这里统一走 _ensureTable,把已存在的表真正加载出来。
832
+ */
833
+ _walTargetTable(name) {
834
+ if (!name) return null;
835
+ if (this._tables[name]) return this._tables[name];
836
+ if (this._dirMode && this._meta && this._meta.tables && this._meta.tables[name]) {
837
+ const loaded = this._ensureTable(name);
838
+ if (loaded) return loaded;
839
+ }
840
+ return null;
841
+ }
842
+
723
843
  _recoverFromWAL() {
724
844
  if (!this._walEnabled || !this._walPath || !fs.existsSync(this._walPath)) return;
725
845
 
@@ -777,7 +897,10 @@ class Database {
777
897
  try {
778
898
  switch (op.op) {
779
899
  case 'insert': {
780
- let t = op.table && this._tables[op.table];
900
+ // #259:目录模式下表是懒加载的(_tables 里可能还没有),
901
+ // 回放前必须先把它加载出来,否则 WAL 里的行会落到一个
902
+ // 凭空新建的空表上。
903
+ let t = op.table && this._walTargetTable(op.table);
781
904
  if (!t && op.table && Array.isArray(op.rows) && op.rows.length > 0) {
782
905
  this._createTableSync(op.table, this._inferWalSchema(op.rows));
783
906
  t = this._tables[op.table];
@@ -797,7 +920,8 @@ class Database {
797
920
  break;
798
921
  }
799
922
  case 'upsertRows': {
800
- let t = op.table && this._tables[op.table];
923
+ // #259:同上 —— 目录模式先加载已存在的表
924
+ let t = op.table && this._walTargetTable(op.table);
801
925
  if (!t && op.table && Array.isArray(op.rows) && op.rows.length > 0) {
802
926
  this._createTableSync(op.table, this._inferWalSchema(op.rows));
803
927
  t = this._tables[op.table];
@@ -814,7 +938,7 @@ class Database {
814
938
  break;
815
939
  }
816
940
  case 'removeRows': {
817
- const t = op.table && this._tables[op.table];
941
+ const t = op.table && this._walTargetTable(op.table);
818
942
  if (!t || !op.pk || !Array.isArray(op.ids)) { failed++; break; }
819
943
  const gone = new Set(op.ids.map(String));
820
944
  t._rows = t._rows.filter(r => !r || !gone.has(String(r[op.pk])));
@@ -823,7 +947,7 @@ class Database {
823
947
  break;
824
948
  }
825
949
  case 'replaceTable': {
826
- let t = op.table && this._tables[op.table];
950
+ let t = op.table && this._walTargetTable(op.table);
827
951
  if (!t && op.table && Array.isArray(op.rows) && op.rows.length > 0) {
828
952
  this._createTableSync(op.table, this._inferWalSchema(op.rows));
829
953
  t = this._tables[op.table];
@@ -835,7 +959,7 @@ class Database {
835
959
  break;
836
960
  }
837
961
  case 'update': {
838
- const t = this._tables[op.table];
962
+ const t = this._walTargetTable(op.table);
839
963
  if (!t || !op.pk || op.row === undefined) { failed++; break; }
840
964
  const cur = t._rows.find(r => r[op.pk] === op.id);
841
965
  if (!cur) { failed++; break; }
@@ -845,7 +969,7 @@ class Database {
845
969
  break;
846
970
  }
847
971
  case 'remove': {
848
- const t = this._tables[op.table];
972
+ const t = this._walTargetTable(op.table);
849
973
  if (!t || !op.pk) { failed++; break; }
850
974
  const before = t._rows.length;
851
975
  t._rows = t._rows.filter(r => r[op.pk] !== op.id);
@@ -915,8 +1039,22 @@ class Database {
915
1039
  _replayWalOp(op) {
916
1040
  switch (op.op) {
917
1041
  case 'createTable':
1042
+ // #259:目录模式下的两种情形:
1043
+ // a) 表文件已落盘 → 懒加载表对象即可(_walTargetTable)
1044
+ // b) meta.json 已登记但 .jsql 未落盘(崩溃发生在首次刷盘前)
1045
+ // → 需要按 WAL 里的 schema 重建表,否则行数据无处安放。
1046
+ // _createTableSync 会因「meta 里已登记」抛 ER_TABLE_EXISTS_ERROR,
1047
+ // 这里先清掉那条陈旧的 meta 登记再重建。
918
1048
  if (op.table && !this._tables[op.table]) {
919
- this._createTableSync(op.table, op.schema || {});
1049
+ const existing = this._walTargetTable(op.table);
1050
+ if (!existing) {
1051
+ if (this._dirMode && this._meta && this._meta.tables
1052
+ && this._meta.tables[op.table]
1053
+ && !fs.existsSync(this._tableFile(op.table))) {
1054
+ delete this._meta.tables[op.table];
1055
+ }
1056
+ this._createTableSync(op.table, op.schema || {});
1057
+ }
920
1058
  }
921
1059
  return true;
922
1060
 
@@ -1180,17 +1318,39 @@ class Database {
1180
1318
  }
1181
1319
 
1182
1320
  hasTable(name) {
1183
- return !!this._tables[name] || (this._dirMode && !!this._meta.tables[name]);
1321
+ // #262:损坏的表不再报告为「存在」—— 否则 meta 说在、查询说缺表,
1322
+ // 两种状态互相矛盾且没有任何告警。
1323
+ if (this._corruptTables && this._corruptTables[name]) return false;
1324
+ if (this._tables[name]) return true;
1325
+ if (!this._dirMode || !this._meta.tables[name]) return false;
1326
+ // 主动探测:首次访问前损坏状态还没记录,这里触发一次加载判定
1327
+ this._ensureTable(name);
1328
+ return !(this._corruptTables && this._corruptTables[name]);
1184
1329
  }
1185
1330
 
1186
1331
  getTables() {
1187
1332
  const names = new Set(Object.keys(this._tables));
1188
1333
  if (this._dirMode) {
1189
- for (const name of Object.keys(this._meta.tables)) names.add(name);
1334
+ for (const name of Object.keys(this._meta.tables)) {
1335
+ // #262:跳过已确认损坏的表,避免列出「查不到」的幽灵表
1336
+ if (this._corruptTables && this._corruptTables[name]) continue;
1337
+ // 主动探测损坏状态,保证 getTables 与实际可查询状态一致
1338
+ this._ensureTable(name);
1339
+ if (this._corruptTables && this._corruptTables[name]) continue;
1340
+ names.add(name);
1341
+ }
1190
1342
  }
1191
1343
  return [...names];
1192
1344
  }
1193
1345
 
1346
+ /**
1347
+ * 列出损坏的表及其原因(#262)。
1348
+ * @returns {Object<string, Error>} tableName -> 加载错误
1349
+ */
1350
+ getCorruptTables() {
1351
+ return { ...(this._corruptTables || {}) };
1352
+ }
1353
+
1194
1354
  getTableSchema(name) {
1195
1355
  const table = this._ensureTable(name);
1196
1356
  if (table) return table._schema;
@@ -1290,7 +1450,7 @@ class Database {
1290
1450
  */
1291
1451
  importCSV(filePath, tableName, options = {}) {
1292
1452
  const table = this._ensureTable(tableName);
1293
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
1453
+ if (!table) throw this._noSuchTable(tableName);
1294
1454
 
1295
1455
  const delimiter = options.delimiter || ',';
1296
1456
  const hasHeader = options.hasHeader !== false;
@@ -1346,7 +1506,7 @@ class Database {
1346
1506
  */
1347
1507
  exportCSV(filePath, tableName, query = {}, options = {}) {
1348
1508
  const table = this._ensureTable(tableName);
1349
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
1509
+ if (!table) throw this._noSuchTable(tableName);
1350
1510
 
1351
1511
  const delimiter = options.delimiter || ',';
1352
1512
  const rows = table._applyFilter(table._rows, query);
@@ -1885,7 +2045,7 @@ class Database {
1885
2045
  const versions = this._versions[tableName];
1886
2046
  if (!versions || versions.length < 2) throw createError('ER_NOT_SUPPORTED', 'No versions to undo');
1887
2047
  const table = this._ensureTable(tableName);
1888
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2048
+ if (!table) throw this._noSuchTable(tableName);
1889
2049
 
1890
2050
  for (let i = 0; i < steps && versions.length > 1; i++) {
1891
2051
  versions.pop();
@@ -2091,6 +2251,17 @@ class Database {
2091
2251
  for (const fn of this._eventListeners) {
2092
2252
  try { fn(eventName, data); } catch (e) { /* ignore */ }
2093
2253
  }
2254
+ // #263:'error' 事件同时投递给 on('error', fn) 注册的钩子。
2255
+ // on() 走 registerHook(进 _hooks),onEvent() 走 _eventListeners ——
2256
+ // 此前只有后者能收到错误,db.on('error', ...) 永远静默。
2257
+ if (eventName === 'error') {
2258
+ const hooks = this._hooks && this._hooks.error;
2259
+ if (hooks && hooks.length) {
2260
+ for (const entry of hooks) {
2261
+ try { entry.fn(data); } catch (e) { /* ignore */ }
2262
+ }
2263
+ }
2264
+ }
2094
2265
  }
2095
2266
 
2096
2267
  _runHooks(hookName, args) {
@@ -2157,7 +2328,7 @@ class Database {
2157
2328
 
2158
2329
  async insert(tableName, data) {
2159
2330
  const table = this._ensureTable(tableName);
2160
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2331
+ if (!table) throw this._noSuchTable(tableName);
2161
2332
  // #303:beforeInsert 可返回「修改后 data」(PLUGINS.md 契约)。
2162
2333
  // 钩子返回值通过 args 数组原地写回,这里必须读回被替换后的 arr。
2163
2334
  const hookArgs = [tableName, Array.isArray(data) ? data : [data]];
@@ -2217,7 +2388,7 @@ class Database {
2217
2388
 
2218
2389
  async find(tableName, filter, opts = {}) {
2219
2390
  const table = this._ensureTable(tableName);
2220
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2391
+ if (!table) throw this._noSuchTable(tableName);
2221
2392
  if (!(await this._runHooks('beforeFind', [tableName, { filter, opts }]))) return [];
2222
2393
  const { limit, offset = 0 } = opts;
2223
2394
  // P1-4: 软删除模式下不得泄露已删除行——只看可见行
@@ -2241,20 +2412,20 @@ class Database {
2241
2412
  */
2242
2413
  convertToColumnar(tableName) {
2243
2414
  const table = this._ensureTable(tableName);
2244
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2415
+ if (!table) throw this._noSuchTable(tableName);
2245
2416
  return table.toColumnar();
2246
2417
  }
2247
2418
 
2248
2419
  /** 把表转回行存(丢弃列存缓存)。 */
2249
2420
  convertToRow(tableName) {
2250
2421
  const table = this._ensureTable(tableName);
2251
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2422
+ if (!table) throw this._noSuchTable(tableName);
2252
2423
  return table.toRow();
2253
2424
  }
2254
2425
 
2255
2426
  exists(tableName, filter = {}) {
2256
2427
  const table = this._ensureTable(tableName);
2257
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2428
+ if (!table) throw this._noSuchTable(tableName);
2258
2429
  this._touchTable(tableName);
2259
2430
  return table.exists(filter);
2260
2431
  }
@@ -2273,7 +2444,7 @@ class Database {
2273
2444
 
2274
2445
  async findById(tableName, id) {
2275
2446
  const table = this._ensureTable(tableName);
2276
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2447
+ if (!table) throw this._noSuchTable(tableName);
2277
2448
  if (!(await this._runHooks('beforeFind', [tableName, { id }]))) return null;
2278
2449
  const row = this._resolveId(table, id);
2279
2450
  // P1-4: 软删除行对普通读取不可见
@@ -2287,7 +2458,7 @@ class Database {
2287
2458
 
2288
2459
  async findByIds(tableName, ids) {
2289
2460
  const table = this._ensureTable(tableName);
2290
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2461
+ if (!table) throw this._noSuchTable(tableName);
2291
2462
  if (!(await this._runHooks('beforeFind', [tableName, { ids }]))) return null;
2292
2463
  // P1-4: 过滤掉软删除行;P1-11: 返回浅拷贝
2293
2464
  const rows = ids.map(id => this._resolveId(table, id)).filter(r => r !== null && !r._deleted).map(r => ({ ...r }));
@@ -2302,7 +2473,7 @@ class Database {
2302
2473
 
2303
2474
  async count(tableName) {
2304
2475
  const table = this._ensureTable(tableName);
2305
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2476
+ if (!table) throw this._noSuchTable(tableName);
2306
2477
  if (!(await this._runHooks('beforeCount', [tableName]))) return undefined;
2307
2478
  // P1-4: 软删除模式下只统计可见行
2308
2479
  const n = table._softDelete ? table._getVisibleRows().length : table._rows.length;
@@ -2313,7 +2484,7 @@ class Database {
2313
2484
 
2314
2485
  async updateById(tableName, id, data) {
2315
2486
  const table = this._ensureTable(tableName);
2316
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2487
+ if (!table) throw this._noSuchTable(tableName);
2317
2488
  // #303:beforeUpdate 可返回「修改后 data」(PLUGINS.md 契约),
2318
2489
  // 写回后必须用改写后的值继续。
2319
2490
  const hookArgs = [tableName, id, data];
@@ -2354,6 +2525,14 @@ class Database {
2354
2525
  if (table._foreignKeys && table._foreignKeys.length) {
2355
2526
  table._validateForeignKeys({ ...row, ...validated });
2356
2527
  }
2528
+ // #250:updateById 必须与 db.update() 走同一套约束校验。
2529
+ // 此前只补了 CHECK / 复合唯一,漏了 NOT NULL(required)——
2530
+ // 于是 updateById 能把 NULL 写进 NOT NULL 列,而 db.update() 会正确报 1048。
2531
+ // 两条 API 路径必须一致。
2532
+ if (typeof table._validateConstraints === 'function') {
2533
+ const rowIdx = table._rows.indexOf(row);
2534
+ table._validateConstraints({ ...row, ...validated }, rowIdx);
2535
+ }
2357
2536
  // CHECK 约束(Issue #70):Database.updateById 直接 Object.assign 写行,
2358
2537
  // 绕过了 Table.updateById 的约束校验,导致 CHECK 在 UPDATE 上失效。
2359
2538
  if (typeof table._enforceChecks === 'function') {
@@ -2390,7 +2569,7 @@ class Database {
2390
2569
 
2391
2570
  async updateByIds(tableName, entries) {
2392
2571
  const table = this._ensureTable(tableName);
2393
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2572
+ if (!table) throw this._noSuchTable(tableName);
2394
2573
  const pairs = entries.map(([id, data]) => [id, data]);
2395
2574
  if (!(await this._runHooks('beforeUpdate', [tableName, pairs]))) return;
2396
2575
  const pk = this._pkOf(table);
@@ -2417,7 +2596,7 @@ class Database {
2417
2596
 
2418
2597
  async removeById(tableName, id) {
2419
2598
  const table = this._ensureTable(tableName);
2420
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2599
+ if (!table) throw this._noSuchTable(tableName);
2421
2600
  if (!(await this._runHooks('beforeDelete', [tableName, id]))) return;
2422
2601
  if (table._primaryKey) {
2423
2602
  const removed = table.removeById(id);
@@ -2443,7 +2622,7 @@ class Database {
2443
2622
 
2444
2623
  async removeByIds(tableName, ids) {
2445
2624
  const table = this._ensureTable(tableName);
2446
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2625
+ if (!table) throw this._noSuchTable(tableName);
2447
2626
  if (!(await this._runHooks('beforeDelete', [tableName, ids]))) return;
2448
2627
  let removed = 0;
2449
2628
  if (table._primaryKey) {
@@ -2488,7 +2667,7 @@ class Database {
2488
2667
 
2489
2668
  async removeWhere(tableName, filter) {
2490
2669
  const table = this._ensureTable(tableName);
2491
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2670
+ if (!table) throw this._noSuchTable(tableName);
2492
2671
  if (!(await this._runHooks('beforeDelete', [tableName, [filter]]))) return { ok: true, count: 0 };
2493
2672
  const before = table._rows.length;
2494
2673
  // P1-4: 只匹配可见行(软删除行已“不存在”,不应被硬删操作波及)
@@ -2509,7 +2688,7 @@ class Database {
2509
2688
 
2510
2689
  async insertMany(tableName, items) {
2511
2690
  const table = this._ensureTable(tableName);
2512
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2691
+ if (!table) throw this._noSuchTable(tableName);
2513
2692
  const arr = Array.isArray(items) ? items : [items];
2514
2693
  if (!(await this._runHooks('beforeInsert', [tableName, arr]))) return [];
2515
2694
  const inserted = table.insertMany(arr);
@@ -2522,7 +2701,7 @@ class Database {
2522
2701
 
2523
2702
  async update(tableName, query, updates) {
2524
2703
  const table = this._ensureTable(tableName);
2525
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2704
+ if (!table) throw this._noSuchTable(tableName);
2526
2705
  if (!(await this._runHooks('beforeUpdate', [tableName, query, updates]))) return 0;
2527
2706
  const count = table.update(query, updates);
2528
2707
  // WAL 由 Table.update() 记录
@@ -2534,7 +2713,7 @@ class Database {
2534
2713
 
2535
2714
  async delete(tableName, query = {}) {
2536
2715
  const table = this._ensureTable(tableName);
2537
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2716
+ if (!table) throw this._noSuchTable(tableName);
2538
2717
  if (!(await this._runHooks('beforeDelete', [tableName, query]))) return 0;
2539
2718
  // WAL 由 Table.remove() 记录
2540
2719
  const count = table.remove(query);
@@ -2546,7 +2725,7 @@ class Database {
2546
2725
 
2547
2726
  truncate(tableName) {
2548
2727
  const table = this._ensureTable(tableName);
2549
- if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2728
+ if (!table) throw this._noSuchTable(tableName);
2550
2729
  // #206:被外键引用的父表禁止 TRUNCATE(MySQL 1701),也不应触发级联
2551
2730
  if (this._foreignReferencingRows(tableName).length > 0) {
2552
2731
  throw createError('ER_TRUNCATE_ILLEGAL_FK', tableName);