jsql-neo 6.7.3 → 6.7.6

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/lib/table.js CHANGED
@@ -6,6 +6,7 @@
6
6
 
7
7
  const Query = require('./query');
8
8
  const BTree = require('./btree');
9
+ const { createRowCache } = require('./row_cache');
9
10
  const { validateDateType, now } = require('./date-types');
10
11
  const { createError, JSQL_Error } = require('./errors');
11
12
 
@@ -200,7 +201,10 @@ class Table {
200
201
  this._name = name;
201
202
  this._schema = schema;
202
203
  this._db = db;
203
- this._rows = [];
204
+ // 行级懒加载缓存(仅 hybrid/disk 目录模式启用);普通模式下为 null,
205
+ // `_rows` 就是普通数组。
206
+ this._rowCache = null;
207
+ this.__rows = [];
204
208
  this._indexes = {}; // 旧版 hash 索引(兼容)
205
209
  this._btrees = {}; // B-Tree 索引 { fieldName: BTree }
206
210
  this._autoIncrement = 0;
@@ -213,6 +217,13 @@ class Table {
213
217
  this._softDelete = false;
214
218
  this._computedFields = {};
215
219
 
220
+ // 行级脏标记(仅 hybrid/disk 目录模式使用):刷盘时只写变更行,
221
+ // 不再整表重写。`_dirtyUpserts` 存行对象引用(更新是原地修改,
222
+ // 取用时的值即最新值),`_dirtyDeletes` 存被删除的主键值。
223
+ this._dirtyUpserts = new Set();
224
+ this._dirtyDeletes = new Set();
225
+ this._dirtyAll = false;
226
+
216
227
  // 列式存储缓存(一键转换)。`_rows` 始终是权威数据;列存只是
217
228
  // 「每个字段一个数组」的查询加速视图,任何写入都会把它置空,
218
229
  // 因此不可能出现两份数据不一致。
@@ -281,6 +292,95 @@ class Table {
281
292
  this._autoCreateBTrees();
282
293
  }
283
294
 
295
+ // `_rows` 通过访问器暴露:任何整体替换(_loadRows / truncate / WAL 回放)
296
+ // 都会自动丢弃行缓存,避免旧的定位符继续指向已被重写的文件。
297
+ get _rows() {
298
+ return this.__rows;
299
+ }
300
+
301
+ set _rows(rows) {
302
+ this._detachRowCache();
303
+ this.__rows = rows;
304
+ }
305
+
306
+ _detachRowCache() {
307
+ const cache = this._rowCache;
308
+ this._rowCache = null;
309
+ this._rowReader = null;
310
+ if (cache) cache.close();
311
+ }
312
+
313
+ /**
314
+ * 用磁盘定位符初始化行级懒加载。
315
+ * @param {Array<{block:number, off:number}>} locators - 有效行位置(顺序同 readTableSync)
316
+ * @param {(block:number, off:number) => object} loader - 单行读取函数
317
+ * @param {object} [reader] - 底层 JSQLFormat 句柄(缓存丢弃时一并关闭)
318
+ */
319
+ _loadRowRefs(locators, loader, reader) {
320
+ this._detachRowCache();
321
+ const cache = createRowCache(this, locators, loader, () => {
322
+ if (reader && typeof reader._close === 'function') {
323
+ try { reader._close(); } catch (e) { /* 忽略关闭失败 */ }
324
+ }
325
+ });
326
+ this.__rows = cache.rows;
327
+ this._rowCache = cache;
328
+ this._rowReader = reader || null;
329
+ this._rebuildRowMetaStreaming();
330
+ }
331
+
332
+ /** 从磁盘逐行读取并重建主键索引 / B-Tree / 自增计数,不把整表留在内存。 */
333
+ _rebuildRowMetaStreaming() {
334
+ const cache = this._rowCache;
335
+ if (!cache) return;
336
+
337
+ if (this._autoIncrementField) {
338
+ const field = this._autoIncrementField;
339
+ let max = this._autoIncrement;
340
+ cache.scan(row => {
341
+ const v = row[field];
342
+ if (typeof v === 'number' && v > max) max = v;
343
+ });
344
+ this._autoIncrement = max;
345
+ }
346
+
347
+ if (this._pkIndex && this._primaryKey) {
348
+ const field = this._primaryKey;
349
+ this._pkIndex.clear();
350
+ cache.scan((row, i) => {
351
+ const v = row[field];
352
+ if (v !== undefined && v !== null) this._pkIndex.set(v, i);
353
+ });
354
+ }
355
+
356
+ for (const field of Object.keys(this._btrees)) {
357
+ const tree = this._btrees[field];
358
+ tree.clear();
359
+ cache.scan((row, i) => {
360
+ const v = row[field];
361
+ if (v !== undefined && v !== null) tree.insert(v, i);
362
+ });
363
+ }
364
+
365
+ for (const field of Object.keys(this._indexes)) this.createIndex(field);
366
+ }
367
+
368
+ /** 供 Database 在内存压力下按 LRU 逐行淘汰;返回实际淘汰行数。 */
369
+ _evictRows(max) {
370
+ if (!this._rowCache) return 0;
371
+ return this._rowCache.evict(max === undefined ? Infinity : max);
372
+ }
373
+
374
+ /** 整表重写后刷新全部定位符(行顺序不变)。 */
375
+ _resetRowLocators(locators) {
376
+ if (this._rowCache) this._rowCache.reset(locators);
377
+ }
378
+
379
+ /** 行级刷盘后更新被写入行的定位符。 */
380
+ _applyFlushedLocators(rows, locators) {
381
+ if (this._rowCache) this._rowCache.applyLocators(rows, locators);
382
+ }
383
+
284
384
  // P1-2: DDL 后统一刷新 schema 缓存。
285
385
  // dropColumn/renameColumn 过去只改 _cachedSchemaFields,unique/required/numeric/
286
386
  // date/computed 缓存残留旧列 → insertMany 等路径拿到陈旧 schema 直接崩溃或漏校验。
@@ -415,6 +515,8 @@ class Table {
415
515
  hook(data);
416
516
  }
417
517
  this._db._emitChange('insert', this._name, data);
518
+ this._db._walLogUpsert(this._name, [data]);
519
+ this._markRowDirty(this._rows[rowIndex]);
418
520
 
419
521
  return data;
420
522
  }
@@ -537,6 +639,8 @@ class Table {
537
639
  for (let i = 0; i < N; i++) hook(result[i]);
538
640
  }
539
641
  this._db._emitChange('insertMany', this._name, { count: N });
642
+ this._db._walLogUpsert(this._name, result);
643
+ for (let i = 0; i < N; i++) this._markRowDirty(this._rows[this._rows.length - N + i]);
540
644
  return result;
541
645
  }
