jsql-neo 6.8.4 → 6.8.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/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  > **One engine to rule them all** — a Rust-powered embedded database that speaks your language:
4
4
  > MySQL, PostgreSQL, MongoDB, Redis, SQL, TypeScript, **and the browser**.
5
5
 
6
- > **v6.8.4** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
6
+ > **v6.8.6** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
7
7
 
8
8
  ![Engines](https://img.shields.io/badge/engines-Native%20%7C%20WASM%20%7C%20Pure%20JS-7ee787)
9
9
  ![MySQL](https://img.shields.io/badge/protocol-MySQL%20compatible-1f6feb)
package/bin/jsql CHANGED
@@ -14,7 +14,9 @@ const { nag, setStarred, readConfig } = require('../lib/star-nag');
14
14
  // star 提示:任何异常都不该挡住命令本身
15
15
  // version / --version 只回版本号、star 本身就是干这件事的 —— 这些不提示,其余全部提示
16
16
  const NO_NAG_ARGS = new Set(['version', '--version', '-v', 'star', 'update', 'uninstall', 'remove']);
17
- if (!process.env.JSQL_NO_STAR_NAG && !NO_NAG_ARGS.has(process.argv[2])) {
17
+ // #189:--json 的 stdout 必须是纯 JSON,star 提示会污染机器可读输出
18
+ const WANTS_JSON = process.argv.slice(2).includes('--json');
19
+ if (!process.env.JSQL_NO_STAR_NAG && !WANTS_JSON && !NO_NAG_ARGS.has(process.argv[2])) {
18
20
  try { nag(); } catch (e) { /* 提示失败与命令无关 */ }
19
21
  }
20
22
 
@@ -378,7 +380,8 @@ const cli = (yaggs || require('./yaggs-fallback').buildYaggsFallback(_pkg))({
378
380
  sub.option('data-dir', { type: 'string', description: 'Data directory (default :memory:)' });
379
381
  sub.option('json', { type: 'boolean', description: 'Output as JSON' });
380
382
  }, async (argv) => {
381
- const N = argv.n || 10000;
383
+ // #188:回退解析器不做类型强转,数值选项在这里归一
384
+ const N = Number(argv.n) || 10000;
382
385
  const dataDir = argv['data-dir'] || ':memory:';
383
386
  try {
384
387
  const db = new Database(dataDir === ':memory:' ? ':memory:' : path.join(dataDir, 'bench.json'), { autoSave: false });
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.8.4 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.8.6 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
@@ -12,9 +12,18 @@
12
12
  */
13
13
 
14
14
  const MARKER = '__jsql_bigint__';
15
+ // #169:用户数据里恰好有 { __jsql_bigint__: "123" } 时,用 NUL 前缀转义,
16
+ // reviver 只还原没有被转义的标记,避免把用户对象误改成 BigInt。
17
+ const ESCAPE = '\u0000';
15
18
 
16
19
  function replacer(_key, value) {
17
20
  if (typeof value === 'bigint') return { [MARKER]: value.toString() };
21
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
22
+ const keys = Object.keys(value);
23
+ if (keys.length === 1 && keys[0] === MARKER && typeof value[MARKER] === 'string') {
24
+ return { [MARKER]: ESCAPE + value[MARKER] };
25
+ }
26
+ }
18
27
  return value;
19
28
  }
20
29
 
@@ -22,6 +31,9 @@ function reviver(_key, value) {
22
31
  if (value && typeof value === 'object' && !Array.isArray(value)) {
23
32
  const keys = Object.keys(value);
24
33
  if (keys.length === 1 && keys[0] === MARKER && typeof value[MARKER] === 'string') {
34
+ if (value[MARKER].startsWith(ESCAPE)) {
35
+ return { [MARKER]: value[MARKER].slice(ESCAPE.length) };
36
+ }
25
37
  try { return BigInt(value[MARKER]); } catch (_) { return value; }
26
38
  }
27
39
  }
package/lib/cache.js CHANGED
@@ -91,7 +91,17 @@ class Cache {
91
91
  incr(key) { return this._incrby(key, 1); }
92
92
  decr(key) { return this._incrby(key, -1); }
93
93
  incrby(key, increment) { return this._incrby(key, increment); }
94
- decrby(key, decrement) { return this._incrby(key, -decrement); }
94
+ decrby(key, decrement) {
95
+ // #167:一元负号会先把大整数字符串转成 Number 丢精度,改用 BigInt 取负
96
+ let delta;
97
+ if (typeof decrement === 'bigint') delta = -decrement;
98
+ else {
99
+ const s = String(decrement).trim();
100
+ if (!/^[-+]?\d+$/.test(s)) throw new Error('value is not an integer or out of range');
101
+ delta = -BigInt(s);
102
+ }
103
+ return this._incrby(key, delta);
104
+ }
95
105
  _incrby(key, delta) {
96
106
  const k = String(key);
97
107
  const isInt = (v) => typeof v === 'bigint'
@@ -112,6 +122,8 @@ class Cache {
112
122
 
113
123
  hset(key, field, value) {
114
124
  const k = String(key);
125
+ // #166:_type 是内部类型标记,不能被用户字段覆盖
126
+ if (field === '_type') throw new Error('ERR reserved field name _type');
115
127
  let hash = this._getData().get(k);
116
128
  if (hash !== undefined && (typeof hash !== 'object' || hash._type !== 'hash')) {
117
129
  throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
@@ -127,6 +139,7 @@ class Cache {
127
139
  if (this._isExpired(k)) return null;
128
140
  const hash = this._getData().get(k);
129
141
  if (!hash || typeof hash !== 'object' || hash._type !== 'hash') return null;
142
+ if (field === '_type') return null;
130
143
  return hash[field] !== undefined ? hash[field] : null;
131
144
  }
132
145
  hgetall(key) {
@@ -143,7 +156,7 @@ class Cache {
143
156
  const hash = this._getData().get(k);
144
157
  if (!hash || typeof hash !== 'object' || hash._type !== 'hash') return 0;
145
158
  let count = 0;
146
- for (const field of fields) { if (delete hash[field]) count++; }
159
+ for (const field of fields) { if (field !== '_type' && delete hash[field]) count++; }
147
160
  if (count > 0) this._dirty = true;
148
161
  return count;
149
162
  }
@@ -280,8 +293,11 @@ class Cache {
280
293
  return count;
281
294
  }
282
295
  select(index) {
283
- const idx = Number(index);
284
- if (idx < 0 || idx > 15) throw new Error('DB index out of range');
296
+ // #165:只接受十进制整数;NaN / 小数 / Infinity 不能被当作合法索引
297
+ const s = String(index).trim();
298
+ if (!/^-?\d+$/.test(s)) throw new Error('value is not an integer or out of range');
299
+ const idx = Number(s);
300
+ if (!Number.isSafeInteger(idx) || idx < 0 || idx > 15) throw new Error('DB index out of range');
285
301
  this._db = idx;
286
302
  if (!this._dbs[idx]) { this._dbs[idx] = new Map(); this._dbsExpires[idx] = new Map(); }
287
303
  this._data = this._dbs[idx];
@@ -325,7 +325,9 @@ function groupBy(statement, data) {
325
325
  else row.push(st.seen ? st.best : null);
326
326
  } else {
327
327
  const n = colNameOf(c.scalar || c.expr);
328
- row.push(entry.keyVals[gNames.indexOf(n)]);
328
+ // #233:布尔分组键与通用路径的 projectScalar 保持一致(true→1, false→0)
329
+ const gv = entry.keyVals[gNames.indexOf(n)];
330
+ row.push(gv === true ? 1 : gv === false ? 0 : gv);
329
331
  }
330
332
  }
331
333
  outRows.push(row);
package/lib/database.js CHANGED
@@ -321,6 +321,10 @@ class Database {
321
321
  }
322
322
 
323
323
  _markDirty(name) {
324
+ // #181:SQL 写路径(updateById/removeByIds 等)不经过 Table.update/remove,
325
+ // 统一在这里让列存派生缓存失效,避免后续 SELECT 读到旧快照。
326
+ const table = name && this._tables ? this._tables[name] : null;
327
+ if (table && typeof table._invalidateColumnar === 'function') table._invalidateColumnar();
324
328
  if (!this._dirMode) {
325
329
  this._dirty = true;
326
330
  return;
@@ -678,6 +682,27 @@ class Database {
678
682
  * 日志格式为 append-only JSONL;最后一行可能在崩溃时写半,
679
683
  * 因此解析时逐行 try/catch,坏行直接丢弃(它必然是未完成的那条)。
680
684
  */
685
+ /**
686
+ * #237:快照损坏时 WAL 里可能只有行数据、没有建表记录。
687
+ * 从行值推断一个最小 schema,让 WAL 能重放而不是因「表不存在」全部失败。
688
+ */
689
+ _inferWalSchema(rows) {
690
+ const defs = {};
691
+ for (const row of rows || []) {
692
+ if (!row || typeof row !== 'object') continue;
693
+ for (const [field, value] of Object.entries(row)) {
694
+ if (value === null || value === undefined || defs[field]) continue;
695
+ let type = 'string';
696
+ if (typeof value === 'number') type = Number.isInteger(value) ? 'integer' : 'number';
697
+ else if (typeof value === 'boolean') type = 'boolean';
698
+ else if (Array.isArray(value)) type = 'array';
699
+ else if (typeof value === 'object') type = 'object';
700
+ defs[field] = { type };
701
+ }
702
+ }
703
+ return defs;
704
+ }
705
+
681
706
  _recoverFromWAL() {
682
707
  if (!this._walEnabled || !this._walPath || !fs.existsSync(this._walPath)) return;
683
708
 
@@ -735,7 +760,11 @@ class Database {
735
760
  try {
736
761
  switch (op.op) {
737
762
  case 'insert': {
738
- const t = op.table && this._tables[op.table];
763
+ let t = op.table && this._tables[op.table];
764
+ if (!t && op.table && Array.isArray(op.rows) && op.rows.length > 0) {
765
+ this._createTableSync(op.table, this._inferWalSchema(op.rows));
766
+ t = this._tables[op.table];
767
+ }
739
768
  if (!t || !Array.isArray(op.rows) || op.rows.length === 0) { failed++; break; }
740
769
  const pk = t._primaryKey;
741
770
  for (const __e of op.rows) {
@@ -751,7 +780,11 @@ class Database {
751
780
  break;
752
781
  }
753
782
  case 'upsertRows': {
754
- const t = op.table && this._tables[op.table];
783
+ let t = op.table && this._tables[op.table];
784
+ if (!t && op.table && Array.isArray(op.rows) && op.rows.length > 0) {
785
+ this._createTableSync(op.table, this._inferWalSchema(op.rows));
786
+ t = this._tables[op.table];
787
+ }
755
788
  if (!t || !op.pk || !Array.isArray(op.rows)) { failed++; break; }
756
789
  for (const __r of op.rows) {
757
790
  if (!__r || typeof __r !== 'object') continue;
@@ -773,7 +806,11 @@ class Database {
773
806
  break;
774
807
  }
775
808
  case 'replaceTable': {
776
- const t = op.table && this._tables[op.table];
809
+ let t = op.table && this._tables[op.table];
810
+ if (!t && op.table && Array.isArray(op.rows) && op.rows.length > 0) {
811
+ this._createTableSync(op.table, this._inferWalSchema(op.rows));
812
+ t = this._tables[op.table];
813
+ }
777
814
  if (!t || !Array.isArray(op.rows)) { failed++; break; }
778
815
  t._rows = op.rows.map(r => ({ ...r }));
779
816
  touched.add(t);
@@ -993,11 +1030,32 @@ class Database {
993
1030
 
994
1031
  async dropTable(name) {
995
1032
  if (!this._tables[name] && !(this._dirMode && this._meta.tables[name])) throw createError('ER_NO_SUCH_TABLE', name);
1033
+ // #200:被外键引用且存在引用行时禁止删除父表
1034
+ if (this._foreignReferencingRows(name).length > 0) {
1035
+ throw createError('ER_ROW_IS_REFERENCED_2', name);
1036
+ }
996
1037
  if (!(await this._runHooks('beforeDropTable', [name]))) return;
997
1038
  this._dropTableSync(name);
998
1039
  await this._runHooks('afterDropTable', [name]);
999
1040
  }
1000
1041
 
1042
+ /**
1043
+ * 找出所有引用指定父表的子表外键,且子表中至少有一行非空引用值。
1044
+ * 用于 DROP TABLE / TRUNCATE 的引用完整性检查。
1045
+ */
1046
+ _foreignReferencingRows(parentName) {
1047
+ const target = String(parentName).toLowerCase();
1048
+ const refs = [];
1049
+ for (const [childName, table] of Object.entries(this._tables)) {
1050
+ for (const fk of (table._foreignKeys || [])) {
1051
+ if (String(fk.table).toLowerCase() !== target) continue;
1052
+ const hasRow = table._rows.some(r => r[fk.field] !== undefined && r[fk.field] !== null);
1053
+ if (hasRow) refs.push({ child: childName, field: fk.field });
1054
+ }
1055
+ }
1056
+ return refs;
1057
+ }
1058
+
1001
1059
  /**
1002
1060
  * 重命名表。
1003
1061
  *
@@ -1200,21 +1258,22 @@ class Database {
1200
1258
  const mapping = options.mapping || null;
1201
1259
 
1202
1260
  const content = fs.readFileSync(filePath, 'utf8');
1203
- const lines = content.split(/\r?\n/).filter(l => l.trim());
1261
+ // #184:RFC 4180 允许引号字段内出现换行,不能先按行切分
1262
+ const records = this._parseCSV(content, delimiter);
1204
1263
 
1205
1264
  let headers = [];
1206
1265
  let startRow = 0;
1207
1266
 
1208
1267
  if (hasHeader) {
1209
- headers = this._parseCSVLine(lines[0], delimiter);
1268
+ headers = records[0] || [];
1210
1269
  startRow = 1 + skipRows;
1211
1270
  } else {
1212
1271
  startRow = skipRows;
1213
1272
  }
1214
1273
 
1215
1274
  let count = 0;
1216
- for (let i = startRow; i < lines.length; i++) {
1217
- const values = this._parseCSVLine(lines[i], delimiter);
1275
+ for (let i = startRow; i < records.length; i++) {
1276
+ const values = records[i];
1218
1277
  if (values.length === 0) continue;
1219
1278
 
1220
1279
  const data = {};
@@ -1269,37 +1328,60 @@ class Database {
1269
1328
  return lines.length - 1;
1270
1329
  }
1271
1330
 
1272
- _parseCSVLine(line, delimiter) {
1273
- const result = [];
1274
- let current = '';
1331
+ /**
1332
+ * RFC 4180 解析:引号内的 CR/LF、逗号和双引号都是数据;
1333
+ * 非引号字段保留首尾空格(原实现会 trim,破坏有意义的数据)。
1334
+ */
1335
+ _parseCSV(text, delimiter) {
1336
+ const records = [];
1337
+ let record = [];
1338
+ let field = '';
1339
+ let fieldStarted = false;
1275
1340
  let inQuotes = false;
1341
+ const s = String(text).replace(/^\uFEFF/, '');
1342
+
1343
+ const pushField = () => {
1344
+ record.push(field);
1345
+ field = '';
1346
+ fieldStarted = false;
1347
+ };
1348
+ const pushRecord = () => {
1349
+ pushField();
1350
+ records.push(record);
1351
+ record = [];
1352
+ };
1276
1353
 
1277
- for (let i = 0; i < line.length; i++) {
1278
- const ch = line[i];
1354
+ for (let i = 0; i < s.length; i++) {
1355
+ const ch = s[i];
1279
1356
  if (inQuotes) {
1280
1357
  if (ch === '"') {
1281
- if (i + 1 < line.length && line[i + 1] === '"') {
1282
- current += '"';
1283
- i++;
1284
- } else {
1285
- inQuotes = false;
1286
- }
1358
+ if (s[i + 1] === '"') { field += '"'; i++; }
1359
+ else inQuotes = false;
1287
1360
  } else {
1288
- current += ch;
1361
+ field += ch;
1289
1362
  }
1363
+ } else if (ch === '"') {
1364
+ inQuotes = true;
1365
+ fieldStarted = true;
1366
+ } else if (ch === delimiter) {
1367
+ pushField();
1368
+ } else if (ch === '\r' || ch === '\n') {
1369
+ if (ch === '\r' && s[i + 1] === '\n') i++;
1370
+ // 空行不是记录;被引号包裹的空字段仍然算数据
1371
+ if (record.length > 0 || field !== '' || fieldStarted) pushRecord();
1372
+ else { field = ''; fieldStarted = false; }
1290
1373
  } else {
1291
- if (ch === '"') {
1292
- inQuotes = true;
1293
- } else if (ch === delimiter) {
1294
- result.push(current.trim());
1295
- current = '';
1296
- } else {
1297
- current += ch;
1298
- }
1374
+ field += ch;
1375
+ fieldStarted = true;
1299
1376
  }
1300
1377
  }
1301
- result.push(current.trim());
1302
- return result;
1378
+ if (record.length > 0 || field !== '' || fieldStarted) pushRecord();
1379
+ return records;
1380
+ }
1381
+
1382
+ _parseCSVLine(line, delimiter) {
1383
+ const records = this._parseCSV(line, delimiter);
1384
+ return records.length > 0 ? records[0] : [];
1303
1385
  }
1304
1386
 
1305
1387
  _csvEscape(value, delimiter) {
@@ -1479,11 +1561,16 @@ class Database {
1479
1561
  for (const [name, table] of Object.entries(this._tables)) {
1480
1562
  snap[name] = {
1481
1563
  rows: bigintJson.parse(bigintJson.stringify(table.toJSON())),
1482
- schema: table._schema,
1564
+ // #199:schema 必须深拷贝(到列定义层),否则 ALTER TABLE 会直接改到快照,
1565
+ // ROLLBACK 后列结构无法还原。逐列浅拷贝可保留 check/computed 函数引用。
1566
+ schema: Object.fromEntries(Object.entries(table._schema).map(
1567
+ ([k, v]) => [k, v && typeof v === 'object' ? { ...v } : v]
1568
+ )),
1483
1569
  // 自增计数器也要存:否则回滚掉刚插入的行之后,
1484
1570
  // 下一次插入会跳过已用过的号(用户看到 id 从 2 开始会困惑)。
1485
1571
  // 原有 rollback() 一直是这么做的,保存点保持一致。
1486
- autoIncrement: table._autoIncrement
1572
+ autoIncrement: table._autoIncrement,
1573
+ hooks: table._hooks
1487
1574
  };
1488
1575
  }
1489
1576
  return snap;
@@ -1506,12 +1593,16 @@ class Database {
1506
1593
  }
1507
1594
  for (const [name, entry] of Object.entries(snap)) {
1508
1595
  const rows = bigintJson.parse(bigintJson.stringify(entry.rows));
1509
- let table = this._tables[name];
1510
- if (!table) {
1511
- table = new Table(name, entry.schema, this);
1512
- this._tables[name] = table;
1513
- }
1596
+ const prev = this._tables[name];
1597
+ // #199:用快照 schema 重建表对象,确保 ADD/DROP/MODIFY COLUMN、
1598
+ // 默认值、约束与派生缓存一并回滚。保留 hooks,避免回滚丢监听器。
1599
+ const schema = Object.fromEntries(Object.entries(entry.schema || {}).map(
1600
+ ([k, v]) => [k, v && typeof v === 'object' ? { ...v } : v]
1601
+ ));
1602
+ const table = new Table(name, schema, this);
1603
+ if (prev && prev._hooks) table._hooks = prev._hooks;
1514
1604
  table._loadRows(rows);
1605
+ this._tables[name] = table;
1515
1606
  // B1-2: 恢复后必须重新标记脏,否则 rollback 后 _flushDirty 空转
1516
1607
  // —— 事务写已落盘(900/600),回滚恢复正确数据(1000/500)到内存,
1517
1608
  // 但若不标记脏,_flushDirty 检测 _dirtyTables.size===0 直接 return,
@@ -1563,7 +1654,9 @@ class Database {
1563
1654
  // 快照:保存当前所有数据(深拷贝,保证嵌套对象可回滚)
1564
1655
  this._transaction.snapshot = this._captureTxSnapshot();
1565
1656
  } else {
1566
- // READ_COMMITTED:只保存 autoIncrement
1657
+ // #204:READ_COMMITTED 只降低读可见性,ROLLBACK 仍必须撤销写入,
1658
+ // 因此同样保存行快照(仅记录 autoIncrement 会让 UPDATE/INSERT 残留)。
1659
+ this._transaction.snapshot = this._captureTxSnapshot();
1567
1660
  for (const [name, table] of Object.entries(this._tables)) {
1568
1661
  this._transaction.autoIncrements[name] = table._autoIncrement;
1569
1662
  }
@@ -2028,11 +2121,11 @@ class Database {
2028
2121
  const arr = Array.isArray(data) ? data : [data];
2029
2122
  if (!(await this._runHooks('beforeInsert', [tableName, arr]))) return [];
2030
2123
  const pk = this._pkOf(table);
2031
- const ids = [];
2032
- for (const row of arr) {
2033
- const r = table.insert(row);
2034
- ids.push(pk ? r[pk] : table._rows.length);
2035
- }
2124
+ // #201:多行 INSERT 走 insertMany,逐行校验全部通过后再统一落库
2125
+ const inserted = (arr.length > 1 && typeof table.insertMany === 'function')
2126
+ ? table.insertMany(arr)
2127
+ : arr.map(row => table.insert(row));
2128
+ const ids = inserted.map((r, i) => (pk ? r[pk] : table._rows.length - inserted.length + i + 1));
2036
2129
  // WAL 已由 Table.insert() 在写入瞬间逐条落盘(含无主键表的整表镜像)
2037
2130
  this._emit('insert', { table: tableName, count: arr.length, ids });
2038
2131
  await this._runHooks('afterInsert', [tableName, arr, ids]);
@@ -2214,6 +2307,10 @@ class Database {
2214
2307
  if (typeof table._enforceChecks === 'function') {
2215
2308
  table._enforceChecks({ ...row, ...validated });
2216
2309
  }
2310
+ // #234:复合唯一索引在 UPDATE 路径上同样必须校验
2311
+ if (typeof table._checkCompositeUnique === 'function') {
2312
+ table._checkCompositeUnique({ ...row, ...validated }, table._rows.indexOf(row));
2313
+ }
2217
2314
  // 改主键/唯一值时索引必须同步:否则 _pkIndex 还指向旧值,
2218
2315
  // 后续 FK 校验 findOne({id:新值}) 查不到刚更新的父行。
2219
2316
  {
@@ -2398,6 +2495,10 @@ class Database {
2398
2495
  truncate(tableName) {
2399
2496
  const table = this._ensureTable(tableName);
2400
2497
  if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
2498
+ // #206:被外键引用的父表禁止 TRUNCATE(MySQL 1701),也不应触发级联
2499
+ if (this._foreignReferencingRows(tableName).length > 0) {
2500
+ throw createError('ER_TRUNCATE_ILLEGAL_FK', tableName);
2501
+ }
2401
2502
  // WAL 由 Table.truncate() 记录整表镜像
2402
2503
  const count = table.truncate();
2403
2504
  this._emit('delete', { table: tableName, count });
@@ -2587,7 +2688,18 @@ class Database {
2587
2688
  }
2588
2689
 
2589
2690
  const json = this._readFile(this._filePath);
2590
- const data = bigintJson.parse(json);
2691
+ let data;
2692
+ try {
2693
+ data = bigintJson.parse(json);
2694
+ } catch (parseErr) {
2695
+ // #237:快照损坏(崩溃半写)不能直接整库打不开;
2696
+ // 记录告警后继续走 WAL 恢复(缺失的表由 WAL 行推断重建)。
2697
+ const warn = new Error(`Snapshot '${this._filePath}' is corrupt (${parseErr.message}); attempting WAL recovery.`);
2698
+ try { this._emit('error', warn); } catch (e) { /* 监听器异常不阻塞恢复 */ }
2699
+ console.error('[jsql-neo] ' + warn.message);
2700
+ this._recoverFromWAL();
2701
+ return;
2702
+ }
2591
2703
 
2592
2704
  if (data.__schema__) {
2593
2705
  for (const [name, schema] of Object.entries(data.__schema__)) {
@@ -2718,17 +2830,29 @@ class Database {
2718
2830
  // ============================================================
2719
2831
 
2720
2832
  _writeFile(filePath, content) {
2833
+ let payload;
2721
2834
  if (this._encryptKey) {
2722
2835
  const iv = crypto.randomBytes(16);
2723
2836
  const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(this._encryptKey.padEnd(32).slice(0, 32)), iv);
2724
2837
  const encrypted = Buffer.concat([cipher.update(content, 'utf8'), cipher.final()]);
2725
2838
  const data = Buffer.concat([iv, encrypted]);
2726
- fs.writeFileSync(filePath, data.toString('base64'), 'utf8');
2839
+ payload = data.toString('base64');
2727
2840
  } else {
2728
- const dir = path.dirname(filePath);
2729
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
2730
- fs.writeFileSync(filePath, content, 'utf8');
2841
+ payload = content;
2842
+ }
2843
+ // #237:先写临时文件 + fsync,再原子 rename;崩溃只会留下旧快照或新快照,
2844
+ // 不会出现写到一半的半份 JSON。
2845
+ const dir = path.dirname(filePath);
2846
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
2847
+ const tmp = filePath + '.tmp';
2848
+ const fd = fs.openSync(tmp, 'w');
2849
+ try {
2850
+ fs.writeFileSync(fd, payload, 'utf8');
2851
+ fs.fsyncSync(fd);
2852
+ } finally {
2853
+ fs.closeSync(fd);
2731
2854
  }
2855
+ fs.renameSync(tmp, filePath);
2732
2856
  }
2733
2857
 
2734
2858
  _readFile(filePath) {
package/lib/date-types.js CHANGED
@@ -268,8 +268,8 @@ function validateTimestamp(value, fieldName) {
268
268
  return Math.floor(value.getTime() / 1000);
269
269
  }
270
270
  if (typeof value === 'number') {
271
- // 自动检测毫秒时间戳
272
- if (value > 1e12) return Math.floor(value / 1000);
271
+ // 自动检测毫秒时间戳(#168:恰好 1e12 也属于毫秒)
272
+ if (value >= 1e12) return Math.floor(value / 1000);
273
273
  return value;
274
274
  }
275
275
  if (typeof value === 'string') {
@@ -283,7 +283,7 @@ function validateTimestamp(value, fieldName) {
283
283
  }
284
284
  const n = parseInt(value, 10);
285
285
  if (!isNaN(n)) {
286
- if (n > 1e12) return Math.floor(n / 1000);
286
+ if (n >= 1e12) return Math.floor(n / 1000);
287
287
  return n;
288
288
  }
289
289
  }
@@ -330,7 +330,7 @@ function now(type = 'datetime') {
330
330
  }
331
331
 
332
332
  function formatDate(value, format = 'YYYY-MM-DD') {
333
- if (!value) return value;
333
+ if (value === null || value === undefined || value === '') return value;
334
334
  let d;
335
335
  if (value instanceof Date) d = value;
336
336
  else {
package/lib/errors.js CHANGED
@@ -56,6 +56,10 @@ const ErrorCodes = {
56
56
  ER_NO_TRANSACTION: { code: 1569, msg: "No transaction in progress" },
57
57
  // 保存点不存在(MySQL 用这个码:SAVEPOINT xxx does not exist)
58
58
  ER_SP_DOES_NOT_EXIST: { code: 1305, msg: "SAVEPOINT %s does not exist" },
59
+ ER_FUNCTION_NOT_EXIST: { code: 1305, msg: "FUNCTION %s does not exist" },
60
+ ER_WRONG_VALUE_COUNT_ON_ROW: { code: 1136, msg: "Column count doesn't match value count at row %s" },
61
+ ER_TRUNCATE_ILLEGAL_FK: { code: 1701, msg: "Cannot truncate a table referenced in a foreign key constraint (%s)" },
62
+ ER_ROW_IS_REFERENCED_2: { code: 1451, msg: "Cannot delete or update a parent row: a foreign key constraint fails (%s)" },
59
63
 
60
64
  // 其他
61
65
  ER_NOT_SUPPORTED: { code: 1235, msg: "This version doesn't yet support '%s'" },
package/lib/migrate.js CHANGED
@@ -11,6 +11,7 @@ const fs = require('fs');
11
11
  const path = require('path');
12
12
  const { splitStatements, executeSQL } = require('./sql');
13
13
  const { parseFieldShorthand } = require('./database');
14
+ const bigintJson = require('./bigint_json');
14
15
 
15
16
  // 体积护栏(CWE-770):与 lib/sql.js 的 DEFAULT_MAX_SQL_LENGTH 同风格。
16
17
  // 可用 opts.maxInputSize / opts.maxRows 覆盖;传 Infinity 关闭;chunkSize 控制每批 insert 行数。
@@ -38,17 +39,28 @@ function normalizeSchema(schema) {
38
39
  }
39
40
 
40
41
  function serializeValue(v) {
41
- if (v === null || v === undefined) return '';
42
+ // #235:NULL 与空串必须可区分(MySQL 约定 NULL 写 \N)
43
+ if (v === null || v === undefined) return '\\N';
42
44
  if (v instanceof Date) return v.toISOString();
43
45
  if (typeof v === 'object') return JSON.stringify(v);
44
46
  return String(v);
45
47
  }
46
48
 
47
49
  function parseValue(str, type) {
48
- if (str === '' || str === null || str === undefined) return null;
50
+ if (str === '\\N') return null; // #235:显式 NULL 标记
51
+ if (str === null || str === undefined) return null;
49
52
  const t = String(type || 'string').toLowerCase();
50
- if (t === 'integer') return Number.isFinite(Number(str)) ? Math.trunc(Number(str)) : str;
51
- if (t === 'float' || t === 'number') return Number.isFinite(Number(str)) ? Number(str) : str;
53
+ if (str === '') return (t === 'string' || t === 'text' || t === 'varchar' || t === 'char') ? '' : null;
54
+ if (t === 'integer' || t === 'int' || t === 'bigint') {
55
+ const s = str.trim();
56
+ if (!/^[-+]?\d+$/.test(s)) return str;
57
+ try {
58
+ const b = BigInt(s);
59
+ // #235:>2^53 用 BigInt 精确保留,不能先过 Number
60
+ return (b >= BigInt(Number.MIN_SAFE_INTEGER) && b <= BigInt(Number.MAX_SAFE_INTEGER)) ? Number(b) : b;
61
+ } catch (e) { return str; }
62
+ }
63
+ if (t === 'float' || t === 'number' || t === 'numeric' || t === 'decimal') return Number.isFinite(Number(str)) ? Number(str) : str;
52
64
  if (t === 'boolean') {
53
65
  const s = str.toLowerCase();
54
66
  if (['1', 'true', 'yes', 'y'].includes(s)) return true;
@@ -217,7 +229,7 @@ async function importFromJSON(engine, data, opts = {}) {
217
229
  `(raise opts.maxInputSize to allow larger input)`
218
230
  );
219
231
  }
220
- try { tables = JSON.parse(data); }
232
+ try { tables = bigintJson.parse(data); }
221
233
  catch (e) {
222
234
  throw new Error(`importFromJSON: invalid JSON: ${e.message}`);
223
235
  }
@@ -378,15 +390,15 @@ async function exportToFile(engine, table, filePath, opts = {}) {
378
390
  try {
379
391
  if (ext === '.json') {
380
392
  await write(
381
- '{\n "table": ' + JSON.stringify(table) +
382
- ',\n "schema": ' + JSON.stringify(schema, null, 2) +
393
+ '{\n "table": ' + bigintJson.stringify(table) +
394
+ ',\n "schema": ' + bigintJson.stringify(schema, 2) +
383
395
  ',\n "rows": [\n'
384
396
  );
385
397
  let first = true;
386
398
  await iterateTable(engine, table, opts, async (rows) => {
387
399
  let buf = '';
388
400
  for (const row of rows) {
389
- buf += (first ? ' ' : ',\n ') + JSON.stringify(row);
401
+ buf += (first ? ' ' : ',\n ') + bigintJson.stringify(row);
390
402
  first = false;
391
403
  }
392
404
  await write(buf);