jsql-neo 6.7.5 → 6.7.7

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.7.5** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
6
+ > **v6.7.7** — 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)
@@ -167,7 +167,7 @@ await db.start();
167
167
  |---|---|---|
168
168
  | Memory | `new Database(':memory:')` | Testing, caching |
169
169
  | Disk | `new Database('./data/app')` | Production persistence |
170
- | Hybrid | `new Database('./data', { autoSave: true, saveInterval: 3000 })` | Performance + durability |
170
+ | Hybrid | `new Database('./data', { mode: 'hybrid', flushInterval: 3000 })` | Performance + durability |
171
171
 
172
172
  File mode (`new Database('./data/db.json')`) is **not** an in-memory store that only
173
173
  writes on exit. Every `insert` / `insertMany` / `update` / `updateById` / `remove` /
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.7.5 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.7.7 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
package/lib/database.js CHANGED
@@ -28,6 +28,7 @@ function errorWithHint(codeKey, hint) {
28
28
  return new JSQL_Error(t.code, msg, { codeKey });
29
29
  }
30
30
  const JSQLFormat = require('./jsql_format');
31
+ const { valuesEqual } = require('./objectid');
31
32
  const {
32
33
  createHookRegistry, applyPlugin, buildPluginContext, registerHook,
33
34
  runHooks, getPluginApis
@@ -295,9 +296,17 @@ class Database {
295
296
  if (!fs.existsSync(file)) return null;
296
297
  try {
297
298
  const fmt = new JSQLFormat(file);
298
- const { rows } = fmt.readTableSync(name);
299
+ fmt._open();
299
300
  const table = new Table(name, meta.schema, this);
300
- if (rows && rows.length > 0) table._loadRows(rows);
301
+ // 行级懒加载:只在内存里保留 {block, off},被访问的行才读盘。
302
+ const locators = fmt.scanLocators(name);
303
+ if (locators.length > 0) {
304
+ table._loadRowRefs(locators, (block, off) => fmt.readRowAt(block, off), fmt);
305
+ } else {
306
+ table._loadRows([]);
307
+ fmt._close();
308
+ }
309
+ if (typeof table._clearDirtyRows === 'function') table._clearDirtyRows();
301
310
  this._tables[name] = table;
302
311
  if (this._versioning) this._versions[name] = [];
303
312
  this._touchTable(name);
@@ -338,7 +347,7 @@ class Database {
338
347
  const names = [...this._dirtyTables];
339
348
  for (const name of names) {
340
349
  try {
341
- this._flushTable(name);
350
+ this._flushTableDelta(name);
342
351
  this._dirtyTables.delete(name);
343
352
  } catch (e) {
344
353
  // 保留脏标记,下次 flush 重试;错误对外传播而非静默
@@ -348,6 +357,53 @@ class Database {
348
357
  this._saveMeta();
349
358
  }
350
359
 
360
+ /**
361
+ * 行级刷盘:只把本表变更过的行追加到表文件,不再整表重写。
362
+ * 无主键表、truncate、schema 变更、回滚等场景退化为全量重写。
363
+ */
364
+ _flushTableDelta(name) {
365
+ const table = this._tables[name];
366
+ if (!table) return;
367
+ const dirty = typeof table._peekDirtyRows === 'function'
368
+ ? table._peekDirtyRows()
369
+ : { all: true, upserts: [], deletes: [] };
370
+
371
+ if (dirty.all) {
372
+ this._flushTable(name);
373
+ return;
374
+ }
375
+ if (dirty.upserts.length === 0 && dirty.deletes.length === 0) {
376
+ table._clearDirtyRows();
377
+ return;
378
+ }
379
+
380
+ const meta = this._meta.tables[name];
381
+ const file = meta && meta.file ? meta.file : encodeURIComponent(name) + '.jsql';
382
+ const fmt = new JSQLFormat(path.join(this._filePath, file));
383
+ let appendBlocks = 0;
384
+ try {
385
+ const written = fmt.writeRows(name, table._schema, dirty.upserts, dirty.deletes, table._primaryKey);
386
+ appendBlocks = fmt.nBlocks;
387
+ this._meta.tables[name] = { file, schema: table._schema };
388
+ if (typeof table._applyFlushedLocators === 'function') {
389
+ if (written && written.length === dirty.upserts.length) {
390
+ table._applyFlushedLocators(dirty.upserts, written);
391
+ } else {
392
+ // 退化成整表写入时行位置全部变化,重建定位符
393
+ table._resetRowLocators(fmt.scanLocators(name));
394
+ }
395
+ }
396
+ table._clearDirtyRows();
397
+ } finally {
398
+ fmt._close();
399
+ }
400
+
401
+ // 空洞块过多时回收:阈值取「行数 2 倍 + 64」,超过则整表重写一次。
402
+ if (appendBlocks > Math.max(64, table._rows.length * 2 + 64)) {
403
+ this._flushTable(name);
404
+ }
405
+ }
406
+
351
407
  _flushTable(name) {
352
408
  const table = this._tables[name];
353
409
  if (!table) return;
@@ -358,6 +414,11 @@ class Database {
358
414
  const pkField = Object.keys(table._schema).find(f => table._schema[f].primaryKey) || null;
359
415
  fmt.writeTable(name, table._schema, table._rows, pkField);
360
416
  this._meta.tables[name] = { file, schema: table._schema };
417
+ // 整表重写改变了每一行的物理位置,用新文件的定位符重置缓存
418
+ if (typeof table._resetRowLocators === 'function') {
419
+ table._resetRowLocators(fmt.scanLocators(name));
420
+ }
421
+ if (typeof table._clearDirtyRows === 'function') table._clearDirtyRows();
361
422
  } finally {
362
423
  fmt._close();
363
424
  }
@@ -385,9 +446,23 @@ class Database {
385
446
  const candidates = Object.keys(this._tables)
386
447
  .filter(n => n !== '__meta__' && !this._versioning && this._meta.tables[n]);
387
448
  candidates.sort((a, b) => (this._lastAccess[a] || 0) - (this._lastAccess[b] || 0));
449
+
450
+ // 先做行级 LRU 淘汰:把冷行回退成磁盘定位符,表结构与索引保持不变。
451
+ // 这一步只在两次同步操作之间触发(定时器回调),不会打断正在进行的查询。
388
452
  for (const name of candidates) {
389
453
  if (budget !== undefined && process.memoryUsage().rss <= budget) break;
390
- try { this._flushTable(name); } catch (e) { continue; }
454
+ const table = this._tables[name];
455
+ if (table && typeof table._evictRows === 'function' && table._rowCache) {
456
+ table._evictRows(Infinity);
457
+ }
458
+ }
459
+
460
+ // 仍超预算时才整表卸载。
461
+ for (const name of candidates) {
462
+ if (budget !== undefined && process.memoryUsage().rss <= budget) break;
463
+ const table = this._tables[name];
464
+ if (table && table._rowCache) continue; // 行级淘汰已足够,保留表对象
465
+ try { this._flushTableDelta(name); } catch (e) { continue; }
391
466
  delete this._tables[name];
392
467
  delete this[name];
393
468
  this._dirtyTables.delete(name);
@@ -719,6 +794,7 @@ class Database {
719
794
  if (typeof t._rebuildPKIndex === 'function') t._rebuildPKIndex();
720
795
  if (typeof t._rebuildAllBTrees === 'function') t._rebuildAllBTrees();
721
796
  for (const field of Object.keys(t._indexes || {})) t.createIndex(field);
797
+ if (typeof t._markAllRowsDirty === 'function') t._markAllRowsDirty();
722
798
  if (t._autoIncrementField) {
723
799
  for (const row of t._rows) {
724
800
  const v = row[t._autoIncrementField];
@@ -1663,6 +1739,7 @@ class Database {
1663
1739
  versions.pop();
1664
1740
  const snapshot = versions[versions.length - 1];
1665
1741
  table._rows = snapshot.rows.map(r => ({ ...r }));
1742
+ if (typeof table._markAllRowsDirty === 'function') table._markAllRowsDirty();
1666
1743
  table._autoIncrement = 0;
1667
1744
  for (const row of table._rows) {
1668
1745
  if (table._autoIncrementField && row[table._autoIncrementField] > table._autoIncrement) {
@@ -1962,13 +2039,21 @@ class Database {
1962
2039
  if (pk) {
1963
2040
  // Issue #44:主键查询值按列类型归一('5' → 5),与索引/insert 保持一致
1964
2041
  const key = typeof table._coerceQueryValue === 'function' ? table._coerceQueryValue(pk, id) : id;
2042
+ // 优先走主键索引:行级懒加载下避免为了取一行而把整表读进内存
2043
+ if (table._pkIndex) {
2044
+ const idx = table._pkIndex.get(key);
2045
+ if (idx !== undefined) {
2046
+ const row = table._rows[idx];
2047
+ if (row && (row[pk] === key || row[pk] === id)) return row;
2048
+ }
2049
+ }
1965
2050
  return table._rows.find(r => r[pk] === key || r[pk] === id) || null;
1966
2051
  }
1967
2052
  // 无主键表:id 是行对象(可能是 find() 返回的浅拷贝)时,用内容匹配代替引用比较。
1968
2053
  // 做法:逐行比对所有字段值是否相等;是数字时当 1-based 行号。
1969
2054
  if (id && typeof id === 'object') {
1970
2055
  const keys = Object.keys(id);
1971
- return table._rows.find(r => keys.every(k => r[k] === id[k])) || null;
2056
+ return table._rows.find(r => keys.every(k => valuesEqual(r[k], id[k]))) || null;
1972
2057
  }
1973
2058
  const idx = Number(id);
1974
2059
  if (!isNaN(idx)) return table._rows[idx - 1] || null;
@@ -2113,10 +2198,20 @@ class Database {
2113
2198
  // 改主键/唯一值时索引必须同步:否则 _pkIndex 还指向旧值,
2114
2199
  // 后续 FK 校验 findOne({id:新值}) 查不到刚更新的父行。
2115
2200
  {
2116
- const rowIndex = table._rows.indexOf(row);
2201
+ // 优先用主键索引定位,避免行级懒加载时 indexOf 把前面的行全部读进内存
2202
+ let rowIndex = -1;
2203
+ if (pk && table._pkIndex) {
2204
+ const oldKey = typeof table._coerceQueryValue === 'function'
2205
+ ? table._coerceQueryValue(pk, row[pk]) : row[pk];
2206
+ const i = table._pkIndex.get(oldKey);
2207
+ if (i !== undefined && table._rows[i] === row) rowIndex = i;
2208
+ }
2209
+ if (rowIndex === -1) rowIndex = table._rows.indexOf(row);
2210
+ const oldPk = pk ? row[pk] : undefined;
2117
2211
  if (rowIndex !== -1) table._removeFromIndexes(rowIndex, row);
2118
2212
  Object.assign(row, validated);
2119
2213
  if (rowIndex !== -1) table._addToIndexes(rowIndex, row);
2214
+ if (typeof table._markRowDirty === 'function') table._markRowDirty(row, oldPk);
2120
2215
  }
2121
2216
  this._walLogUpsert(tableName, [row]);
2122
2217
  this._emit('update', { table: tableName, id, data: validated });
@@ -2138,7 +2233,9 @@ class Database {
2138
2233
  if (row) {
2139
2234
  // CHECK 约束(Issue #70):批量更新同样不能在无校验的情况下写行
2140
2235
  if (typeof table._enforceChecks === 'function') table._enforceChecks({ ...row, ...data });
2236
+ const oldPk = pk ? row[pk] : undefined;
2141
2237
  Object.assign(row, data);
2238
+ if (typeof table._markRowDirty === 'function') table._markRowDirty(row, oldPk);
2142
2239
  count++;
2143
2240
  changed.push(row);
2144
2241
  }
@@ -2207,6 +2304,7 @@ class Database {
2207
2304
  }
2208
2305
  if (targets.length) {
2209
2306
  table._rows = table._rows.filter((_, idx) => !seen.has(idx));
2307
+ if (typeof table._markAllRowsDirty === 'function') table._markAllRowsDirty();
2210
2308
  removed = targets.length;
2211
2309
  }
2212
2310
  table._rebuildPKIndex();
@@ -2229,6 +2327,7 @@ class Database {
2229
2327
  const matched = table._applyFilter(table._getVisibleRows(), filter || {});
2230
2328
  const matchSet = new Set(matched);
2231
2329
  table._rows = table._rows.filter(r => !matchSet.has(r));
2330
+ if (typeof table._markAllRowsDirty === 'function') table._markAllRowsDirty();
2232
2331
  const removed = before - table._rows.length;
2233
2332
  table._rebuildPKIndex();
2234
2333
  table._rebuildAllBTrees();
@@ -2531,6 +2630,10 @@ class Database {
2531
2630
  this._sigInstalled = false;
2532
2631
  Database.removeSignalHandler(this);
2533
2632
  }
2633
+ // 关闭行缓存持有的文件句柄
2634
+ for (const t of Object.values(this._tables)) {
2635
+ if (t && typeof t._detachRowCache === 'function') t._detachRowCache();
2636
+ }
2534
2637
  this._tables = {};
2535
2638
  }
2536
2639
 
@@ -1,6 +1,7 @@
1
1
  const zlib = require('zlib');
2
2
  const crypto = require('crypto');
3
3
  const fs = require('fs');
4
+ const { ObjectId } = require('./objectid');
4
5
 
5
6
 
6
7
  const SZ = {
@@ -12,7 +13,7 @@ const SZ = {
12
13
 
13
14
  const BT = { FREE: 0, DATA: 1, IDX: 2 };
14
15
 
15
- const TYPE = { NUL:0, BOL:1, I32:2, F64:3, STR:4, BUF:5, ARR:6, OBJ:7, I64:8 };
16
+ const TYPE = { NUL:0, BOL:1, I32:2, F64:3, STR:4, BUF:5, ARR:6, OBJ:7, I64:8, DATE:9, OID:10 };
16
17
 
17
18
  function tag(v) {
18
19
  if (v===null||v===undefined) return TYPE.NUL;
@@ -26,8 +27,12 @@ function tag(v) {
26
27
  return TYPE.F64;
27
28
  }
28
29
  if (typeof v==='bigint') return TYPE.I64;
30
+ // Date 必须在通用对象分支之前识别:Object.keys(date) 为空,否则会存成 {}
31
+ if (v instanceof Date) return TYPE.DATE;
29
32
  if (typeof v==='string') return TYPE.STR;
30
33
  if (v instanceof Buffer) return TYPE.BUF;
34
+ // ObjectId 必须在通用对象分支之前识别,否则会退化成普通对象
35
+ if (v instanceof ObjectId) return TYPE.OID;
31
36
  return Array.isArray(v)?TYPE.ARR:TYPE.OBJ;
32
37
  }
33
38
 
@@ -39,6 +44,8 @@ function enc(v) {
39
44
  case TYPE.I32: { const b=Buffer.alloc(5); b[0]=t; b.writeInt32LE(v,1); return b; }
40
45
  case TYPE.I64: { const b=Buffer.alloc(9); b[0]=t; b.writeBigInt64LE(BigInt(v),1); return b; }
41
46
  case TYPE.F64: { const b=Buffer.alloc(9); b[0]=t; b.writeDoubleLE(v,1); return b; }
47
+ case TYPE.DATE: { const b=Buffer.alloc(9); b[0]=t; b.writeBigInt64LE(BigInt(v.getTime()),1); return b; }
48
+ case TYPE.OID: { const b=Buffer.alloc(13); b[0]=t; v.bytes.copy(b,1); return b; }
42
49
  case TYPE.STR: { const s=Buffer.from(v,'utf8'); const b=Buffer.alloc(5+s.length); b[0]=t; b.writeUInt32LE(s.length,1); s.copy(b,5); return b; }
43
50
  case TYPE.BUF: { const b=Buffer.alloc(5+v.length); b[0]=t; b.writeUInt32LE(v.length,1); v.copy(b,5); return b; }
44
51
  case TYPE.ARR: { const p=[Buffer.from([t]),enc(v.length)]; for(const i of v) p.push(enc(i)); return Buffer.concat(p); }
@@ -59,6 +66,8 @@ function dec(buf, off) {
59
66
  return {v: safe ? Number(b) : b, off:off+8};
60
67
  }
61
68
  case TYPE.F64: return {v:buf.readDoubleLE(off),off:off+8};
69
+ case TYPE.DATE: return {v:new Date(Number(buf.readBigInt64LE(off))),off:off+8};
70
+ case TYPE.OID: return {v:new ObjectId(buf.subarray(off,off+12)),off:off+12};
62
71
  case TYPE.STR: { const l=buf.readUInt32LE(off);off+=4; return {v:buf.toString('utf8',off,off+l),off:off+l}; }
63
72
  case TYPE.BUF: { const l=buf.readUInt32LE(off);off+=4; return {v:Buffer.from(buf.subarray(off,off+l)),off:off+l}; }
64
73
  case TYPE.ARR: { let r=dec(buf,off);off=r.off; const l=r.v,a=new Array(l); for(let i=0;i<l;i++){r=dec(buf,off);a[i]=r.v;off=r.off;} return {v:a,off}; }
@@ -111,8 +120,21 @@ function encRowInPlace(row, encoders, scratch, offStart) {
111
120
  }
112
121
 
113
122
  // Build reusable field encoders from schema
114
- function buildEncoders(schema) {
115
- return Object.keys(schema).filter(f => f !== '_softDelete').map(name => ({ name, nameEnc: enc(name) }));
123
+ // 无 schema 的表(如 Mongo collection 以 {} 建表):字段从行数据本身取并集。
124
+ // 否则 0 个编码器会把每一行刷成 4 字节空桩,重载时一行都读不回来。
125
+ // shortcut: 某行缺的字段重载后变 null(不区分「缺字段」和「值为 null」),需要严格区分时再升级
126
+ function buildEncoders(schema, rows) {
127
+ const skip = f => f !== '_softDelete'; // _softDelete 是 schema 配置键,不会是数据字段
128
+ const schemaFields = Object.keys(schema || {}).filter(skip);
129
+ if (schemaFields.length > 0) {
130
+ return schemaFields.map(name => ({ name, nameEnc: enc(name) }));
131
+ }
132
+ const seen = new Set();
133
+ for (const row of rows || []) {
134
+ if (!row) continue;
135
+ for (const f of Object.keys(row)) if (skip(f)) seen.add(f);
136
+ }
137
+ return [...seen].map(name => ({ name, nameEnc: enc(name) }));
116
138
  }
117
139
 
118
140
  const encRow = encRowInPlace;
@@ -224,8 +246,17 @@ class JSQLFormat {
224
246
  _saveIdx(name) {
225
247
  const entries = this.pkIdx.get(name) || [];
226
248
  const maxPerBlock = Math.floor((SZ.DATA - 4) / 12);
227
- let firstBlock = 0, prevBlock = 0;
249
+ if (entries.length === 0) {
250
+ const t0 = this.tables.get(name);
251
+ if (t0) t0.pkBlock = 0;
252
+ return 0;
253
+ }
228
254
 
255
+ // 先为每个分块分配物理块号,再回填 next/prev 指针,最后统一写盘。
256
+ // 旧实现边分配边写:next 指针写进了当前块自身,上一个块永远指向 0,
257
+ // 导致索引超过一个块(335 项)时后续行在重开后不可见。
258
+ const chunks = [];
259
+ const ids = [];
229
260
  for (let chunk = 0; chunk < entries.length; chunk += maxPerBlock) {
230
261
  const chunkEnd = Math.min(chunk + maxPerBlock, entries.length);
231
262
  const buf = Buffer.alloc(SZ.BLOCK);
@@ -240,23 +271,22 @@ class JSQLFormat {
240
271
  buf.writeUInt32LE(e.block, off); off += 4;
241
272
  buf.writeUInt32LE(e.off, off); off += 4;
242
273
  }
274
+ chunks.push(buf);
275
+ ids.push(this._alloc());
276
+ }
243
277
 
244
- const bid = this._alloc();
245
- if (chunk === 0) firstBlock = bid;
246
- if (prevBlock) buf.writeUInt32LE(bid, 52); // next block pointer
247
- buf.writeUInt32LE(prevBlock, 56); // prev block pointer
248
-
249
- // total entry count in first block
250
- if (chunk === 0) buf.writeUInt32LE(entries.length, 48);
251
-
278
+ for (let c = 0; c < chunks.length; c++) {
279
+ const buf = chunks[c];
280
+ buf.writeUInt32LE(c + 1 < ids.length ? ids[c + 1] : 0, 52); // next block
281
+ buf.writeUInt32LE(c > 0 ? ids[c - 1] : 0, 56); // prev block
282
+ if (c === 0) buf.writeUInt32LE(entries.length, 48); // 总条目数
252
283
  finalize(buf);
253
- fs.writeSync(this.fd, buf, 0, SZ.BLOCK, bid * SZ.BLOCK);
254
- prevBlock = bid;
284
+ fs.writeSync(this.fd, buf, 0, SZ.BLOCK, ids[c] * SZ.BLOCK);
255
285
  }
256
286
 
257
287
  const t = this.tables.get(name);
258
- if (t) t.pkBlock = firstBlock;
259
- return firstBlock;
288
+ if (t) t.pkBlock = ids[0];
289
+ return ids[0];
260
290
  }
261
291
 
262
292
  _loadIdx(blockId) {
@@ -345,7 +375,7 @@ class JSQLFormat {
345
375
  mkHeader(BT.DATA, curBlock, tableId).copy(buf);
346
376
 
347
377
  // Pre-build field encoders once per table
348
- const encoders = buildEncoders(schema);
378
+ const encoders = buildEncoders(schema, rows);
349
379
  // Scratch buffer for row encoding (max row size fits in one block)
350
380
  const scratch = Buffer.allocUnsafe(SZ.DATA);
351
381
 
@@ -417,17 +447,172 @@ class JSQLFormat {
417
447
 
418
448
  this._saveSuper();
419
449
  this.dirty = false;
450
+ // 整表重写后回收文件尾部的历史空洞块,否则反复「增量追加 + 压缩」会让
451
+ // 文件只增不减。
452
+ fs.ftruncateSync(this.fd, this.nBlocks * SZ.BLOCK);
420
453
  }
421
454
 
422
455
  writeTable(name, schema, rows, pkField) {
423
456
  this.saveAll({ [name]: { schema, rows, pkField } });
424
457
  }
425
458
 
459
+ // ---- 行级增量写入(hybrid/disk 一行一刷盘) ----
460
+
461
+ _hashRange(entries, hash) {
462
+ let lo = 0, hi = entries.length;
463
+ while (lo < hi) {
464
+ const m = (lo + hi) >>> 1;
465
+ if (entries[m].hash < hash) lo = m + 1; else hi = m;
466
+ }
467
+ return lo;
468
+ }
469
+
470
+ /** 在索引中定位某个主键值的条目,返回下标;未找到返回 -1。 */
471
+ _findEntry(entries, pkValue, pkField) {
472
+ const h = hashPK(pkValue);
473
+ for (let i = this._hashRange(entries, h); i < entries.length && entries[i].hash === h; i++) {
474
+ const row = this._readInBlock(entries[i].block, entries[i].off);
475
+ if (!pkField || row[pkField] === pkValue) return i;
476
+ }
477
+ return -1;
478
+ }
479
+
480
+ _setEntry(entries, entry, pkValue, pkField) {
481
+ const idx = this._findEntry(entries, pkValue, pkField);
482
+ if (idx >= 0) { entries[idx] = entry; return; }
483
+ entries.splice(this._hashRange(entries, entry.hash), 0, entry);
484
+ }
485
+
486
+ _delEntry(entries, pkValue, pkField) {
487
+ const idx = this._findEntry(entries, pkValue, pkField);
488
+ if (idx >= 0) entries.splice(idx, 1);
489
+ }
490
+
491
+ /**
492
+ * 只把变更行追加为独立数据块并更新主键索引,不重写整表。
493
+ * upserts 为最新行(同主键旧索引项被就地替换),deletes 为主键值数组。
494
+ * 旧数据块保留为空洞,由调用方按阈值触发全量重写回收。
495
+ */
496
+ writeRows(name, schema, upserts, deletes, pkField) {
497
+ this._open();
498
+ const t = this.tables.get(name);
499
+ if (!t) {
500
+ if (upserts && upserts.length > 0) this.writeTable(name, schema, upserts, pkField);
501
+ return [];
502
+ }
503
+ if (schema) t.schema = schema;
504
+
505
+ const entries = this.pkIdx.get(name) || [];
506
+ this.pkIdx.set(name, entries);
507
+ const encoders = buildEncoders(t.schema);
508
+ const scratch = Buffer.allocUnsafe(SZ.DATA);
509
+ const written = [];
510
+
511
+ for (const row of upserts || []) {
512
+ const end = encRowInPlace(row, encoders, scratch, 0);
513
+ if (end > SZ.DATA) {
514
+ throw new Error(
515
+ `row in table '${name}' is too large (${end} bytes > max row size ${SZ.DATA} bytes); ` +
516
+ 'split the value or reduce field sizes before saving'
517
+ );
518
+ }
519
+ const bid = this._alloc();
520
+ const buf = Buffer.alloc(SZ.BLOCK);
521
+ mkHeader(BT.DATA, bid, t.tableId).copy(buf);
522
+ const comp = zlib.gzipSync(Buffer.from(scratch.subarray(0, end)), { level: 1 });
523
+ buf.writeUInt32LE(end, 40);
524
+ buf[48] = 1;
525
+ buf.writeUInt32LE(comp.length, 44);
526
+ comp.copy(buf, SZ.HEADER);
527
+ finalize(buf);
528
+ fs.writeSync(this.fd, buf, 0, SZ.BLOCK, bid * SZ.BLOCK);
529
+ t.dataBlock = bid;
530
+ written.push({ block: bid, off: 0 });
531
+
532
+ const pkValue = pkField ? row[pkField] : undefined;
533
+ if (pkValue !== undefined && pkValue !== null) {
534
+ this._setEntry(entries, { hash: hashPK(pkValue), block: bid, off: 0 }, pkValue, pkField);
535
+ }
536
+ }
537
+
538
+ for (const pkValue of deletes || []) {
539
+ if (pkValue !== undefined && pkValue !== null) this._delEntry(entries, pkValue, pkField);
540
+ }
541
+
542
+ t.rowCount = entries.length;
543
+ this._saveIdx(name);
544
+ this._saveSuper();
545
+ return written;
546
+ }
547
+
548
+ /**
549
+ * 扫描某张表,返回所有「有效行」的物理位置(按 readTableSync 的同一顺序)。
550
+ * 只走长度前缀,不 decode 行内容,因此内存占用与行大小无关 —— 供行级
551
+ * 懒加载缓存建立 {block, off} 引用使用。
552
+ */
553
+ scanLocators(name) {
554
+ this._open();
555
+ const t = this.tables.get(name);
556
+ if (!t) return [];
557
+ const entries = this.pkIdx.get(name) || [];
558
+ const pkField = Object.keys(t.schema || {})
559
+ .find(f => t.schema[f] && t.schema[f].primaryKey) || null;
560
+ const live = entries.length > 0
561
+ ? new Set(entries.map(e => `${e.block}:${e.off}`))
562
+ : null;
563
+
564
+ const locs = [];
565
+ for (let bid = 1; bid < this.nBlocks; bid++) {
566
+ const buf = Buffer.alloc(SZ.BLOCK);
567
+ try { fs.readSync(this.fd, buf, 0, SZ.BLOCK, bid * SZ.BLOCK); } catch (e) { continue; }
568
+ if (buf[36] !== BT.DATA || buf[37] !== t.tableId) continue;
569
+ if (!verifyHash(buf)) {
570
+ throw new Error(`[JSQLFormat] Table '${name}': data block ${bid} failed integrity check`);
571
+ }
572
+ const compFlag = buf[48];
573
+ const raw = compFlag
574
+ ? zlib.gunzipSync(buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(44)))
575
+ : buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(40));
576
+
577
+ let off = 0;
578
+ while (off + 4 <= raw.length) {
579
+ const l = raw.readUInt32LE(off);
580
+ if (l === 0 || off + 4 + l > raw.length) break;
581
+ if (!live || live.has(`${bid}:${off}`)) {
582
+ locs.push({ block: bid, off });
583
+ off += 4 + l;
584
+ continue;
585
+ }
586
+ // 不在索引里:可能是旧版本空洞,也可能是没有主键值的行。只有后者要保留。
587
+ const r = decRow(raw, off);
588
+ if (pkField && (r.row[pkField] === undefined || r.row[pkField] === null)) {
589
+ locs.push({ block: bid, off });
590
+ }
591
+ off = r.off;
592
+ }
593
+ }
594
+ return locs;
595
+ }
596
+
597
+ /** 按物理位置读取一行(行级懒加载的最小读单位)。 */
598
+ readRowAt(block, off) {
599
+ this._open();
600
+ return this._readInBlock(block, off);
601
+ }
602
+
426
603
  readTableSync(name) {
427
604
  this._open();
428
605
  const t = this.tables.get(name);
429
606
  if (!t) return { schema: null, rows: [] };
430
607
 
608
+ // 行级增量写入会留下旧版本的「空洞」块;有主键索引时只保留索引指向的
609
+ // 最新行,保证更新/删除后不会读出重复或已删的行。
610
+ const entries = this.pkIdx.get(name) || [];
611
+ const pkField = Object.keys(t.schema || {}).find(f => t.schema[f] && t.schema[f].primaryKey) || null;
612
+ const live = entries.length > 0
613
+ ? new Set(entries.map(e => `${e.block}:${e.off}`))
614
+ : null;
615
+
431
616
  const rows = [];
432
617
  for (let bid = 1; bid < this.nBlocks; bid++) {
433
618
  const buf = Buffer.alloc(SZ.BLOCK);
@@ -450,7 +635,11 @@ class JSQLFormat {
450
635
  const l = raw.readUInt32LE(off);
451
636
  if (l === 0 || off + 4 + l > raw.length) break;
452
637
  const r = decRow(raw, off);
453
- rows.push(r.row);
638
+ // 只有索引指向的最新行有效;无主键值的行无法进索引,保留以免丢数据
639
+ if (!live || live.has(`${bid}:${off}`)
640
+ || (pkField && (r.row[pkField] === undefined || r.row[pkField] === null))) {
641
+ rows.push(r.row);
642
+ }
454
643
  off = r.off;
455
644
  }
456
645
  }