542
646
 
@@ -638,6 +742,7 @@ class Table {
638
742
  this._removeFromIndexes(index, oldData);
639
743
  Object.assign(this._rows[index], updates);
640
744
  this._addToIndexes(index, this._rows[index]);
745
+ this._markRowDirty(this._rows[index], this._primaryKey ? oldData[this._primaryKey] : undefined);
641
746
  count++;
642
747
  }
643
748
 
@@ -648,6 +753,7 @@ class Table {
648
753
  hook(query, updates, count);
649
754
  }
650
755
  this._db._emitChange('update', this._name, { query, updates, count });
756
+ this._db._walLogUpsert(this._name, matched);
651
757
  }
652
758
  return count;
653
759
  }
@@ -690,6 +796,8 @@ class Table {
690
796
  hook({ [this._primaryKey]: id }, updates, 1);
691
797
  }
692
798
  this._db._emitChange('update', this._name, { query: { [this._primaryKey]: id }, updates, count: 1 });
799
+ this._db._walLogUpsert(this._name, [row]);
800
+ this._markRowDirty(row, oldData[this._primaryKey]);
693
801
  return 1;
694
802
  }
695
803
 
@@ -754,6 +862,12 @@ class Table {
754
862
  hook(query, count);
755
863
  }
756
864
  this._db._emitChange('remove', this._name, { query, count });
865
+ this._db._walLogRemove(this._name, toRemove);
866
+ if (this._primaryKey) {
867
+ for (const row of toRemove) this._markRowDeleted(row[this._primaryKey]);
868
+ } else {
869
+ this._markAllRowsDirty();
870
+ }
757
871
  }
758
872
  return count;
759
873
  }
@@ -815,6 +929,8 @@ class Table {
815
929
  hook({ [this._primaryKey]: id }, 1);
816
930
  }
817
931
  this._db._emitChange('remove', this._name, { query: { [this._primaryKey]: id }, count: 1 });
932
+ this._db._walLogRemove(this._name, [row]);
933
+ this._markRowDeleted(row[this._primaryKey]);
818
934
  return 1;
819
935
  }
