jsql-neo 6.7.3 → 6.7.5

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.3** — 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.5** — 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)
@@ -169,6 +169,17 @@ await db.start();
169
169
  | Disk | `new Database('./data/app')` | Production persistence |
170
170
  | Hybrid | `new Database('./data', { autoSave: true, saveInterval: 3000 })` | Performance + durability |
171
171
 
172
+ File mode (`new Database('./data/db.json')`) is **not** an in-memory store that only
173
+ writes on exit. Every `insert` / `insertMany` / `update` / `updateById` / `remove` /
174
+ `removeById` / `softDelete` / `truncate` appends one JSONL record to `<file>.wal` and
175
+ `fsync`s it before returning, so a `kill -9` loses nothing that already committed.
176
+ `save()` / `close()` / `stop()` only checkpoint (write a full snapshot, then truncate
177
+ the WAL); they are no longer the moment data first reaches disk.
178
+ WAL is on by default for file mode — pass `wal: false` for the old semantics, or tune
179
+ auto-checkpointing with `walCheckpointOps` (default 1000, `0` disables). Directory
180
+ (`mode: 'disk' | 'hybrid'`) and encrypted (`encryptKey`) databases keep it off unless
181
+ you opt in with `wal: true`, because the WAL is plaintext.
182
+
172
183
  ---
173
184
 