820
936
 
@@ -839,6 +955,8 @@ class Table {
839
955
  hook(query, count);
840
956
  }
841
957
  this._db._emitChange('remove', this._name, { query, count, soft: true });
958
+ this._db._walLogUpsert(this._name, matched);
959
+ for (const row of matched) this._markRowDirty(row);
842
960
  }
843
961
  return count;
844
962
  }
@@ -884,6 +1002,8 @@ class Table {
884
1002
  // P1-13: truncate 不应重置软删除模式——保留原值
885
1003
  this._dirty = true;
886
1004
  this._db._markDirty(this._name);
1005
+ this._db._walLogReplaceTable(this._name);
1006
+ this._markAllRowsDirty();
887
1007
  return count;
888
1008
  }
889
1009
 
@@ -936,6 +1056,7 @@ class Table {
936
1056
  this._refreshSchemaCache();
937
1057
  this._dirty = true;
938
1058
  this._db._markDirty(this._name);
1059
+ this._markAllRowsDirty(); // schema 变更:整表重写
939
1060
  return this;
940
1061
  }
941
1062
 
@@ -961,6 +1082,7 @@ class Table {
961
1082
  this._refreshSchemaCache();
962
1083
  this._dirty = true;
963
1084
  this._db._markDirty(this._name);
1085
+ this._markAllRowsDirty(); // schema 变更:整表重写
964
1086
  return this;
965
1087
  }
966
1088
 
@@ -1009,6 +1131,7 @@ class Table {
1009
1131
  this._refreshSchemaCache();
1010
1132
  this._dirty = true;
1011
1133
  this._db._markDirty(this._name);
1134
+ this._markAllRowsDirty(); // schema 变更:整表重写
1012
1135
  return this;
1013
1136
  }
1014
1137
 
@@ -1034,6 +1157,7 @@ class Table {
1034
1157
  this._refreshSchemaCache();
1035
1158
  this._dirty = true;
1036
1159
  this._db._markDirty(this._name);
1160
+ this._markAllRowsDirty(); // schema 变更:整表重写
1037
1161
  return this;
1038
1162
  }
1039
1163
 
@@ -1943,6 +2067,57 @@ class Table {
1943
2067
  }
1944
2068
  }
1945
2069
 
2070
+ // ---- 行级脏标记(hybrid/disk 目录模式) ----
2071
+
2072
+ /** 记录一行待刷盘。oldPk 用于主键变更时删除旧索引项。 */
2073
+ _markRowDirty(row, oldPk) {
2074
+ const db = this._db;
2075
+ if (!db || !db._dirMode) return;
2076
+ if (!this._primaryKey) { this._dirtyAll = true; return; }
2077
+ const pk = row[this._primaryKey];
2078
+ if (pk === undefined || pk === null) { this._dirtyAll = true; return; }
2079
+ if (oldPk !== undefined && oldPk !== pk) this._dirtyDeletes.add(oldPk);
2080
+ this._dirtyUpserts.add(row);
2081
+ }
2082
+
2083
+ _markRowDeleted(pkValue) {
2084
+ const db = this._db;
2085
+ if (!db || !db._dirMode) return;
2086
+ if (!this._primaryKey || pkValue === undefined || pkValue === null) {
2087
+ this._dirtyAll = true;
2088
+ return;
2089
+ }
2090
+ this._dirtyDeletes.add(pkValue);
2091
+ for (const r of this._dirtyUpserts) {
2092
+ if (r[this._primaryKey] === pkValue) this._dirtyUpserts.delete(r);
2093
+ }
2094
+ }
2095
+
2096
+ /** 整表脏(无主键表、truncate、回滚/恢复快照等),下次刷盘走全量重写。 */
2097
+ _markAllRowsDirty() {
2098
+ const db = this._db;
2099
+ if (!db || !db._dirMode) return;
2100
+ this._dirtyAll = true;
2101
+ this._dirtyUpserts.clear();
2102
+ this._dirtyDeletes.clear();
2103
+ }
2104
+
2105
+ _peekDirtyRows() {
2106
+ const all = this._dirtyAll || !this._primaryKey
2107
+ || this._dirtyUpserts.size > this._rows.length; // 批量改写过多时全量更划算
2108
+ return {
2109
+ all,
2110
+ upserts: all ? [] : [...this._dirtyUpserts],
2111
+ deletes: all ? [] : [...this._dirtyDeletes]
2112
+ };
2113
+ }
2114
+
2115
+ _clearDirtyRows() {
2116
+ this._dirtyAll = false;
2117
+ this._dirtyUpserts.clear();
2118
+ this._dirtyDeletes.clear();
2119
+ }
2120
+
1946
2121
  _loadRows(rows) {
1947
2122
  this._rows = rows;
1948
2123
  if (this._autoIncrementField) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.7.3",
3
+ "version": "6.7.6",
4
4
  "description": "JSQL-NEO — Rust-powered embedded database with WASM, REST API, B-Tree indexes, WAL, crash recovery",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -152,7 +152,8 @@ console.warn = () => {};
152
152
  ok('LENGTH 是字节数(é = 2 字节)', (await one("SELECT LENGTH('héllo')")) === 6);
153
153
  ok('LENGTH 是字节数(emoji 4 字节 ×2)', (await one("SELECT LENGTH('🚀🌟')")) === 8);
154
154
  ok('CHAR_LENGTH 是字符数', (await one("SELECT CHAR_LENGTH('héllo')")) === 5);
155
- ok('CHARACTER_LENGTH 是字符数', (await one("SELECT CHARACTER_LENGTH('🚀🌟')")) === 4);
155
+ // Issue #111:字符数按 Unicode code point 计(🚀🌟 是 2 个字符,不是 4 个 UTF-16 code unit)
156
+ ok('CHARACTER_LENGTH 是字符数', (await one("SELECT CHARACTER_LENGTH('🚀🌟')")) === 2);
156
157
  ok('OCTET_LENGTH 已实现(= LENGTH)', (await one("SELECT OCTET_LENGTH('中文')")) === 6);
157
158
  ok('LENGTH(NULL) = NULL', (await one('SELECT LENGTH(NULL)')) === null);
158
159
  ok('OCTET_LENGTH(NULL) = NULL', (await one('SELECT OCTET_LENGTH(NULL)')) === null);
@@ -167,10 +167,11 @@ test('Unicode é:LENGTH 为字节数(6),CHAR_LENGTH 为字符数(5)'
167
167
  assert.strictEqual(await one(q, "SELECT UPPER('café')"), 'CAFÉ');
168
168
  });