174
185
  ## Query results
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.7.3 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.7.5 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
package/lib/database.js CHANGED
@@ -103,7 +103,9 @@ class Database {
103
103
  * @param {boolean} options.pretty - JSON 是否格式化(默认 true,仅旧文件模式)
104
104
  * @param {string} options.encryptKey - 加密密钥(16/24/32 字节),启用 AES-256-CBC
105
105
  * @param {boolean} options.versioning - 是否启用版本历史(默认 false)
106
- * @param {boolean} options.wal - 是否启用 WAL 模式(默认 false,内存模式自动禁用)
106
+ * @param {boolean} options.wal - 是否启用 WAL(默认 true:文件模式每次写入立即 append+fsync;
107
+ * 内存模式自动禁用;传 false 关闭;目录 hybrid/disk 模式与加密库默认关闭)
108
+ * @param {number} options.walCheckpointOps - WAL 累积多少条后自动做一次快照检查点(默认 1000,0 禁用)
107
109
  * @param {string} options.isolationLevel - 事务隔离级别 'READ_COMMITTED' | 'REPEATABLE_READ'(默认 'READ_COMMITTED')
108
110
  * @param {number} options.slowQueryThreshold - 慢查询阈值 ms(默认 100,0 记录全部,<0 禁用)
109
111
  * @param {boolean} options.fileLock - 是否启用文件锁(默认 false)
@@ -157,13 +159,20 @@ class Database {
157
159
  this._attached = {}; // 附加数据库 { name: db }
158
160
  this._changeStream = null; // 变更流
159
161
 
160
- // WAL(Write-Ahead Logging)
161
- this._walEnabled = options.wal === true && !this._memoryMode;
162
+ // WAL(Write-Ahead Logging):文件模式下默认开启,每次写入立即追加并 fsync,
163
+ // 不再依赖「内存中改完、退出时 save()」的旧语义。
164
+ if (this._memoryMode) this._walEnabled = false;
165
+ else if (this._dirMode) this._walEnabled = options.wal === true;
166
+ else if (this._encryptKey) this._walEnabled = options.wal === true; // WAL 为明文,加密库需显式开启
167
+ else this._walEnabled = options.wal !== false;
162
168
  this._walPath = this._filePath ? this._filePath + '.wal' : null;
163
169
  this._walOps = []; // WAL 操作日志(内存镜像)
164
170
  this._walFlushedCount = 0; // 已落盘记录数(append-only 增量追加用)
165
171
  this._walReplaying = false; // 回放中:抑制再次写日志
166
172
  this._walReplaySummary = null;
173
+ this._walOpCount = 0; // 自上次检查点以来的操作数
174
+ this._walCheckpointOps = options.walCheckpointOps !== undefined ? options.walCheckpointOps : 1000;
175
+ this._walCheckpointScheduled = false;
167
176
 
168
177
  // 事务隔离:默认 REPEATABLE_READ(begin 时保存行快照,rollback 可回滚)
169
178
  this._isolationLevel = options.isolationLevel || 'REPEATABLE_READ';
@@ -441,23 +450,89 @@ class Database {
441
450
  * append-only 下崩溃最多丢失最后一行(已 fsync 过的行不会丢)。
442
451
  */
443
452
  _walWrite(op) {
444
- if (!this._walEnabled) return;
453
+ if (!this._walEnabled || this._loading) return;
445
454
  const entry = {
446
455
  ...op,
447
456
  timestamp: Date.now(),
448
457
  sequence: this._walOps.length + 1
449
458
  };
450
459
  this._walOps.push(entry);
460
+ this._walOpCount++;
451
461
  // 恢复过程中重放操作不能再次写 WAL,否则会无限增长
452
462
  if (this._walReplaying) return;
453
463
  this._flushWAL();
464
+ this._maybeCheckpointWAL();
465
+ }
466
+
467
+ /**
468
+ * 记录「写入后的行」:有主键时按主键幂等 upsert,无主键时退化为整表镜像。
469
+ * 这样任何写入都立刻落到 WAL,崩溃后按序回放即可恢复。
470
+ */
471
+ _walLogUpsert(tableName, rows) {
472
+ if (!this._walEnabled || this._walReplaying || this._loading) return;
473
+ const t = this._tables[tableName];
474
+ if (!t || !Array.isArray(rows) || rows.length === 0) return;
475
+ if (t._primaryKey) {
476
+ const pk = t._primaryKey;
477
+ const out = rows.filter(r => r && r[pk] !== undefined && r[pk] !== null).map(r => ({ ...r }));
478
+ if (out.length === 0) return;
479
+ this._walWrite({ op: 'upsertRows', table: tableName, pk, rows: out });
480
+ } else {
481
+ this._walLogReplaceTable(tableName);
482
+ }
483
+ }
484
+
485
+ /** 记录删除:有主键时只记主键列表,无主键时记录整表镜像。 */
486
+ _walLogRemove(tableName, removedRows) {
487
+ if (!this._walEnabled || this._walReplaying || this._loading) return;
488
+ const t = this._tables[tableName];
489
+ if (!t) return;
490
+ if (t._primaryKey && Array.isArray(removedRows) && removedRows.length) {
491
+ const pk = t._primaryKey;
492
+ const ids = removedRows.map(r => r && r[pk]).filter(v => v !== undefined && v !== null);
493
+ if (ids.length) {
494
+ this._walWrite({ op: 'removeRows', table: tableName, pk, ids });
495
+ return;
496
+ }
497
+ }
498
+ this._walLogReplaceTable(tableName);
499
+ }
500
+
501
+ /** 无主键表 / truncate / 结构变化:写入该表的完整行镜像。 */
502
+ _walLogReplaceTable(tableName) {
503
+ if (!this._walEnabled || this._walReplaying || this._loading) return;
504
+ const t = this._tables[tableName];
505
+ if (!t) return;
506
+ this._walWrite({ op: 'replaceTable', table: tableName, rows: t._rows.map(r => ({ ...r })) });
507
+ }
508
+
509
+ /**
510
+ * WAL 增长到阈值后自动做一次快照检查点,避免日志无限膨胀。
511
+ * 事务进行中不检查点,否则未提交的数据会进入快照。
512
+ */
513
+ _maybeCheckpointWAL() {
514
+ if (!this._walEnabled || this._walCheckpointScheduled) return;
515
+ if (this._walCheckpointOps <= 0 || this._walOpCount < this._walCheckpointOps) return;
516
+ if (this._loading || this._walReplaying || this._transaction) return;
517
+ this._walCheckpointScheduled = true;
518
+ const run = () => {
519
+ this._walCheckpointScheduled = false;
520
+ if (this._loading || this._walReplaying || this._transaction) return;
521
+ try {
522
+ this.save();
523
+ } catch (e) {
524
+ // 快照失败时保留 WAL,数据仍可恢复
525
+ }
526
+ };
527
+ if (typeof setImmediate === 'function') setImmediate(run);
528
+ else setTimeout(run, 0);
454
529
  }
455
530
 
456
531
  /**
457
532
  * 将新增的 WAL 记录追加到磁盘(append-only)
458
533
  */
459
534
  _flushWAL() {
460
- if (!this._walEnabled || this._walOps.length === 0) return;
535
+ if (!this._walEnabled || !this._walPath || this._walOps.length === 0) return;
461
536
  try {
462
537
  const dir = path.dirname(this._walPath);
463
538
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
@@ -489,6 +564,7 @@ class Database {
489
564
  if (!this._walEnabled) return;
490
565
  this._walOps = [];
491
566
  this._walFlushedCount = 0;
567
+ this._walOpCount = 0;
492
568
  try {
493
569
  if (this._walPath && fs.existsSync(this._walPath)) {
494
570
  fs.unlinkSync(this._walPath);
@@ -567,7 +643,45 @@ class Database {
567
643
  case 'insert': {
568
644
  const t = op.table && this._tables[op.table];
569
645
  if (!t || !Array.isArray(op.rows) || op.rows.length === 0) { failed++; break; }
570
- for (const __e of op.rows) t._rows.push(__e);
646
+ const pk = t._primaryKey;
647
+ for (const __e of op.rows) {
648
+ // 幂等:快照已包含该行时覆盖而不是重复插入
649
+ if (pk && __e && __e[pk] !== undefined) {
650
+ const ai = t._rows.findIndex(r => r && r[pk] === __e[pk]);
651
+ if (ai >= 0) { t._rows[ai] = __e; continue; }
652
+ }
653
+ t._rows.push(__e);
654
+ }
655
+ touched.add(t);
656
+ replayed++;
657
+ break;
658
+ }
659
+ case 'upsertRows': {
660
+ const t = op.table && this._tables[op.table];
661
+ if (!t || !op.pk || !Array.isArray(op.rows)) { failed++; break; }
662
+ for (const __r of op.rows) {
663
+ if (!__r || typeof __r !== 'object') continue;
664
+ const ai = t._rows.findIndex(r => r && String(r[op.pk]) === String(__r[op.pk]));
665
+ if (ai >= 0) t._rows[ai] = { ...__r };
666
+ else t._rows.push({ ...__r });
667
+ }
668
+ touched.add(t);
669
+ replayed++;
670
+ break;
671
+ }
672
+ case 'removeRows': {
673
+ const t = op.table && this._tables[op.table];
674
+ if (!t || !op.pk || !Array.isArray(op.ids)) { failed++; break; }
675
+ const gone = new Set(op.ids.map(String));
676
+ t._rows = t._rows.filter(r => !r || !gone.has(String(r[op.pk])));
677
+ touched.add(t);
678
+ replayed++;
679
+ break;
680
+ }
681
+ case 'replaceTable': {
682
+ const t = op.table && this._tables[op.table];
683
+ if (!t || !Array.isArray(op.rows)) { failed++; break; }
684
+ t._rows = op.rows.map(r => ({ ...r }));
571
685
  touched.add(t);
572
686
  replayed++;
573
687
  break;
@@ -679,6 +793,9 @@ class Database {
679
793
  case 'insert':
680
794
  case 'update':
681
795
  case 'remove':
796
+ case 'upsertRows':
797
+ case 'removeRows':
798
+ case 'replaceTable':
682
799
  // 数据类操作由 _recoverFromWAL 按序直接处理(需维护表内行序),
683
800
  // 不走这里。
684
801
  return false;
@@ -688,6 +805,8 @@ class Database {
688
805
  case 'begin':
689
806
  case 'commit':
690
807
  case 'rollback':
808
+ case 'rollbackTo':
809
+ case 'savepoint':
691
810
  case 'undo':
692
811
  case 'restore':
693
812
  case 'import':
@@ -1375,6 +1494,11 @@ class Database {
1375
1494
 
1376
1495
  if (this._transaction.snapshot) {
1377
1496
  this._restoreTxSnapshot(this._transaction.snapshot);
1497
+ // 回滚后的状态必须重新写入 WAL:否则 WAL 里已记录的写入
1498
+ // 会在崩溃重放时被重新应用,回滚等于没做。
1499
+ for (const name of Object.keys(this._transaction.snapshot)) {
1500
+ if (this._tables[name]) this._walLogReplaceTable(name);
1501
+ }
1378
1502
  } else {
1379
1503
  // READ_COMMITTED:没有行快照,只能退回自增值
1380
1504
  for (const [name, table] of Object.entries(this._tables)) {
@@ -1429,6 +1553,9 @@ class Database {
1429
1553
  const list = this._requireSavepoints(name, 'ROLLBACK TO SAVEPOINT');
1430
1554
  const idx = this._findSavepoint(list, name);
1431
1555
  this._restoreTxSnapshot(list[idx].snap);
1556
+ for (const tableName of Object.keys(list[idx].snap)) {
1557
+ if (this._tables[tableName]) this._walLogReplaceTable(tableName);
1558
+ }
1432
1559
  list.length = idx + 1;
1433
1560
  this._walWrite({ op: 'rollbackTo', name });
1434
1561
  this._markDirtyLegacy();
@@ -1806,17 +1933,11 @@ class Database {
1806
1933
  if (!(await this._runHooks('beforeInsert', [tableName, arr]))) return [];
1807
1934
  const pk = this._pkOf(table);
1808
1935
  const ids = [];
1809
- const logged = [];
1810
1936
  for (const row of arr) {
1811
1937
  const r = table.insert(row);
1812
- const id = pk ? r[pk] : table._rows.length;
1813
- ids.push(id);
1814
- // 记录落库后的完整行(含自增主键),保证回放能还原真实数据
1815
- if (pk) logged.push({ ...r });
1816
- else logged.push(r);
1817
- }
1818
- // 有主键才可幂等回放;无主键表回放会重复插行,故不记录
1819
- if (pk) this._walWrite({ op: 'insert', table: tableName, rows: logged });
1938
+ ids.push(pk ? r[pk] : table._rows.length);
1939
+ }
1940
+ // WAL 已由 Table.insert() 在写入瞬间逐条落盘(含无主键表的整表镜像)
1820
1941
  this._emit('insert', { table: tableName, count: arr.length, ids });
1821
1942
  await this._runHooks('afterInsert', [tableName, arr, ids]);
1822
1943
  this._markDirty(tableName);
@@ -1828,6 +1949,7 @@ class Database {
1828
1949
  if (this._dirMode) {
1829
1950
  this._flushDirty();
1830
1951
  this._saveMeta();
1952
+ this._checkpoint();
1831
1953
  } else if (!this._memoryMode) {
1832
1954
  this.save();
1833
1955
  }
@@ -1996,7 +2118,7 @@ class Database {
1996
2118
  Object.assign(row, validated);
1997
2119
  if (rowIndex !== -1) table._addToIndexes(rowIndex, row);
1998
2120
  }
1999
- if (pk) this._walWrite({ op: 'update', table: tableName, pk, id, row: { ...validated } });
2121
+ this._walLogUpsert(tableName, [row]);
2000
2122
  this._emit('update', { table: tableName, id, data: validated });
2001
2123
  await this._runHooks('afterUpdate', [tableName, id, validated, { ok: true }]);
2002
2124
  this._markDirty(tableName);
@@ -2010,6 +2132,7 @@ class Database {
2010
2132
  if (!(await this._runHooks('beforeUpdate', [tableName, pairs]))) return;
2011
2133
  const pk = this._pkOf(table);
2012
2134
  let count = 0;
2135
+ const changed = [];
2013
2136
  for (const [id, data] of pairs) {
2014
2137
  const row = this._resolveId(table, id);
2015
2138
  if (row) {
@@ -2017,9 +2140,10 @@ class Database {
2017
2140
  if (typeof table._enforceChecks === 'function') table._enforceChecks({ ...row, ...data });
2018
2141
  Object.assign(row, data);
2019
2142
  count++;
2020
- if (pk) this._walWrite({ op: 'update', table: tableName, pk, id, row: { ...data } });
2143
+ changed.push(row);
2021
2144
  }
2022
2145
  }
2146
+ if (changed.length) this._walLogUpsert(tableName, changed);
2023
2147
  this._emit('update', { table: tableName, entries: pairs, result: { ok: true, count } });
2024
2148
  await this._runHooks('afterUpdate', [tableName, pairs, { ok: true, count }]);
2025
2149
  this._markDirty(tableName);
@@ -2033,7 +2157,7 @@ class Database {
2033
2157
  if (table._primaryKey) {
2034
2158
  const removed = table.removeById(id);
2035
2159
  if (removed === 0) return { ok: false, error: 'not found' };
2036
- this._walWrite({ op: 'remove', table: tableName, pk: table._primaryKey, id });
2160
+ // WAL 由 Table.removeById() 记录
2037
2161
  this._emit('delete', { table: tableName, id });
2038
2162
  await this._runHooks('afterDelete', [tableName, id, { ok: true }]);
2039
2163
  this._markDirty(tableName);
@@ -2045,6 +2169,7 @@ class Database {
2045
2169
  table._rebuildPKIndex();
2046
2170
  table._rebuildAllBTrees();
2047
2171
  for (const field of Object.keys(table._indexes)) table.createIndex(field);
2172
+ this._walLogReplaceTable(tableName);
2048
2173
  this._emit('delete', { table: tableName, id });
2049
2174
  await this._runHooks('afterDelete', [tableName, id, { ok: true }]);
2050
2175
  this._markDirty(tableName);
@@ -2087,6 +2212,7 @@ class Database {
2087
2212
  table._rebuildPKIndex();
2088
2213
  table._rebuildAllBTrees();
2089
2214
  for (const field of Object.keys(table._indexes)) table.createIndex(field);
2215
+ if (removed > 0) this._walLogReplaceTable(tableName);
2090
2216
  }
2091
2217
  this._emit('delete', { table: tableName, ids, result: { ok: true, count: removed } });
2092
2218
  await this._runHooks('afterDelete', [tableName, ids, { ok: true, count: removed }]);
@@ -2107,6 +2233,7 @@ class Database {
2107
2233
  table._rebuildPKIndex();
2108
2234
  table._rebuildAllBTrees();
2109
2235
  for (const field of Object.keys(table._indexes)) table.createIndex(field);
2236
+ if (removed > 0) this._walLogRemove(tableName, matched);
2110
2237
  this._emit('delete', { table: tableName, ids: [], result: { ok: true, count: removed } });
2111
2238
  await this._runHooks('afterDelete', [tableName, [filter], { ok: true, count: removed }]);
2112
2239
  this._markDirty(tableName);
@@ -2119,10 +2246,7 @@ class Database {
2119
2246
  const arr = Array.isArray(items) ? items : [items];
2120
2247
  if (!(await this._runHooks('beforeInsert', [tableName, arr]))) return [];
2121
2248
  const inserted = table.insertMany(arr);
2122
- // P1-6: insertMany 不写 WAL——崩溃恢复时丢失这些操作
2123
- if (table._primaryKey && inserted.length > 0) {
2124
- this._walWrite({ op: 'insert', table: tableName, rows: inserted });
2125
- }
2249
+ // WAL 由 Table.insertMany() 记录
2126
2250
  this._emit('insert', { table: tableName, count: arr.length });
2127
2251
  await this._runHooks('afterInsert', [tableName, arr, inserted]);
2128
2252
  this._markDirty(tableName);
@@ -2134,14 +2258,7 @@ class Database {
2134
2258
  if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2135
2259
  if (!(await this._runHooks('beforeUpdate', [tableName, query, updates]))) return 0;
2136
2260
  const count = table.update(query, updates);
2137
- // P1-6: update 不写 WAL——崩溃恢复时丢失这些操作
2138
- if (table._primaryKey && count > 0) {
2139
- const updatedRows = table.find(query);
2140
- for (const row of updatedRows) {
2141
- const id = row[table._primaryKey];
2142
- if (id !== undefined) this._walWrite({ op: 'update', table: tableName, pk: table._primaryKey, id, row: { ...row } });
2143
- }
2144
- }
2261
+ // WAL 由 Table.update() 记录
2145
2262
  this._emit('update', { table: tableName, query, count });
2146
2263
  await this._runHooks('afterUpdate', [tableName, query, updates, count]);
2147
2264
  this._markDirty(tableName);
@@ -2152,14 +2269,7 @@ class Database {
2152
2269
  const table = this._ensureTable(tableName);
2153
2270
  if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2154
2271
  if (!(await this._runHooks('beforeDelete', [tableName, query]))) return 0;
2155
- // P1-6: delete 不写 WAL——崩溃恢复时丢失这些操作
2156
- if (table._primaryKey) {
2157
- const toDelete = table.find(query);
2158
- for (const row of toDelete) {
2159
- const id = row[table._primaryKey];
2160
- if (id !== undefined) this._walWrite({ op: 'remove', table: tableName, pk: table._primaryKey, id });
2161
- }
2162
- }
2272
+ // WAL 由 Table.remove() 记录
2163
2273
  const count = table.remove(query);
2164
2274
  this._emit('delete', { table: tableName, query, count });
2165
2275
  await this._runHooks('afterDelete', [tableName, query, count]);
@@ -2170,14 +2280,7 @@ class Database {
2170
2280
  truncate(tableName) {
2171
2281
  const table = this._ensureTable(tableName);
2172
2282
  if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2173
- // P1-6: truncate 不写 WAL——崩溃恢复时丢失这些操作
2174
- if (table._primaryKey) {
2175
- const toDelete = table.find({});
2176
- for (const row of toDelete) {
2177
- const id = row[table._primaryKey];
2178
- if (id !== undefined) this._walWrite({ op: 'remove', table: tableName, pk: table._primaryKey, id });
2179
- }
2180
- }
2283
+ // WAL 由 Table.truncate() 记录整表镜像
2181
2284
  const count = table.truncate();
2182
2285
  this._emit('delete', { table: tableName, count });
2183
2286
  this._markDirty(tableName);
@@ -2194,7 +2297,11 @@ class Database {
2194
2297
  try {
2195
2298
  this._flushDirty();
2196
2299
  this._saveMeta();
2300
+ this._checkpoint();
2197
2301
  } catch (e) {}
2302
+ } else if (!this._memoryMode) {
2303
+ // 正常关闭时做一次快照检查点,缩短下次启动的回放时间
2304
+ try { this.save(); } catch (e) {}
2198
2305
  }
2199
2306
  if (this._sigInstalled) {
2200
2307
  this._sigInstalled = false;
@@ -2304,6 +2411,7 @@ class Database {
2304
2411
  if (this._dirMode) {
2305
2412
  this._flushDirty();
2306
2413
  this._saveMeta();
2414
+ this._checkpoint();
2307
2415
  return;
2308
2416
  }
2309
2417
 
package/lib/sql.js CHANGED
@@ -490,9 +490,14 @@ function tokenize(sql) {
490
490
 
491
491
  // 聚合函数集合:这些必须走 aggregate 节点,否则会被当成逐行标量函数(返回 null 且不折叠行)
492
492
  const AGG_FUNCS = new Set(['SUM', 'AVG', 'MIN', 'MAX', 'COUNT',
493
- 'GROUP_CONCAT', 'STDDEV', 'STDDEV_POP', 'STDDEV_SAMP',
493
+ 'GROUP_CONCAT', 'STDDEV', 'STD', 'STDDEV_POP', 'STDDEV_SAMP',
494
494
  'VARIANCE', 'VAR_POP', 'VAR_SAMP', 'FIRST', 'LAST']);
495
495
 
496
+ // 方差/标准差族(Issue #114):MySQL 里无后缀的 VARIANCE / STDDEV / STD
497
+ // 都是**总体**口径(= VAR_POP / STDDEV_POP),不是样本。
498
+ const VARIANCE_FUNCS = new Set(['STDDEV', 'STD', 'STDDEV_POP', 'STDDEV_SAMP',
499
+ 'VARIANCE', 'VAR_POP', 'VAR_SAMP']);
500
+
496
501
  // 这些词会跟在表名/子查询之后,不能被误当成表别名。
497
502
  // 新增任何"跟在 FROM 之后"的子句时,都要往这里加词。
498
503
  const NOT_ALIAS_WORDS = ['JOIN', 'LEFT', 'RIGHT', 'FULL', 'WHERE', 'GROUP', 'ORDER', 'LIMIT',
@@ -2574,9 +2579,21 @@ class Parser {
2574
2579
  }
2575
2580
  column = { type: 'tuple', items: cols };
2576
2581
  } else if (this.peek().type === 'op' && this.peek().value === ',') {
2577
- // GROUP_CONCAT(expr, 'sep')
2578
- this.next();
2579
- separator = this.parseValue();
2582
+ if (VARIANCE_FUNCS.has(fn)) {
2583
+ // Issue #114:MySQL 的 VARIANCE/STDDEV/STD 只接受单个表达式,
2584
+ // 但本项目历史上接受 VARIANCE(1,2,3) 这种多参数写法,统一收集成 arglist,
2585
+ // 让每个参数值都参与统计(多参数时不再误当成 GROUP_CONCAT 的分隔符)。
2586
+ const items = [column];
2587
+ while (this.peek().type === 'op' && this.peek().value === ',') {
2588
+ this.next();
2589
+ items.push(this.parseScalar());
2590
+ }
2591
+ column = { type: 'arglist', items };
2592
+ } else {
2593
+ // GROUP_CONCAT(expr, 'sep')
2594
+ this.next();
2595
+ separator = this.parseValue();
2596
+ }
2580
2597
  }
2581
2598
  // GROUP_CONCAT(expr ORDER BY col [DESC])
2582
2599
  if (this.isKeyword('ORDER')) {
@@ -3438,6 +3455,24 @@ class BinaryValue {
3438
3455
 
3439
3456
  function isBinaryValue(v) { return v instanceof BinaryValue; }
3440
3457
 
3458
+ /**
3459
+ * Issue #111:按 Unicode code point 定位子串,返回 1-based 字符位置;
3460
+ * 未找到返回 0(与 MySQL LOCATE/INSTR 一致)。空子串返回 1。
3461
+ * 用 Array.from 把代理对拆成单个 code point,避免 emoji 被当成两个字符。
3462
+ */
3463
+ function codePointIndexOf(needle, haystack) {
3464
+ const hay = Array.from(String(haystack));
3465
+ const pat = Array.from(String(needle));
3466
+ if (pat.length === 0) return 1;
3467
+ outer: for (let i = 0; i + pat.length <= hay.length; i++) {
3468
+ for (let j = 0; j < pat.length; j++) {
3469
+ if (hay[i + j] !== pat[j]) continue outer;
3470
+ }
3471
+ return i + 1;
3472
+ }
3473
+ return 0;
3474
+ }
3475
+
3441
3476
  /** 去重 / GROUP BY / 窗口分组用的键:二进制值按文本,其余保持原逻辑 */
3442
3477
  function valueKey(v) {
3443
3478
  if (isBinaryValue(v)) return v.toString();
@@ -4226,8 +4261,10 @@ function applyScalarFunction(fnNode, row, ctx) {
4226
4261
  : (isBinaryValue(args[0]) ? args[0].bytes.length : Buffer.byteLength(String(args[0]), 'utf8'));
4227
4262
  case 'CHAR_LENGTH': case 'CHARACTER_LENGTH':
4228
4263
  // MySQL:二进制串的 CHAR_LENGTH 也等于字节数
4264
+ // Issue #111:文本按 Unicode code point 计数(Array.from 会按代理对合并),
4265
+ // 否则 '🚀' 会被算成 2(UTF-16 code unit 数)。
4229
4266
  return args[0] == null ? null
4230
- : (isBinaryValue(args[0]) ? args[0].bytes.length : String(args[0]).length);
4267
+ : (isBinaryValue(args[0]) ? args[0].bytes.length : Array.from(String(args[0])).length);
4231
4268
  // TRIM(s) / TRIM([LEADING|TRAILING|BOTH] chars FROM s) / TRIM(s, chars)
4232
4269
  case 'TRIM': {
4233
4270
  if (args[0] == null) return null;
@@ -4715,25 +4752,26 @@ function applyScalarFunction(fnNode, row, ctx) {
4715
4752
  }
4716
4753
  case 'SUBSTRING': case 'SUBSTR': {
4717
4754
  if (args[0] == null) return null;
4718
- const s = String(args[0]);
4719
- const len = s.length;
4755
+ // Issue #111:按 code point 切分,避免把 emoji/增补平面字符劈成孤立代理项
4756
+ const cps = Array.from(String(args[0]));
4757
+ const len = cps.length;
4720
4758
  let start = Number(args[1]);
4721
4759
  // MySQL 语义:1-based;负数从末尾倒数;0 视为 1(MySQL 返回空串)
4722
4760
  if (start === 0) return '';
4723
4761
  if (start < 0) start = len + start + 1;
4724
4762
  if (args[2] !== undefined) {
4725
- let n = Number(args[2]);
4763
+ const n = Number(args[2]);
4726
4764
  if (n < 0) return '';
4727
- return s.substr(start - 1, n);
4765
+ return cps.slice(start - 1, start - 1 + n).join('');
4728
4766
  }
4729
- return s.substr(start - 1);
4767
+ return cps.slice(start - 1).join('');
4730
4768
  }
4731
4769
  case 'LEFT': {
4732
4770
  if (args[0] == null) return null;
4733
4771
  const n = Number(args[1]);
4734
4772
  // MySQL:长度 <= 0 返回空串(此前 slice(0, -1) 返回「去尾 1 字符」的 'ab')
4735
4773
  if (!Number.isFinite(n) || n <= 0) return '';
4736
- return String(args[0]).slice(0, Math.trunc(n));
4774
+ return Array.from(String(args[0])).slice(0, Math.trunc(n)).join('');
4737
4775
  }
4738
4776
  case 'RIGHT': {
4739
4777
  if (args[0] == null) return null;
@@ -4742,21 +4780,23 @@ function applyScalarFunction(fnNode, row, ctx) {
4742
4780
  // 所以 0 必须显式短路,不能只判 n < 0。
4743
4781
  if (!Number.isFinite(n) || n <= 0) return '';
4744
4782
  const s = String(args[0]);
4745
- return n >= s.length ? s : s.slice(s.length - n);
4783
+ const cps = Array.from(s); // Issue #111:code point 语义
4784
+ return n >= cps.length ? s : cps.slice(cps.length - n).join('');
4746
4785
  }
4747
4786
  case 'LOCATE': {
4748
4787
  if (args[0] == null || args[1] == null) return null;
4749
- const idx = String(args[1]).indexOf(String(args[0]));
4750
- return idx + 1;
4788
+ // Issue #111:按 code point 定位,返回**字符**位置(不是 UTF-16 code unit 下标)
4789
+ return codePointIndexOf(String(args[0]), String(args[1]));
4751
4790
  }
4752
4791
  case 'INSTR': {
4753
4792
  // INSTR(str, substr):参数顺序与 LOCATE(substr, str) 相反。
4754
4793
  // 此前两者共用一段代码,导致 INSTR 静默返回 0。
4755
4794
  if (args[0] == null || args[1] == null) return null;
4756
- const idx = String(args[0]).indexOf(String(args[1]));
4757
- return idx + 1;
4795
+ // Issue #111:code point 语义,返回字符位置
4796
+ return codePointIndexOf(String(args[1]), String(args[0]));
4758
4797
  }
4759
- case 'REVERSE': return args[0] == null ? null : String(args[0]).split('').reverse().join('');
4798
+ // Issue #111:code point 反转,否则代理对会被倒着拼成非法字符串('b\uDE80\uD83Da')
4799
+ case 'REVERSE': return args[0] == null ? null : Array.from(String(args[0])).reverse().join('');
4760
4800
 
4761
4801
  // ---- 以下这批此前没有实现:调用时静默返回 null(不报错),
4762
4802
  // 只有拿标准答案对照才发现。语义按 MySQL 8.0。
@@ -4813,23 +4853,31 @@ function applyScalarFunction(fnNode, row, ctx) {
4813
4853
  case 'LPAD': {
4814
4854
  if (args[0] == null || args[1] == null) return null;
4815
4855
  const s = String(args[0]);
4856
+ const cps = Array.from(s); // Issue #111:长度/截断都按 code point
4816
4857
  const n = Math.trunc(Number(args[1]));
4817
4858
  if (!Number.isFinite(n) || n < 0) return null;
4818
- if (n <= s.length) return s.slice(0, n);
4859
+ if (n <= cps.length) return cps.slice(0, n).join('');
4819
4860
  const pad = args[2] == null ? ' ' : String(args[2]);
4820
4861
  if (pad === '') return '';
4821
- const fill = pad.repeat(Math.ceil((n - s.length) / pad.length)).slice(0, n - s.length);
4862
+ const padCps = Array.from(pad);
4863
+ let fill = '';
4864
+ const need = n - cps.length;
4865
+ for (let i = 0; i < need; i++) fill += padCps[i % padCps.length];
4822
4866
  return fill + s;
4823
4867
  }
4824
4868
  case 'RPAD': {
4825
4869
  if (args[0] == null || args[1] == null) return null;
4826
4870
  const s = String(args[0]);
4871
+ const cps = Array.from(s); // Issue #111:长度/截断都按 code point
4827
4872
  const n = Math.trunc(Number(args[1]));
4828
4873
  if (!Number.isFinite(n) || n < 0) return null;
4829
- if (n <= s.length) return s.slice(0, n);
4874
+ if (n <= cps.length) return cps.slice(0, n).join('');
4830
4875
  const pad = args[2] == null ? ' ' : String(args[2]);
4831
4876
  if (pad === '') return '';
4832
- const fill = pad.repeat(Math.ceil((n - s.length) / pad.length)).slice(0, n - s.length);
4877
+ const padCps = Array.from(pad);
4878
+ let fill = '';
4879
+ const need = n - cps.length;
4880
+ for (let i = 0; i < need; i++) fill += padCps[i % padCps.length];
4833
4881
  return s + fill;
4834
4882
  }
4835
4883
  case 'RAND': return args.length > 0 && args[0] != null ? seedRand(Number(args[0]))() : Math.random();
@@ -7575,11 +7623,15 @@ class SQLExecutor {
7575
7623
  const noColumn = !op || op.type === 'star';
7576
7624
  let values = noColumn
7577
7625
  ? rows.map(r => 1)
7578
- : op && op.type === 'tuple'
7579
- // COUNT(DISTINCT a, b):先把多列拼成元组再聚合
7580
- ? rows.map(r => JSON.stringify(op.items.map(it => resolveOperand(it, r, this.ctx))))
7626
+ // Issue #114:VARIANCE(1,2,3) 这类多参数写法,所有参数值都纳入统计
7627
+ : op && op.type === 'arglist'
7628
+ ? rows.flatMap(r => op.items.map(it => resolveOperand(it, r, this.ctx)))
7581
7629
  .filter(v => v !== null && v !== undefined)
7582
- : rows.map(r => resolveOperand(op, r, this.ctx)).filter(v => v !== null && v !== undefined);
7630
+ // COUNT(DISTINCT a, b):先把多列拼成元组再聚合
7631
+ : op && op.type === 'tuple'
7632
+ ? rows.map(r => JSON.stringify(op.items.map(it => resolveOperand(it, r, this.ctx))))
7633
+ .filter(v => v !== null && v !== undefined)
7634
+ : rows.map(r => resolveOperand(op, r, this.ctx)).filter(v => v !== null && v !== undefined);
7583
7635
  // COUNT(DISTINCT x) / SUM(DISTINCT x):先按值去重再聚合
7584
7636
  if (distinct) {
7585
7637
  const seen = new Set();
@@ -7698,17 +7750,17 @@ class SQLExecutor {
7698
7750
  const sep = (separator !== undefined && separator !== null) ? String(separator) : ',';
7699
7751
  return joined.map(v => (v === null || v === undefined ? '' : String(v))).join(sep);
7700
7752
  }
7701
- // 标准差 / 方差族:_POP 为总体、_SAMP(及无后缀 VAR/STDDEV)为样本
7702
- if (fn === 'STDDEV' || fn === 'STDDEV_POP' || fn === 'STDDEV_SAMP' ||
7703
- fn === 'VARIANCE' || fn === 'VAR_POP' || fn === 'VAR_SAMP') {
7753
+ // 标准差 / 方差族:_POP 与无后缀 VARIANCE/STDDEV/STD 为总体,仅 _SAMP 为样本
7754
+ if (VARIANCE_FUNCS.has(fn)) {
7704
7755
  const nums = values.map(v => Number(v)).filter(v => Number.isFinite(v));
7705
7756
  if (nums.length === 0) return null;
7706
- const pop = (fn === 'STDDEV_POP' || fn === 'VAR_POP');
7757
+ const pop = (fn === 'STDDEV_POP' || fn === 'VAR_POP' || fn === 'VARIANCE' || fn === 'STDDEV' || fn === 'STD');
7707
7758
  const mean = nums.reduce((s, v) => s + v, 0) / nums.length;
7708
7759
  const denom = pop ? nums.length : nums.length - 1; // 样本方差用 n-1
7709
7760
  if (denom <= 0) return null;
7710
7761
  const variance = nums.reduce((s, v) => s + (v - mean) * (v - mean), 0) / denom;
7711
- return fn.indexOf('STDDEV') === 0 ? Math.sqrt(variance) : variance;
7762
+ const isStddev = (fn === 'STDDEV' || fn === 'STD' || fn === 'STDDEV_POP' || fn === 'STDDEV_SAMP');
7763
+ return isStddev ? Math.sqrt(variance) : variance;
7712
7764
  }
7713
7765
  return null;
7714
7766
  }
package/lib/table.js CHANGED
@@ -415,6 +415,7 @@ class Table {
415
415
  hook(data);
416
416
  }
417
417
  this._db._emitChange('insert', this._name, data);
418
+ this._db._walLogUpsert(this._name, [data]);
418
419
 
419
420
  return data;
420
421
  }
@@ -537,6 +538,7 @@ class Table {
537
538
  for (let i = 0; i < N; i++) hook(result[i]);
538
539
  }
539
540
  this._db._emitChange('insertMany', this._name, { count: N });
541
+ this._db._walLogUpsert(this._name, result);
540
542
  return result;
541
543
  }
542
544
 
@@ -648,6 +650,7 @@ class Table {
648
650
  hook(query, updates, count);
649
651
  }
650
652
  this._db._emitChange('update', this._name, { query, updates, count });
653
+ this._db._walLogUpsert(this._name, matched);
651
654
  }
652
655
  return count;
653
656
  }
@@ -690,6 +693,7 @@ class Table {
690
693
  hook({ [this._primaryKey]: id }, updates, 1);
691
694
  }
692
695
  this._db._emitChange('update', this._name, { query: { [this._primaryKey]: id }, updates, count: 1 });
696
+ this._db._walLogUpsert(this._name, [row]);
693
697
  return 1;
694
698
  }
695
699
 
@@ -754,6 +758,7 @@ class Table {
754
758
  hook(query, count);
755
759
  }
756
760
  this._db._emitChange('remove', this._name, { query, count });
761
+ this._db._walLogRemove(this._name, toRemove);
757
762
  }
758
763
  return count;
759
764
  }
@@ -815,6 +820,7 @@ class Table {
815
820
  hook({ [this._primaryKey]: id }, 1);
816
821
  }
817
822
  this._db._emitChange('remove', this._name, { query: { [this._primaryKey]: id }, count: 1 });
823
+ this._db._walLogRemove(this._name, [row]);
818
824
  return 1;
819
825
  }
820
826
 
@@ -839,6 +845,7 @@ class Table {
839
845
  hook(query, count);
840
846
  }
841
847
  this._db._emitChange('remove', this._name, { query, count, soft: true });
848
+ this._db._walLogUpsert(this._name, matched);
842
849
  }
843
850
  return count;
844
851
  }
@@ -884,6 +891,7 @@ class Table {
884
891
  // P1-13: truncate 不应重置软删除模式——保留原值
885
892
  this._dirty = true;
886
893
  this._db._markDirty(this._name);
894
+ this._db._walLogReplaceTable(this._name);
887
895
  return count;
888
896
  }
889
897
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.7.3",
3
+ "version": "6.7.5",
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,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
+ });
@@ -0,0 +1,102 @@
1
+ /* ---- Issue #114:方差/标准差族的总体 vs 样本语义回归 ---- */
2
+ /*
3
+ * MySQL 8.0 语义:
4
+ * VARIANCE(expr) = VAR_POP(expr) → 总体方差(分母 n)
5
+ * VAR_POP(expr) → 总体方差(分母 n)
6
+ * VAR_SAMP(expr) → 样本方差(分母 n-1)
7
+ * STDDEV(expr) = STDDEV_POP(expr) → 总体标准差
8
+ * STD(expr) = STDDEV_POP(expr) → 总体标准差(此前静默返回 NULL)
9
+ * STDDEV_SAMP(expr) → 样本标准差
10
+ *
11
+ * 此前无后缀版本全部落进 n-1 分支,结果系统性偏大。
12
+ *
13
+ * node test/issue-114.test.js
14
+ */
15
+ const path = require('path');
16
+ const ROOT = path.join(__dirname, '..');
17
+ const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
18
+
19
+ let pass = 0, fail = 0;
20
+ function ok(name, cond, got) {
21
+ if (cond) { pass++; console.log('[OK] ' + name); }
22
+ else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
23
+ }
24
+ function near(a, b, eps = 1e-12) {
25
+ return typeof a === 'number' && typeof b === 'number' && Math.abs(a - b) < eps;
26
+ }
27
+
28
+ (async () => {
29
+ const db = new Database(':memory:', { autoSave: false });
30
+ const q = async (sql) => {
31
+ const r = await executeSQL(db, sql, { safety: false });
32
+ return r.rows[0][0];
33
+ };
34
+
35
+ // ---------- 无后缀版本 = 总体 ----------
36
+ const variance123 = await q("SELECT VARIANCE(1,2,3)");
37
+ ok('VARIANCE(1,2,3) = 2/3(总体)', near(variance123, 2 / 3), variance123);
38
+
39
+ const stddev123 = await q("SELECT STDDEV(1,2,3)");
40
+ ok('STDDEV(1,2,3) = √(2/3)(总体)', near(stddev123, Math.sqrt(2 / 3)), stddev123);
41
+
42
+ const std123 = await q("SELECT STD(1,2,3)");
43
+ ok('STD(1,2,3) = √(2/3)(STDDEV_POP 别名,不再为 NULL)',
44
+ near(std123, Math.sqrt(2 / 3)), std123);
45
+
46
+ // ---------- _POP / _SAMP 保持不变 ----------
47
+ const varPop = await q("SELECT VAR_POP(1,2,3)");
48
+ ok('VAR_POP(1,2,3) = 2/3', near(varPop, 2 / 3), varPop);
49
+
50
+ const varSamp = await q("SELECT VAR_SAMP(1,2,3)");
51
+ ok('VAR_SAMP(1,2,3) = 1', near(varSamp, 1), varSamp);
52
+
53
+ const stddevPop = await q("SELECT STDDEV_POP(1,2,3)");
54
+ ok('STDDEV_POP(1,2,3) = √(2/3)', near(stddevPop, Math.sqrt(2 / 3)), stddevPop);
55
+
56
+ const stddevSamp = await q("SELECT STDDEV_SAMP(1,2,3)");
57
+ ok('STDDEV_SAMP(1,2,3) = 1', near(stddevSamp, 1), stddevSamp);
58
+
59
+ // ---------- 小样本 n=2:此前 VARIANCE 结果翻倍 ----------
60
+ const v1020 = await q("SELECT VARIANCE(10,20)");
61
+ ok('VARIANCE(10,20) = 25(不是 50)', near(v1020, 25), v1020);
62
+
63
+ const s1020 = await q("SELECT VAR_SAMP(10,20)");
64
+ ok('VAR_SAMP(10,20) = 50', near(s1020, 50), s1020);
65
+
66
+ // ---------- 单列聚合(issue 原始复现) ----------
67
+ const sub = '(SELECT 1 v UNION ALL SELECT 2 UNION ALL SELECT 3) t';
68
+ const vAgg = await q(`SELECT VARIANCE(v) FROM ${sub}`);
69
+ ok('VARIANCE(v) 聚合 = 2/3', near(vAgg, 2 / 3), vAgg);
70
+
71
+ const sAgg = await q(`SELECT STDDEV(v) FROM ${sub}`);
72
+ ok('STDDEV(v) 聚合 = √(2/3)', near(sAgg, Math.sqrt(2 / 3)), sAgg);
73
+
74
+ const stdAgg = await q(`SELECT STD(v) FROM ${sub}`);
75
+ ok('STD(v) 聚合 = √(2/3)', near(stdAgg, Math.sqrt(2 / 3)), stdAgg);
76
+
77
+ const vpAgg = await q(`SELECT VAR_POP(v) FROM ${sub}`);
78
+ ok('VAR_POP(v) 聚合 = 2/3', near(vpAgg, 2 / 3), vpAgg);
79
+
80
+ const vsAgg = await q(`SELECT VAR_SAMP(v) FROM ${sub}`);
81
+ ok('VAR_SAMP(v) 聚合 = 1', near(vsAgg, 1), vsAgg);
82
+
83
+ // ---------- 分组聚合 ----------
84
+ await executeSQL(db, 'CREATE TABLE g (k INT, v INT)', { safety: false });
85
+ await executeSQL(db, 'INSERT INTO g (k, v) VALUES (1,1),(1,2),(1,3),(2,10),(2,20)', { safety: false });
86
+ const rows = (await executeSQL(db, 'SELECT k, VARIANCE(v) AS var, STD(v) AS sd, VAR_SAMP(v) AS vs FROM g GROUP BY k ORDER BY k', { safety: false })).rows;
87
+ ok('分组聚合返回 2 行', rows.length === 2, rows.length);
88
+ ok('组 k=1 VARIANCE = 2/3', rows[0] && near(rows[0][1], 2 / 3), rows[0] && rows[0][1]);
89
+ ok('组 k=1 STD = √(2/3)', rows[0] && near(rows[0][2], Math.sqrt(2 / 3)), rows[0] && rows[0][2]);
90
+ ok('组 k=2 VARIANCE = 25', rows[1] && near(rows[1][1], 25), rows[1] && rows[1][1]);
91
+
92
+ // ---------- NULL 处理:全 NULL → NULL ----------
93
+ await executeSQL(db, 'CREATE TABLE n (v INT)', { safety: false });
94
+ await executeSQL(db, 'INSERT INTO n (v) VALUES (NULL)', { safety: false });
95
+ ok('全 NULL 的 VARIANCE 返回 NULL', await q('SELECT VARIANCE(v) FROM n') === null, null);
96
+
97
+ console.log(`\n${pass} passed, ${fail} failed`);
98
+ process.exit(fail === 0 ? 0 : 1);
99
+ })().catch(e => {
100
+ console.log('[FAIL] unexpected exception: ' + e.stack.split('\n').slice(0, 3).join('\n'));
101
+ process.exit(1);
102
+ });
@@ -156,6 +156,28 @@ const SCHEMA = { id: { type: 'integer', primaryKey: true }, v: { type: 'string'
156
156
  fs.rmSync(dir, { recursive: true, force: true });
157
157
  }
158
158
 
159
+ console.log('--- 8. 默认即 WAL:不传 wal、也不调用 save() 也必须恢复 ---');
160
+ {
161
+ const { dir, file } = tmpFile('default');
162
+ const db = new Database(file, { autoSave: false });
163
+ ok('文件模式默认启用 WAL', db._walEnabled === true);
164
+ await db.createTable('t', SCHEMA);
165
+ await db.createTable('np', { x: { type: 'string' } });
166
+ await db.insert('t', { id: 1, v: 'a' });
167
+ await db.updateById('t', 1, { v: 'a2' });
168
+ await db.insert('np', { x: 'n1' });
169
+ await db.insert('np', { x: 'n2' });
170
+ await db.delete('np', { x: 'n1' });
171
+ ok('写入后立即产生 .wal', fs.existsSync(file + '.wal'));
172
+
173
+ const db2 = new Database(file); // 不传 wal,模拟进程崩溃后重启
174
+ const rows = await db2.find('t', {});
175
+ const npRows = await db2.find('np', {});
176
+ ok('默认 WAL 恢复主键表', rows.length === 1 && rows[0].v === 'a2', rows);
177
+ ok('默认 WAL 恢复无主键表', npRows.length === 1 && npRows[0].x === 'n2', npRows);
178
+ fs.rmSync(dir, { recursive: true, force: true });
179
+ }
180
+
159
181
  console.log(`\n${pass} passed, ${fail} failed`);
160
182
  process.exit(fail === 0 ? 0 : 1);
161
183
  })().catch(e => { console.error('FATAL', e); process.exit(1); });