169
169
 
170
- test('Emoji 按 UTF-8 字节计数(LENGTH=8, CHAR_LENGTH=4)', async () => {
170
+ test('Emoji 按 UTF-8 字节计数(LENGTH=8, CHAR_LENGTH=2)', async () => {
171
171
  const { q } = makeDb();
172
172
  assert.strictEqual(await one(q, "SELECT LENGTH('🚀🌟')"), 8);
173
- assert.strictEqual(await one(q, "SELECT CHAR_LENGTH('🚀🌟')"), 4);
173
+ // Issue #111:CHAR_LENGTH 按 code point 计,两个 emoji = 2 个字符
174
+ assert.strictEqual(await one(q, "SELECT CHAR_LENGTH('🚀🌟')"), 2);
174
175
  });
175
176
 
176
177
  test('Emoji UPPER 无变化', async () => {
@@ -0,0 +1,191 @@
1
+ /*
2
+ * hybrid/disk 模式行级刷盘回归测试
3
+ *
4
+ * 背景:此前 hybrid 的刷盘单位是「整表」——任何一行变更都会把整张表
5
+ * 重写一遍(write amplification),内存里也整表常驻。
6
+ *
7
+ * 现在:Table 按行记录脏标记(_dirtyUpserts/_dirtyDeletes),
8
+ * Database._flushTableDelta() 只把变更行追加到表文件并更新主键索引,
9
+ * 无主键表 / truncate / schema 变更 / 回滚仍走整表重写。
10
+ */
11
+ const fs = require('fs');
12
+ const os = require('os');
13
+ const path = require('path');
14
+ const Database = require('../lib/database.js');
15
+
16
+ let pass = 0, fail = 0;
17
+ function ok(name, cond, extra) {
18
+ if (cond) { pass++; console.log('[OK] ' + name); }
19
+ else { fail++; console.log('[FAIL] ' + name + (extra !== undefined ? ' → ' + JSON.stringify(extra) : '')); }
20
+ }
21
+
22
+ function tmpDir(tag) {
23
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-rowflush-' + tag + '-'));
24
+ }
25
+
26
+ const SCHEMA = {
27
+ id: { type: 'integer', primaryKey: true },
28
+ v: { type: 'string' },
29
+ n: { type: 'integer' }
30
+ };
31
+
32
+ (async () => {
33
+ console.log('--- 1. 单行更新只追加该行,不整表重写 ---');
34
+ {
35
+ const dir = tmpDir('delta');
36
+ let db = new Database(dir, { mode: 'hybrid' });
37
+ await db.createTable('t', SCHEMA);
38
+ await db.insertMany('t', Array.from({ length: 300 }, (_, i) => ({ id: i + 1, v: 'v' + i, n: i })));
39
+ await db.flush();
40
+
41
+ const file = path.join(dir, 't.jsql');
42
+ const before = fs.statSync(file).size;
43
+ await db.updateById('t', 42, { n: 9999 });
44
+ await db.flush();
45
+ const after = fs.statSync(file).size;
46
+ db.close();
47
+
48
+ ok('增量写入远小于整表大小', after - before > 0 && after - before < before,
49
+ { before, after });
50
+
51
+ db = new Database(dir, { mode: 'hybrid' });
52
+ const row = await db.findById('t', 42);
53
+ ok('重开后更新已持久化', row && row.n === 9999, row);
54
+ ok('行数不变', (await db.count('t')) === 300);
55
+ db.close();
56
+ }
57
+
58
+ console.log('--- 2. 删除一行:重开不复活、不重复 ---');
59
+ {
60
+ const dir = tmpDir('delete');
61
+ let db = new Database(dir, { mode: 'hybrid' });
62
+ await db.createTable('t', SCHEMA);
63
+ await db.insertMany('t', [{ id: 1, v: 'a', n: 1 }, { id: 2, v: 'b', n: 2 }, { id: 3, v: 'c', n: 3 }]);
64
+ await db.flush();
65
+ await db.removeById('t', 2);
66
+ await db.flush();
67
+ db.close();
68
+
69
+ db = new Database(dir, { mode: 'hybrid' });
70
+ const rows = await db.find('t', {});
71
+ const ids = rows.map(r => r.id).sort();
72
+ ok('删除的行不复活', (await db.findById('t', 2)) === null);
73
+ ok('剩余行正确且无重复', JSON.stringify(ids) === JSON.stringify([1, 3]), ids);
74
+ db.close();
75
+ }
76
+
77
+ console.log('--- 3. 主键更新后旧主键不残留 ---');
78
+ {
79
+ const dir = tmpDir('pkchange');
80
+ let db = new Database(dir, { mode: 'hybrid' });
81
+ await db.createTable('t', SCHEMA);
82
+ await db.insertMany('t', [{ id: 1, v: 'a', n: 1 }, { id: 2, v: 'b', n: 2 }]);
83
+ await db.flush();
84
+ await db.updateById('t', 1, { id: 10 });
85
+ await db.flush();
86
+ db.close();
87
+
88
+ db = new Database(dir, { mode: 'hybrid' });
89
+ const oldRow = await db.findById('t', 1);
90
+ const newRow = await db.findById('t', 10);
91
+ ok('旧主键已不可见', oldRow === null, oldRow);
92
+ ok('新主键可查到', newRow && newRow.v === 'a', newRow);
93
+ ok('总行数仍为 2', (await db.count('t')) === 2);
94
+ db.close();
95
+ }
96
+
97
+ console.log('--- 4. 无主键表回退整表重写,语义不变 ---');
98
+ {
99
+ const dir = tmpDir('nopk');
100
+ let db = new Database(dir, { mode: 'hybrid' });
101
+ await db.createTable('log', { v: { type: 'string' } });
102
+ await db.insert('log', { v: 'a' });
103
+ await db.insert('log', { v: 'b' });
104
+ await db.flush();
105
+ await db.removeWhere('log', { v: 'a' });
106
+ await db.flush();
107
+ db.close();
108
+
109
+ db = new Database(dir, { mode: 'hybrid' });
110
+ const rows = await db.find('log', {});
111
+ ok('无主键表删除已持久化', rows.length === 1 && rows[0].v === 'b', rows);
112
+ db.close();
113
+ }
114
+
115
+ console.log('--- 5. 反复更新触发压缩后数据仍正确 ---');
116
+ {
117
+ const dir = tmpDir('compact');
118
+ let db = new Database(dir, { mode: 'hybrid' });
119
+ await db.createTable('t', SCHEMA);
120
+ await db.insertMany('t', [{ id: 1, n: 0 }, { id: 2, n: 0 }]);
121
+ await db.flush();
122
+ const file = path.join(dir, 't.jsql');
123
+ const baseSize = fs.statSync(file).size;
124
+ for (let i = 1; i <= 200; i++) {
125
+ await db.updateById('t', 1, { n: i });
126
+ await db.flush();
127
+ }
128
+ const grownSize = fs.statSync(file).size;
129
+ db.close();
130
+
131
+ db = new Database(dir, { mode: 'hybrid' });
132
+ const row = await db.findById('t', 1);
133
+ ok('压缩后最新值正确', row && row.n === 200, row);
134
+ ok('压缩后行数正确', (await db.count('t')) === 2);
135
+ ok('文件未无限膨胀', grownSize < baseSize * 60, { baseSize, grownSize });
136
+ db.close();
137
+ }
138
+
139
+ console.log('--- 6. 删除后重新插入同主键 ---');
140
+ {
141
+ const dir = tmpDir('reinsert');
142
+ let db = new Database(dir, { mode: 'hybrid' });
143
+ await db.createTable('t', SCHEMA);
144
+ await db.insert('t', { id: 1, v: 'old', n: 1 });
145
+ await db.flush();
146
+ await db.removeById('t', 1);
147
+ await db.flush();
148
+ await db.insert('t', { id: 1, v: 'new', n: 2 });
149
+ await db.flush();
150
+ db.close();
151
+
152
+ db = new Database(dir, { mode: 'hybrid' });
153
+ const row = await db.findById('t', 1);
154
+ ok('重新插入的行是唯一一行', row && row.v === 'new' && (await db.count('t')) === 1, row);
155
+ db.close();
156
+ }
157
+
158
+ console.log('--- 7. 重开后按行懒加载 + 逐行淘汰 ---');
159
+ {
160
+ const dir = tmpDir('lazy');
161
+ let db = new Database(dir, { mode: 'hybrid' });
162
+ await db.createTable('t', SCHEMA);
163
+ // 400 行超过单个索引块的容量(335 项),同时覆盖索引分块读取
164
+ await db.insertMany('t', Array.from({ length: 400 }, (_, i) => ({ id: i + 1, v: 'v' + i, n: i })));
165
+ await db.flush();
166
+ db.close();
167
+
168
+ db = new Database(dir, { mode: 'hybrid' });
169
+ const table = db._ensureTable('t');
170
+ ok('重开后行数完整(索引跨块)', table._rows.length === 400 && (await db.count('t')) === 400,
171
+ table._rows.length);
172
+ ok('打开时不把整表读入内存', table._rowCache.size() === 0, table._rowCache.size());
173
+
174
+ const row = await db.findById('t', 200);
175
+ ok('按主键只加载命中的一行', row && row.n === 199 && table._rowCache.size() === 1,
176
+ { row, cached: table._rowCache.size() });
177
+
178
+ await db.updateById('t', 200, { n: 8888 });
179
+ await db.flush();
180
+ table._evictRows(Infinity);
181
+ ok('淘汰后按需重读仍是新值',
182
+ (await db.findById('t', 200)).n === 8888 && table._rowCache.size() === 1);
183
+
184
+ table._evictRows(Infinity);
185
+ ok('淘汰后行数不变', (await db.count('t')) === 400 && table._rowCache.size() === 0);
186
+ db.close();
187
+ }
188
+
189
+ console.log(`\n${pass} passed, ${fail} failed`);
190
+ if (fail > 0) process.exit(1);
191
+ })();
@@ -0,0 +1,112 @@
1
+ /* ---- Issue #111:字符串函数必须按 Unicode code point 语义 ---- */
2
+ /*
3
+ * JS 的 String#length / slice / substr / split('') / indexOf 都是 UTF-16 code unit
4
+ * 语义,会把增补平面字符(emoji 🚀 U+1F680、生僻汉字 𡋾 U+212FE)劈成孤立代理项。
5
+ * MySQL 按字符(code point)计数/定位/截取。这里钉死相关函数的正确行为,
6
+ * 并确认 LENGTH() 仍按 UTF-8 字节计(4 字节,不能被顺手改坏)。
7
+ *
8
+ * node test/issue-111.test.js
9
+ */
10
+ const path = require('path');
11
+ const ROOT = path.join(__dirname, '..');
12
+ const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
13
+
14
+ let pass = 0, fail = 0;
15
+ function ok(name, cond, got) {
16
+ if (cond) { pass++; console.log('[OK] ' + name); }
17
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
18
+ }
19
+ // 是否包含孤立(未配对)代理项
20
+ function hasLoneSurrogate(s) {
21
+ if (typeof s !== 'string') return false;
22
+ for (let i = 0; i < s.length; i++) {
23
+ const c = s.charCodeAt(i);
24
+ if (c >= 0xD800 && c <= 0xDBFF) {
25
+ const n = s.charCodeAt(i + 1);
26
+ if (!(n >= 0xDC00 && n <= 0xDFFF)) return true;
27
+ i++;
28
+ } else if (c >= 0xDC00 && c <= 0xDFFF) {
29
+ return true;
30
+ }
31
+ }
32
+ return false;
33
+ }
34
+
35
+ (async () => {
36
+ const db = new Database(':memory:', { autoSave: false });
37
+ const q = async (sql) => {
38
+ const r = await executeSQL(db, sql, { safety: false });
39
+ return r.rows[0][0];
40
+ };
41
+
42
+ // ---------- CHAR_LENGTH / CHARACTER_LENGTH ----------
43
+ ok("CHAR_LENGTH('🚀') = 1", await q("SELECT CHAR_LENGTH('🚀')") === 1, await q("SELECT CHAR_LENGTH('🚀')"));
44
+ ok("CHAR_LENGTH('a🚀b') = 3", await q("SELECT CHAR_LENGTH('a🚀b')") === 3, await q("SELECT CHAR_LENGTH('a🚀b')"));
45
+ ok("CHARACTER_LENGTH('a🚀b') = 3",
46
+ await q("SELECT CHARACTER_LENGTH('a🚀b')") === 3, await q("SELECT CHARACTER_LENGTH('a🚀b')"));
47
+ ok("CHAR_LENGTH('𡋾') = 1", await q("SELECT CHAR_LENGTH('𡋾')") === 1, await q("SELECT CHAR_LENGTH('𡋾')"));
48
+
49
+ // ---------- LENGTH 保持字节语义 ----------
50
+ ok("LENGTH('🚀') = 4(字节,不应改变)", await q("SELECT LENGTH('🚀')") === 4, await q("SELECT LENGTH('🚀')"));
51
+ ok("LENGTH('a🚀b') = 6", await q("SELECT LENGTH('a🚀b')") === 6, await q("SELECT LENGTH('a🚀b')"));
52
+
53
+ // ---------- LEFT / RIGHT ----------
54
+ const left1 = await q("SELECT LEFT('🚀ab',1)");
55
+ ok("LEFT('🚀ab',1) = '🚀'", left1 === '🚀', left1);
56
+ ok("LEFT('🚀ab',1) 无孤立代理项", !hasLoneSurrogate(left1), left1);
57
+
58
+ const right1 = await q("SELECT RIGHT('ab🚀',1)");
59
+ ok("RIGHT('ab🚀',1) = '🚀'", right1 === '🚀', right1);
60
+ ok("RIGHT('ab🚀',1) 无孤立代理项", !hasLoneSurrogate(right1), right1);
61
+
62
+ ok("LEFT('𡋾xy',1) = '𡋾'", await q("SELECT LEFT('𡋾xy',1)") === '𡋾', await q("SELECT LEFT('𡋾xy',1)"));
63
+ ok("RIGHT('xy𡋾',1) = '𡋾'", await q("SELECT RIGHT('xy𡋾',1)") === '𡋾', await q("SELECT RIGHT('xy𡋾',1)"));
64
+ ok("LEFT('abcdef',3) = 'abc'(ASCII 不受影响)", await q("SELECT LEFT('abcdef',3)") === 'abc', null);
65
+ ok("RIGHT('abcdef',3) = 'def'", await q("SELECT RIGHT('abcdef',3)") === 'def', null);
66
+
67
+ // ---------- SUBSTRING / SUBSTR ----------
68
+ const sub1 = await q("SELECT SUBSTRING('🚀ab',1,1)");
69
+ ok("SUBSTRING('🚀ab',1,1) = '🚀'", sub1 === '🚀', sub1);
70
+ ok("SUBSTRING 结果无孤立代理项", !hasLoneSurrogate(sub1), sub1);
71
+ ok("SUBSTR('a🚀b',2,1) = '🚀'", await q("SELECT SUBSTR('a🚀b',2,1)") === '🚀', await q("SELECT SUBSTR('a🚀b',2,1)"));
72
+ ok("SUBSTRING('a🚀b',2) = '🚀b'", await q("SELECT SUBSTRING('a🚀b',2)") === '🚀b', await q("SELECT SUBSTRING('a🚀b',2)"));
73
+ ok("SUBSTRING('abcdef',2,3) = 'bcd'", await q("SELECT SUBSTRING('abcdef',2,3)") === 'bcd', null);
74
+ ok("SUBSTRING('abcdef',-2) = 'ef'", await q("SELECT SUBSTRING('abcdef',-2)") === 'ef', null);
75
+
76
+ // ---------- REVERSE ----------
77
+ const rev = await q("SELECT REVERSE('a🚀b')");
78
+ ok("REVERSE('a🚀b') = 'b🚀a'", rev === 'b🚀a', rev);
79
+ ok("REVERSE 结果无孤立代理项", !hasLoneSurrogate(rev), rev);
80
+ ok("REVERSE('a𡋾b') = 'b𡋾a'", await q("SELECT REVERSE('a𡋾b')") === 'b𡋾a', await q("SELECT REVERSE('a𡋾b')"));
81
+
82
+ // ---------- LOCATE / INSTR ----------
83
+ ok("LOCATE('b','🚀ab') = 3", await q("SELECT LOCATE('b','🚀ab')") === 3, await q("SELECT LOCATE('b','🚀ab')"));
84
+ ok("INSTR('🚀ab','b') = 3", await q("SELECT INSTR('🚀ab','b')") === 3, await q("SELECT INSTR('🚀ab','b')"));
85
+ ok("LOCATE('🚀','a🚀b') = 2", await q("SELECT LOCATE('🚀','a🚀b')") === 2, await q("SELECT LOCATE('🚀','a🚀b')"));
86
+ ok("LOCATE('b','𡋾ab') = 3", await q("SELECT LOCATE('b','𡋾ab')") === 3, await q("SELECT LOCATE('b','𡋾ab')"));
87
+ ok("LOCATE 未命中返回 0", await q("SELECT LOCATE('z','abc')") === 0, await q("SELECT LOCATE('z','abc')"));
88
+ ok("INSTR('abc','') = 1", await q("SELECT INSTR('abc','')") === 1, null);
89
+
90
+ // ---------- LPAD / RPAD ----------
91
+ const lp = await q("SELECT LPAD('🚀',3,'x')");
92
+ ok("LPAD('🚀',3,'x') = 'xx🚀'", lp === 'xx🚀', lp);
93
+ ok("LPAD 结果无孤立代理项", !hasLoneSurrogate(lp), lp);
94
+ ok("RPAD('🚀',3,'x') = '🚀xx'", await q("SELECT RPAD('🚀',3,'x')") === '🚀xx', await q("SELECT RPAD('🚀',3,'x')"));
95
+ // 截断路径也按字符
96
+ ok("LPAD('🚀abc',2,'x') = '🚀a'", await q("SELECT LPAD('🚀abc',2,'x')") === '🚀a', await q("SELECT LPAD('🚀abc',2,'x')"));
97
+ ok("RPAD('🚀abc',2,'x') = '🚀a'", await q("SELECT RPAD('🚀abc',2,'x')") === '🚀a', await q("SELECT RPAD('🚀abc',2,'x')"));
98
+ // ASCII 行为不变
99
+ ok("LPAD('hi',5,'ab') = 'abahi'", await q("SELECT LPAD('hi',5,'ab')") === 'abahi', null);
100
+ ok("RPAD('hi',5,'ab') = 'hiaba'", await q("SELECT RPAD('hi',5,'ab')") === 'hiaba', null);
101
+
102
+ // ---------- 多字节但 BMP 内(不涉及代理对)行为不变 ----------
103
+ ok("CHAR_LENGTH('héllo') = 5", await q("SELECT CHAR_LENGTH('héllo')") === 5, await q("SELECT CHAR_LENGTH('héllo')"));
104
+ ok("LENGTH('héllo') = 6", await q("SELECT LENGTH('héllo')") === 6, await q("SELECT LENGTH('héllo')"));
105
+ ok("REVERSE('héllo') = 'olléh'", await q("SELECT REVERSE('héllo')") === 'olléh', await q("SELECT REVERSE('héllo')"));
106
+
107
+ console.log(`\n${pass} passed, ${fail} failed`);
108
+ process.exit(fail === 0 ? 0 : 1);
109
+ })().catch(e => {
110
+ console.log('[FAIL] unexpected exception: ' + e.stack.split('\n').slice(0, 3).join('\n'));
111
+ process.exit(1);
112
+ });