jsql-neo 6.5.17 → 6.5.22
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 +4 -4
- package/bin/jsql +9 -2
- package/bin/yaggs-fallback.js +108 -0
- package/index.js +4 -1
- package/lib/btree.js +148 -62
- package/lib/compat/v1.js +208 -0
- package/lib/database.js +38 -17
- package/lib/errors.js +16 -4
- package/lib/migrate.js +2 -6
- package/lib/mongo_server.js +3 -20
- package/lib/mysql_compat.js +1 -1
- package/lib/mysql_server.js +24 -13
- package/lib/native_client.js +60 -10
- package/lib/nedb_compat.js +2 -15
- package/lib/pg_server.js +6 -5
- package/lib/plugin.js +3 -14
- package/lib/query.js +7 -4
- package/lib/sql.js +362 -171
- package/lib/sqlite_worker.js +0 -3
- package/lib/star-nag.js +9 -20
- package/lib/table.js +42 -46
- package/lib/tui.js +28 -6
- package/lib/wasm_client.js +66 -12
- package/lib/web_ui.js +6 -10
- package/lib/xql/index.js +0 -0
- package/lib/xql/src/compiler.js +130 -36
- package/lib/xql/src/jsql.js +1 -1
- package/lib/xql/src/tokenizer.js +10 -2
- package/native/jsql-neo-native.node +0 -0
- package/nativesrc/jsql-neo-core/src/engine/hybrid.rs +15 -4
- package/nativesrc/jsql-neo-core/src/engine/memory.rs +1 -1
- package/nativesrc/jsql-neo-core/src/engine/table.rs +93 -10
- package/nativesrc/jsql-neo-wasm/src/lib.rs +39 -14
- package/package.json +10 -5
- package/postinstall.js +42 -18
- package/test/btree.test.js +3 -53
- package/test/bug-regression-2.test.js +299 -0
- package/test/cli-fallback.test.js +55 -0
- package/test/compat-v1.test.js +220 -0
- package/test/coverage.js +3 -3
- package/test/extra-coverage.test.js +4 -2
- package/test/issue-34-35-36.test.js +142 -0
- package/test/issue-39.test.js +160 -0
- package/test/issue-40.test.js +264 -0
- package/test/issue-g4.test.js +82 -0
- package/test/native-add-column.test.js +74 -0
- package/test/native-dup-pk.test.js +114 -0
- package/test/sql-parser.test.js +9 -1
- package/test/sql-tokenizer-literals.test.js +60 -0
- package/wasm/browser.mjs +19 -1
- package/wasm/browser_bg.mjs +150 -97
- package/wasm/jsql_neo_wasm.d.ts +5 -0
- package/wasm/jsql_neo_wasm.js +28 -0
- package/wasm/jsql_neo_wasm_bg.wasm +0 -0
- package/wasm/jsql_neo_wasm_bg.wasm.d.ts +1 -0
- package/nativesrc/jsql-neo-native/jsql-neo-native.node +0 -0
- package/test/v6.5.14-regression.test.js +0 -349
package/lib/database.js
CHANGED
|
@@ -1344,11 +1344,15 @@ class Database {
|
|
|
1344
1344
|
startedAt: Date.now()
|
|
1345
1345
|
};
|
|
1346
1346
|
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1347
|
+
if (level === 'REPEATABLE_READ') {
|
|
1348
|
+
// 快照:保存当前所有数据(深拷贝,保证嵌套对象可回滚)
|
|
1349
|
+
this._transaction.snapshot = this._captureTxSnapshot();
|
|
1350
|
+
} else {
|
|
1351
|
+
// READ_COMMITTED:只保存 autoIncrement
|
|
1352
|
+
for (const [name, table] of Object.entries(this._tables)) {
|
|
1353
|
+
this._transaction.autoIncrements[name] = table._autoIncrement;
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1352
1356
|
|
|
1353
1357
|
this._savepointStack = [];
|
|
1354
1358
|
this._walWrite({ op: 'begin', level });
|
|
@@ -1370,6 +1374,12 @@ class Database {
|
|
|
1370
1374
|
|
|
1371
1375
|
if (this._transaction.snapshot) {
|
|
1372
1376
|
this._restoreTxSnapshot(this._transaction.snapshot);
|
|
1377
|
+
} else {
|
|
1378
|
+
// READ_COMMITTED:没有行快照,只能退回自增值
|
|
1379
|
+
for (const [name, table] of Object.entries(this._tables)) {
|
|
1380
|
+
const v = this._transaction.autoIncrements[name];
|
|
1381
|
+
if (v !== undefined) table._autoIncrement = v;
|
|
1382
|
+
}
|
|
1373
1383
|
}
|
|
1374
1384
|
|
|
1375
1385
|
this._walWrite({ op: 'rollback', at: this._transaction.startedAt });
|
|
@@ -1847,8 +1857,8 @@ class Database {
|
|
|
1847
1857
|
let rows = table._applyFilterOptimized(table._getVisibleRows(), filter || {});
|
|
1848
1858
|
if (limit > 0) rows = rows.slice(offset, offset + limit);
|
|
1849
1859
|
else if (offset > 0) rows = rows.slice(offset);
|
|
1850
|
-
// P1-11:
|
|
1851
|
-
rows = rows.map(r =>
|
|
1860
|
+
// P1-11: 返回浅拷贝,防止调用方修改影响内部数据
|
|
1861
|
+
rows = rows.map(r => ({ ...r }));
|
|
1852
1862
|
this._touchTable(tableName);
|
|
1853
1863
|
await this._runHooks('afterFind', [tableName, { filter, opts }, rows]);
|
|
1854
1864
|
return rows;
|
|
@@ -1880,8 +1890,8 @@ class Database {
|
|
|
1880
1890
|
const row = this._resolveId(table, id);
|
|
1881
1891
|
// P1-4: 软删除行对普通读取不可见
|
|
1882
1892
|
if (row && row._deleted) return null;
|
|
1883
|
-
// P1-11:
|
|
1884
|
-
const result = row ?
|
|
1893
|
+
// P1-11: 返回浅拷贝,防止调用方修改影响内部数据
|
|
1894
|
+
const result = row ? { ...row } : null;
|
|
1885
1895
|
this._touchTable(tableName);
|
|
1886
1896
|
await this._runHooks('afterFind', [tableName, { id }, result]);
|
|
1887
1897
|
return result;
|
|
@@ -1892,7 +1902,7 @@ class Database {
|
|
|
1892
1902
|
if (!table) throw createError('ER_NO_SUCH_TABLE', tableName);
|
|
1893
1903
|
if (!(await this._runHooks('beforeFind', [tableName, { ids }]))) return null;
|
|
1894
1904
|
// P1-4: 过滤掉软删除行;P1-11: 返回浅拷贝
|
|
1895
|
-
const rows = ids.map(id => this._resolveId(table, id)).filter(r => r !== null && !r._deleted).map(r =>
|
|
1905
|
+
const rows = ids.map(id => this._resolveId(table, id)).filter(r => r !== null && !r._deleted).map(r => ({ ...r }));
|
|
1896
1906
|
this._touchTable(tableName);
|
|
1897
1907
|
await this._runHooks('afterFind', [tableName, { ids }, rows]);
|
|
1898
1908
|
return rows;
|
|
@@ -1938,10 +1948,23 @@ class Database {
|
|
|
1938
1948
|
const clash = table._rows.find(r => r !== row && r[field] === nv);
|
|
1939
1949
|
if (clash) throw createError('ER_DUP_ENTRY', `Duplicate entry '${nv}' for key '${field}'`);
|
|
1940
1950
|
}
|
|
1941
|
-
//
|
|
1942
|
-
//
|
|
1943
|
-
|
|
1944
|
-
Object.
|
|
1951
|
+
// 外键:改主键时按 ON UPDATE 传播到引用它的子表;改自身外键列时校验引用存在。
|
|
1952
|
+
// 此前这里直接 Object.assign 绕过 Table.updateById,ON UPDATE CASCADE / RESTRICT
|
|
1953
|
+
// 与 FK 校验全部失效(外键形同虚设)。
|
|
1954
|
+
if (pk && Object.prototype.hasOwnProperty.call(validated, pk) && validated[pk] !== row[pk]) {
|
|
1955
|
+
table._propagatePKUpdate(row[pk], validated[pk]);
|
|
1956
|
+
}
|
|
1957
|
+
if (table._foreignKeys && table._foreignKeys.length) {
|
|
1958
|
+
table._validateForeignKeys({ ...row, ...validated });
|
|
1959
|
+
}
|
|
1960
|
+
// 改主键/唯一值时索引必须同步:否则 _pkIndex 还指向旧值,
|
|
1961
|
+
// 后续 FK 校验 findOne({id:新值}) 查不到刚更新的父行。
|
|
1962
|
+
{
|
|
1963
|
+
const rowIndex = table._rows.indexOf(row);
|
|
1964
|
+
if (rowIndex !== -1) table._removeFromIndexes(rowIndex, row);
|
|
1965
|
+
Object.assign(row, validated);
|
|
1966
|
+
if (rowIndex !== -1) table._addToIndexes(rowIndex, row);
|
|
1967
|
+
}
|
|
1945
1968
|
if (pk) this._walWrite({ op: 'update', table: tableName, pk, id, row: { ...validated } });
|
|
1946
1969
|
this._emit('update', { table: tableName, id, data: validated });
|
|
1947
1970
|
await this._runHooks('afterUpdate', [tableName, id, validated, { ok: true }]);
|
|
@@ -1959,9 +1982,7 @@ class Database {
|
|
|
1959
1982
|
for (const [id, data] of pairs) {
|
|
1960
1983
|
const row = this._resolveId(table, id);
|
|
1961
1984
|
if (row) {
|
|
1962
|
-
|
|
1963
|
-
table._validateConstraints({ ...row, ...validated }, table._rows.indexOf(row));
|
|
1964
|
-
Object.assign(row, validated);
|
|
1985
|
+
Object.assign(row, data);
|
|
1965
1986
|
count++;
|
|
1966
1987
|
if (pk) this._walWrite({ op: 'update', table: tableName, pk, id, row: { ...data } });
|
|
1967
1988
|
}
|
package/lib/errors.js
CHANGED
|
@@ -81,10 +81,22 @@ function createError(codeKey, ...args) {
|
|
|
81
81
|
return new JSQL_Error('UNKNOWN', `Unknown error: ${codeKey}`, { codeKey, args });
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
-
//
|
|
85
|
-
//
|
|
86
|
-
|
|
87
|
-
|
|
84
|
+
// 单次扫描替换:占位符按模板顺序消费,参数内容原样写入。
|
|
85
|
+
//
|
|
86
|
+
// 旧实现是 `for (args) msg = msg.replace('%s', () => String(arg))`,
|
|
87
|
+
// 每一轮都在**上一轮的结果**上再找第一个 '%s' —— 参数里自带的 '%s'
|
|
88
|
+
// 会被当成下一个占位符吃掉,且顺序错位:
|
|
89
|
+
// createError('ER_BAD_FIELD_ERROR', 'X%sY', 'Z')
|
|
90
|
+
// → "Unknown column 'XZY' in '%s'"(X%sY 被改写成 XZY)
|
|
91
|
+
// 正确结果是 "Unknown column 'X%sY' in 'Z'"。
|
|
92
|
+
let i = 0;
|
|
93
|
+
let msg = template.msg.replace(/%s/g, () => (i < args.length ? String(args[i++]) : '%s'));
|
|
94
|
+
if (args.length > 0 && !/%s/.test(template.msg)) {
|
|
95
|
+
// 模板里没有占位符(如 ER_NO_TRANSACTION)时,参数不能被静默丢弃:
|
|
96
|
+
// 追加在后面,至少保留调用方给出的上下文。
|
|
97
|
+
const rest = args.map(a => String(a)).join(' ');
|
|
98
|
+
msg = rest ? `${msg} (${rest})` : msg;
|
|
99
|
+
}
|
|
88
100
|
|
|
89
101
|
return new JSQL_Error(template.code, msg, { args });
|
|
90
102
|
}
|
package/lib/migrate.js
CHANGED
|
@@ -30,12 +30,8 @@ function normalizeSchema(schema) {
|
|
|
30
30
|
if (d.type === 'varchar' || d.type === 'text' || d.type === 'char') d.type = 'string';
|
|
31
31
|
if (d.type === 'double' || d.type === 'real' || d.type === 'decimal' || d.type === 'numeric') d.type = 'float';
|
|
32
32
|
if (d.type === 'bool') d.type = 'boolean';
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
if (d.maxLength !== undefined) {
|
|
36
|
-
if (d.length === undefined) d.length = d.maxLength;
|
|
37
|
-
delete d.maxLength;
|
|
38
|
-
}
|
|
33
|
+
delete d.length;
|
|
34
|
+
if (d.maxLength) { d.length = d.maxLength; delete d.maxLength; }
|
|
39
35
|
out[name] = d;
|
|
40
36
|
}
|
|
41
37
|
return out;
|
package/lib/mongo_server.js
CHANGED
|
@@ -461,7 +461,7 @@ class MongoServer {
|
|
|
461
461
|
await engine.insert(coll, merged);
|
|
462
462
|
value = doc.new ? { ...merged } : null;
|
|
463
463
|
}
|
|
464
|
-
return { ok: 1, value
|
|
464
|
+
return { ok: 1, value, lastErrorObject: { n: found ? 1 : (doc.upsert ? 1 : 0), updatedExisting: !!found && !doc.remove } };
|
|
465
465
|
}
|
|
466
466
|
case 'distinct': {
|
|
467
467
|
const coll = String(doc.distinct);
|
|
@@ -496,7 +496,7 @@ class MongoServer {
|
|
|
496
496
|
if (skip > 0) rows = rows.slice(skip);
|
|
497
497
|
const limit = typeof doc.limit === 'number' ? doc.limit : 0;
|
|
498
498
|
if (limit > 0) rows = rows.slice(0, limit);
|
|
499
|
-
return { ok: 1, cursor: { id: { $long: 0 }, ns: `${this._dbOf(doc)}.${coll}`, firstBatch: rows
|
|
499
|
+
return { ok: 1, cursor: { id: { $long: 0 }, ns: `${this._dbOf(doc)}.${coll}`, firstBatch: rows } };
|
|
500
500
|
}
|
|
501
501
|
case 'getMore':
|
|
502
502
|
return { ok: 1, cursor: { id: { $long: 0 }, ns: String(doc.collection || ''), nextBatch: [] } };
|
|
@@ -673,7 +673,7 @@ class MongoServer {
|
|
|
673
673
|
rows = out;
|
|
674
674
|
}
|
|
675
675
|
}
|
|
676
|
-
return { ok: 1, cursor: { id: { $long: 0 }, ns: `${this._dbOf(doc)}.${coll}`, firstBatch: rows
|
|
676
|
+
return { ok: 1, cursor: { id: { $long: 0 }, ns: `${this._dbOf(doc)}.${coll}`, firstBatch: rows } };
|
|
677
677
|
}
|
|
678
678
|
default:
|
|
679
679
|
return { ok: 1, n: 0 };
|
|
@@ -684,23 +684,6 @@ class MongoServer {
|
|
|
684
684
|
return row._id != null ? row._id : row.id;
|
|
685
685
|
}
|
|
686
686
|
|
|
687
|
-
/**
|
|
688
|
-
* 剥离 JSQL 内部字段后再返回给 Mongo 客户端。
|
|
689
|
-
*
|
|
690
|
-
* _deleted(软删除标记)、_rid(内部行号)、_score(全文检索得分)
|
|
691
|
-
* 都只属于引擎内部实现,泄漏到文档里会污染用户数据、影响后续 $set/$unset
|
|
692
|
-
* 以及客户端 schema 推断。
|
|
693
|
-
*/
|
|
694
|
-
_publicDoc(row) {
|
|
695
|
-
if (!row || typeof row !== 'object') return row;
|
|
696
|
-
if (row._deleted === undefined && row._rid === undefined && row._score === undefined) return row;
|
|
697
|
-
const out = { ...row };
|
|
698
|
-
delete out._deleted;
|
|
699
|
-
delete out._rid;
|
|
700
|
-
delete out._score;
|
|
701
|
-
return out;
|
|
702
|
-
}
|
|
703
|
-
|
|
704
687
|
async _matching(engine, coll, filter) {
|
|
705
688
|
const rows = await engine.find(coll, {});
|
|
706
689
|
return rows.filter((r) => this._match(r, filter || {}));
|
package/lib/mysql_compat.js
CHANGED
|
@@ -146,8 +146,8 @@ class Connection extends EventEmitter {
|
|
|
146
146
|
const r = await executeSQL(engine, finalSql, {
|
|
147
147
|
safety: this.safety,
|
|
148
148
|
allowComments: this.allowComments,
|
|
149
|
-
allowWrites: true,
|
|
150
149
|
maxStatements: this.config.multipleStatements ? null : 1,
|
|
150
|
+
allowStacked: this.config.multipleStatements === true,
|
|
151
151
|
});
|
|
152
152
|
const results = Array.isArray(r) ? r : [r];
|
|
153
153
|
const last = results[results.length - 1];
|
package/lib/mysql_server.js
CHANGED
|
@@ -281,7 +281,8 @@ function columnDefinition(column) {
|
|
|
281
281
|
|
|
282
282
|
function columnTypeFromSchema(def) {
|
|
283
283
|
const type = def && def.type ? String(def.type).toLowerCase() : 'string';
|
|
284
|
-
if (type === 'integer' || type === 'int'
|
|
284
|
+
if (type === 'integer' || type === 'int') return MYSQL_TYPE_LONG;
|
|
285
|
+
if (type === 'bigint') return MYSQL_TYPE_LONGLONG;
|
|
285
286
|
if (type === 'number' || type === 'float' || type === 'double' || type === 'real') return MYSQL_TYPE_DOUBLE;
|
|
286
287
|
if (type === 'boolean' || type === 'bool') return MYSQL_TYPE_TINY;
|
|
287
288
|
if (type === 'date') return MYSQL_TYPE_DATE;
|
|
@@ -394,15 +395,26 @@ function binaryResultSetPacket(result, tableSchema, baseSeq) {
|
|
|
394
395
|
if (v === null || v === undefined) return null;
|
|
395
396
|
if (type === MYSQL_TYPE_LONG || type === MYSQL_TYPE_LONGLONG || type === MYSQL_TYPE_DOUBLE) {
|
|
396
397
|
const num = Number(v);
|
|
398
|
+
if (!Number.isFinite(num)) return encodeLenencString(String(v));
|
|
397
399
|
if (type === MYSQL_TYPE_DOUBLE) {
|
|
398
|
-
if (!Number.isFinite(num)) return encodeLenencString(String(v));
|
|
399
400
|
const b = Buffer.alloc(8); b.writeDoubleLE(num, 0); return b;
|
|
400
401
|
}
|
|
401
|
-
if (Number.isInteger(num) && num <= 2147483647 && num >= -2147483648) {
|
|
402
|
-
const b = Buffer.alloc(4); b.writeInt32LE(num, 0); return b;
|
|
403
|
-
}
|
|
404
402
|
if (!Number.isFinite(num)) return encodeLenencString(String(v));
|
|
405
|
-
|
|
403
|
+
if (type === MYSQL_TYPE_LONG) {
|
|
404
|
+
// 4 字节 LONG:总是写 4 字节(#32)。超出 int32 范围时钳位,
|
|
405
|
+
// 不能写 8 字节,否则二进制结果集的行布局被破坏(下一列错位)。
|
|
406
|
+
let n = Math.trunc(num);
|
|
407
|
+
if (n > 2147483647) n = 2147483647;
|
|
408
|
+
if (n < -2147483648) n = -2147483648;
|
|
409
|
+
const b = Buffer.alloc(4); b.writeInt32LE(n, 0); return b;
|
|
410
|
+
}
|
|
411
|
+
// MYSQL_TYPE_LONGLONG:始终写 8 字节,超出 int64 范围时钳位(保持行布局)。
|
|
412
|
+
let bi = BigInt(Math.trunc(num));
|
|
413
|
+
const INT64_MAX = 9223372036854775807n;
|
|
414
|
+
const INT64_MIN = -9223372036854775808n;
|
|
415
|
+
if (bi > INT64_MAX) bi = INT64_MAX;
|
|
416
|
+
if (bi < INT64_MIN) bi = INT64_MIN;
|
|
417
|
+
const b = Buffer.alloc(8); b.writeBigInt64LE(bi, 0); return b;
|
|
406
418
|
}
|
|
407
419
|
if (type === MYSQL_TYPE_TINY) {
|
|
408
420
|
const b = Buffer.alloc(1); b.writeInt8(v ? 1 : 0, 0); return b;
|
|
@@ -578,9 +590,8 @@ class MysqlConnection {
|
|
|
578
590
|
case 0x19: this._handleStmtClose(body); break; // COM_STMT_CLOSE
|
|
579
591
|
case 0x1a: this._send(okPacket()); break; // COM_STMT_RESET
|
|
580
592
|
case 0x0a: { // COM_PROCESS_INFO
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
// 严格校验序列号的客户端会判定协议错误并断开。
|
|
593
|
+
const seq = this.sequence;
|
|
594
|
+
this.sequence = (this.sequence + 1) & 0xff;
|
|
584
595
|
this._send(encodeLenenc(1));
|
|
585
596
|
this._send(columnDefinition({ name: 'Id', type: MYSQL_TYPE_LONG }));
|
|
586
597
|
this._send(eofPacket());
|
|
@@ -957,8 +968,6 @@ class MysqlConnection {
|
|
|
957
968
|
const r = await executeSQL(engine, sqlToRun, {
|
|
958
969
|
allowComments: this.server.allowComments,
|
|
959
970
|
safety: this.server.safety,
|
|
960
|
-
// 协议服务器本身就是数据库端:客户端发来的 DROP/DELETE/UPDATE 必须执行。
|
|
961
|
-
allowWrites: true,
|
|
962
971
|
maxStatements: 1,
|
|
963
972
|
session: this.session,
|
|
964
973
|
});
|
|
@@ -1105,8 +1114,10 @@ class MysqlServer {
|
|
|
1105
1114
|
if (t && t.indexOf('.') !== -1) {
|
|
1106
1115
|
const re = new RegExp('\\b' + t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\b', 'g');
|
|
1107
1116
|
s = s.replace(re, (match, offset) => {
|
|
1108
|
-
//
|
|
1109
|
-
|
|
1117
|
+
// 如果匹配位置在字符串字面量或注释中,不替换。
|
|
1118
|
+
// _maskStringsAndComments 把字符串/注释内的字符置为空格,
|
|
1119
|
+
// 因此 masked[offset] === ' ' 表示该位置在字面量/注释里(#31)。
|
|
1120
|
+
if (masked[offset] === ' ') return match;
|
|
1110
1121
|
return t.split('.')[1];
|
|
1111
1122
|
});
|
|
1112
1123
|
}
|
package/lib/native_client.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const path = require('path');
|
|
2
2
|
const os = require('os');
|
|
3
3
|
const { executeSQL } = require('./sql');
|
|
4
|
+
const { JSQL_Error, ErrorCodes } = require('./errors');
|
|
4
5
|
const {
|
|
5
6
|
createHookRegistry, applyPlugin, buildPluginContext, registerHook,
|
|
6
7
|
runHooks, getPluginApis
|
|
@@ -56,6 +57,19 @@ function _trackInstance(inst) {
|
|
|
56
57
|
}
|
|
57
58
|
|
|
58
59
|
const INT64_TAG = 1;
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 把可能是字符串/数字的 limit / offset / id 规范成非负整数,供原生 usize/u64 使用。
|
|
63
|
+
* 负值(或 NaN/Infinity)会在绑定层直接抛错,而不是让 Rust 侧 debug panic 或
|
|
64
|
+
* release 静默空结果(#35)。返回 Math.trunc(n)(对非负浮点向下取整,与 usize 语义一致)。
|
|
65
|
+
*/
|
|
66
|
+
function toNonNeg(name, v, def) {
|
|
67
|
+
if (v === undefined || v === null) return def;
|
|
68
|
+
const n = Number(v);
|
|
69
|
+
if (!Number.isFinite(n)) throw new Error(`jsql-neo: ${name} must be a finite number, got ${v}`);
|
|
70
|
+
if (n < 0) throw new Error(`jsql-neo: ${name} must be non-negative, got ${v}`);
|
|
71
|
+
return Math.trunc(n);
|
|
72
|
+
}
|
|
59
73
|
const FLOAT_TAG = 2;
|
|
60
74
|
const STR_TAG = 3;
|
|
61
75
|
const BOOL_TAG = 4;
|
|
@@ -66,6 +80,25 @@ function safeParse(str, fallback) {
|
|
|
66
80
|
try { return JSON.parse(str); } catch (e) { return fallback; }
|
|
67
81
|
}
|
|
68
82
|
|
|
83
|
+
/**
|
|
84
|
+
* 把原生层返回的 `"ER_XXX: message"` 还原成纯 JS 引擎同样的异常:
|
|
85
|
+
* JSQL_Error、message 一致、code 为 MySQL 错误码(1062)、并带上 codeKey/errno。
|
|
86
|
+
* 没有错误码前缀的消息原样透传,普通错误行为不变。
|
|
87
|
+
*/
|
|
88
|
+
function nativeError(raw, fallback) {
|
|
89
|
+
const text = String(raw || fallback || 'native error');
|
|
90
|
+
const m = /^(ER_[A-Z0-9_]+):\s*([\s\S]*)$/.exec(text);
|
|
91
|
+
if (!m) return new Error(text);
|
|
92
|
+
const codeKey = m[1];
|
|
93
|
+
const t = ErrorCodes[codeKey];
|
|
94
|
+
const e = new JSQL_Error(t ? t.code : codeKey, m[2] || text, { codeKey });
|
|
95
|
+
e.codeKey = codeKey;
|
|
96
|
+
if (t) e.errno = t.code;
|
|
97
|
+
return e;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function throwNative(raw, fallback) { throw nativeError(raw, fallback); }
|
|
101
|
+
|
|
69
102
|
/**
|
|
70
103
|
* 深度相等比较两个行对象(用于无主键表行匹配)。
|
|
71
104
|
* 剥离内部字段(_rid, _deleted)后逐字段比较。
|
|
@@ -519,7 +552,7 @@ class JSQL {
|
|
|
519
552
|
if (!schema || !pk) return id;
|
|
520
553
|
const def = schema[pk];
|
|
521
554
|
let t = null;
|
|
522
|
-
if (typeof def === 'string') t = def.toLowerCase();
|
|
555
|
+
if (typeof def === 'string') t = def.trim().split(/\s+/)[0].toLowerCase();
|
|
523
556
|
else if (def && typeof def === 'object' && def.type) t = String(def.type).toLowerCase();
|
|
524
557
|
if (['integer', 'int', 'bigint'].includes(t)) return Number(id);
|
|
525
558
|
return id;
|
|
@@ -532,8 +565,11 @@ class JSQL {
|
|
|
532
565
|
_isAutoIntPk(table) {
|
|
533
566
|
if (!this._pkAutoIncrement(table)) return false;
|
|
534
567
|
const def = this._schemas[table][this._pkOf(table)];
|
|
535
|
-
|
|
536
|
-
|
|
568
|
+
// 简写字符串 schema(如 'integer primary key auto_increment')取首个 token 作为类型;
|
|
569
|
+
// 对象 schema 直接读 def.type。二者都必须精确匹配整数类型,否则负 id 校验不生效(issue #35)。
|
|
570
|
+
let t = '';
|
|
571
|
+
if (typeof def === 'string') t = def.trim().split(/\s+/)[0].toLowerCase();
|
|
572
|
+
else if (def && def.type) t = String(def.type).toLowerCase();
|
|
537
573
|
return ['integer', 'int', 'bigint'].includes(t);
|
|
538
574
|
}
|
|
539
575
|
|
|
@@ -541,8 +577,11 @@ class JSQL {
|
|
|
541
577
|
const pk = this._pkOf(table);
|
|
542
578
|
if (pk) {
|
|
543
579
|
if (this._isAutoIntPk(table)) {
|
|
544
|
-
const n =
|
|
580
|
+
const n = toNonNeg('id', id, NaN);
|
|
545
581
|
if (Number.isFinite(n)) {
|
|
582
|
+
// 负 id 会被原生层 `i64 -> u64` 静默回绕成 usize::MAX,导致
|
|
583
|
+
// findById 误报 not found(行明明存在却取不到)。在此显式拒绝。
|
|
584
|
+
if (n < 0) throw new Error('id must be a non-negative number');
|
|
546
585
|
const r = safeParse(this._n('jsqlFindById', table, n));
|
|
547
586
|
if (r && r.error) return r;
|
|
548
587
|
return r || null;
|
|
@@ -554,15 +593,18 @@ class JSQL {
|
|
|
554
593
|
if (r && r.error) return r;
|
|
555
594
|
return Array.isArray(r) && r.length > 0 ? r[0] : null;
|
|
556
595
|
}
|
|
557
|
-
return safeParse(this._n('jsqlFindById', table,
|
|
596
|
+
return safeParse(this._n('jsqlFindById', table, toNonNeg('id', id, NaN)));
|
|
558
597
|
}
|
|
559
598
|
|
|
560
599
|
_seqIdByPk(table, id) {
|
|
561
600
|
const pk = this._pkOf(table);
|
|
562
601
|
if (pk) {
|
|
563
602
|
if (this._isAutoIntPk(table)) {
|
|
564
|
-
const n =
|
|
603
|
+
const n = toNonNeg('id', id, NaN);
|
|
565
604
|
if (Number.isFinite(n)) {
|
|
605
|
+
// 负 id 在原生层回绕为 usize::MAX 后静默 not found,update/remove
|
|
606
|
+
// 会无提示地什么都不做 —— 这里显式拒绝(见 issue #35)。
|
|
607
|
+
if (n < 0) throw new Error('id must be a non-negative number');
|
|
566
608
|
const r = safeParse(this._n('jsqlFindById', table, n));
|
|
567
609
|
if (r && !r.error && r.id !== undefined) return r.id;
|
|
568
610
|
}
|
|
@@ -628,7 +670,7 @@ class JSQL {
|
|
|
628
670
|
} else {
|
|
629
671
|
r = safeParse(this._n('jsqlInsertBuf', table, encodeBatch(rows)));
|
|
630
672
|
}
|
|
631
|
-
if (r && r.error)
|
|
673
|
+
if (r && r.error) throwNative(r.error);
|
|
632
674
|
if (r && Array.isArray(r) && !this._pkAutoIncrement(table)) {
|
|
633
675
|
const pk = this._pkOf(table);
|
|
634
676
|
if (pk) {
|
|
@@ -734,7 +776,7 @@ class JSQL {
|
|
|
734
776
|
for (let i = 0; i < arr.length; i += this._flushThreshold) {
|
|
735
777
|
const chunk = arr.slice(i, i + this._flushThreshold);
|
|
736
778
|
const r = await this._insertBatch(table, chunk);
|
|
737
|
-
if (r && r.error)
|
|
779
|
+
if (r && r.error) throwNative(r.error);
|
|
738
780
|
if (!result) result = r;
|
|
739
781
|
}
|
|
740
782
|
this._emit('insert', { table, count: arr.length, ids: result });
|
|
@@ -804,7 +846,10 @@ class JSQL {
|
|
|
804
846
|
let r;
|
|
805
847
|
if (this._isAutoIntPk(table) && ids.every(id => Number.isFinite(Number(id)))) {
|
|
806
848
|
// 自增主键:内部 id 即主键值,一次批量调用即可,避免 N 次往返。
|
|
807
|
-
|
|
849
|
+
// #35:负 id 在原生层 `i64 -> u64` 回绕成 usize::MAX,静默 not found;
|
|
850
|
+
// NaN/Infinity 同样不允许。绑定层先校验,绝不把非法值传给原生模块。
|
|
851
|
+
const nums = ids.map(id => toNonNeg('id', id, 0));
|
|
852
|
+
r = safeParse(this._n('jsqlFindByIds', table, JSON.stringify(nums)));
|
|
808
853
|
} else if (this._pkOf(table)) {
|
|
809
854
|
r = ids.map(id => this._findRawById(table, id)).filter(x => x !== null && !(x && x.error));
|
|
810
855
|
} else {
|
|
@@ -826,7 +871,12 @@ class JSQL {
|
|
|
826
871
|
if (!(await this._runHooks('beforeFind', [table, { filter, opts }]))) return [];
|
|
827
872
|
const filterStr = filter ? JSON.stringify(filter) : '';
|
|
828
873
|
const { limit = 100, offset = 0 } = opts;
|
|
829
|
-
|
|
874
|
+
// #35:原生层把 limit/offset 按 `as usize` 无符号转换,负数会静默回绕
|
|
875
|
+
// (release 下空结果 / debug 下 usize::MAX+1 溢出 panic)。绑定层先校验,
|
|
876
|
+
// 与 WASM 端的 usize 签名保持一致,绝不把负值传给原生模块。
|
|
877
|
+
const lim = toNonNeg('limit', limit, 100);
|
|
878
|
+
const off = toNonNeg('offset', offset, 0);
|
|
879
|
+
const r = safeParse(this._n('jsqlFind', table, filterStr, lim, off));
|
|
830
880
|
if (r && r.error) throw new Error(r.error);
|
|
831
881
|
await this._runHooks('afterFind', [table, { filter, opts }, r]);
|
|
832
882
|
const schema = this._schemas[table];
|
package/lib/nedb_compat.js
CHANGED
|
@@ -77,21 +77,8 @@ function matchOperator(value, op, expected) {
|
|
|
77
77
|
case '$in': return Array.isArray(expected) && expected.some(e => looseEqual(value, e));
|
|
78
78
|
case '$nin': return Array.isArray(expected) && !expected.some(e => looseEqual(value, e));
|
|
79
79
|
case '$exists': return expected ? value !== undefined : value === undefined;
|
|
80
|
-
case '$regex':
|
|
81
|
-
|
|
82
|
-
// expected 允许两种写法:/re/flags(RegExp),或 MySQL 风格的字符串模式。
|
|
83
|
-
// 此前直接读 expected.source:字符串没有 source → new RegExp(undefined)
|
|
84
|
-
// 等价于 /(?:)/,静默匹配所有文档。
|
|
85
|
-
let re;
|
|
86
|
-
if (expected instanceof RegExp) {
|
|
87
|
-
re = expected;
|
|
88
|
-
} else if (typeof expected === 'string') {
|
|
89
|
-
try { re = new RegExp(expected); } catch { return false; }
|
|
90
|
-
} else {
|
|
91
|
-
return false;
|
|
92
|
-
}
|
|
93
|
-
return re.test(value);
|
|
94
|
-
}
|
|
80
|
+
case '$regex':
|
|
81
|
+
return typeof value === 'string' && new RegExp(expected.source, expected.flags || 'i').test(value);
|
|
95
82
|
case '$size': return Array.isArray(value) && value.length === expected;
|
|
96
83
|
default: return false;
|
|
97
84
|
}
|
package/lib/pg_server.js
CHANGED
|
@@ -711,7 +711,11 @@ class PgConnection {
|
|
|
711
711
|
const tag = `SELECT ${(res.rows || []).length}`;
|
|
712
712
|
this._send(buildCommandComplete(tag));
|
|
713
713
|
} else if (res.type === 'insert' || res.type === 'update' || res.type === 'delete') {
|
|
714
|
-
|
|
714
|
+
// PG CommandComplete tag:INSERT 是 "INSERT <oid> <count>",UPDATE/DELETE 是
|
|
715
|
+
// "UPDATE <count>" / "DELETE <count>"(#33)。缺了 OID 段会让客户端把 count
|
|
716
|
+
// 解析到 OID 槽位、rowCount 变 NaN。
|
|
717
|
+
const count = res.affectedRows != null ? res.affectedRows : 0;
|
|
718
|
+
const tag = res.type === 'insert' ? `INSERT 0 ${count}` : `${String(res.type).toUpperCase()} ${count}`;
|
|
715
719
|
this._send(buildCommandComplete(tag));
|
|
716
720
|
} else if (res.type === 'begin' || res.type === 'commit' || res.type === 'rollback') {
|
|
717
721
|
this._inTransaction = res.type === 'begin';
|
|
@@ -792,10 +796,7 @@ class PgServer {
|
|
|
792
796
|
if (user !== this.options.user) return undefined;
|
|
793
797
|
return this.options.password || '';
|
|
794
798
|
}
|
|
795
|
-
|
|
796
|
-
// 此前返回 '' 会被 _startAuth 当成 trust,导致任意用户名 + 空密码即可连入,
|
|
797
|
-
// 与 MysqlServer 的默认拒绝策略保持一致。仅显式 noAuth: true 才放行。
|
|
798
|
-
return undefined;
|
|
799
|
+
return '';
|
|
799
800
|
}
|
|
800
801
|
|
|
801
802
|
_canAccessDb(user, dbName) {
|
package/lib/plugin.js
CHANGED
|
@@ -104,16 +104,10 @@ function definePlugin(name, def = {}) {
|
|
|
104
104
|
}
|
|
105
105
|
|
|
106
106
|
/** 登记单个钩子;未知钩子名会自动创建,便于插件自定义扩展点 */
|
|
107
|
-
function registerHook(engine, hook, fn
|
|
107
|
+
function registerHook(engine, hook, fn) {
|
|
108
108
|
if (typeof fn !== 'function') return engine;
|
|
109
109
|
if (!engine._hooks) engine._hooks = createHookRegistry();
|
|
110
110
|
if (!engine._hooks[hook]) engine._hooks[hook] = [];
|
|
111
|
-
// 记录优先级:即使插件是后加载的,也应按 priority 决定执行顺序,
|
|
112
|
-
// 而不是简单追加在已有钩子之后(此前 sort(_plugins) 只排插件列表,
|
|
113
|
-
// 钩子链仍按注册顺序执行,导致 priority 实际无效)。
|
|
114
|
-
try {
|
|
115
|
-
Object.defineProperty(fn, '__jsqlHookPriority', { value: priority, configurable: true, writable: true });
|
|
116
|
-
} catch (e) { /* 冻结函数等无法打标,按 0 处理 */ }
|
|
117
111
|
engine._hooks[hook].push(fn);
|
|
118
112
|
return engine;
|
|
119
113
|
}
|
|
@@ -121,10 +115,9 @@ function registerHook(engine, hook, fn, priority = 0) {
|
|
|
121
115
|
/** 把一个插件声明的所有钩子登记到引擎上 */
|
|
122
116
|
function registerHooks(engine, plugin) {
|
|
123
117
|
if (!plugin || !plugin.hooks) return engine;
|
|
124
|
-
const priority = plugin.priority || 0;
|
|
125
118
|
for (const [hook, val] of Object.entries(plugin.hooks)) {
|
|
126
119
|
const fns = Array.isArray(val) ? val : [val];
|
|
127
|
-
for (const fn of fns) registerHook(engine, hook, fn
|
|
120
|
+
for (const fn of fns) registerHook(engine, hook, fn);
|
|
128
121
|
}
|
|
129
122
|
return engine;
|
|
130
123
|
}
|
|
@@ -260,11 +253,7 @@ function runHooks(engine, hookName, args) {
|
|
|
260
253
|
|
|
261
254
|
return (async () => {
|
|
262
255
|
try {
|
|
263
|
-
|
|
264
|
-
const ordered = hooks.length > 1
|
|
265
|
-
? hooks.slice().sort((a, b) => (b.__jsqlHookPriority || 0) - (a.__jsqlHookPriority || 0))
|
|
266
|
-
: hooks;
|
|
267
|
-
for (const fn of ordered) {
|
|
256
|
+
for (const fn of hooks) {
|
|
268
257
|
const result = await fn(...args);
|
|
269
258
|
if (result === false) return false;
|
|
270
259
|
}
|
package/lib/query.js
CHANGED
|
@@ -227,9 +227,11 @@ class Query {
|
|
|
227
227
|
const startTime = Date.now();
|
|
228
228
|
if (this._explain) return this._getExplain();
|
|
229
229
|
|
|
230
|
-
//
|
|
230
|
+
// 缓存命中: 返回每行的浅拷贝,与未命中路径一致,避免调用方修改污染缓存
|
|
231
231
|
if (this._cache && this._cache.result && (Date.now() - this._cache.timestamp < this._cache.ttl)) {
|
|
232
|
-
|
|
232
|
+
// #37:命中返回副本,而不是内部数组引用——调用方对返回值做变更
|
|
233
|
+
// (push/splice/改字段)会污染缓存;未命中路径返回的是新数组,行为应一致。
|
|
234
|
+
return this._cache.result.map(row => (row && typeof row === 'object' ? { ...row } : row));
|
|
233
235
|
}
|
|
234
236
|
|
|
235
237
|
// P1-4: 软删除模式下 QueryBuilder 也不得泄露已删除行
|
|
@@ -327,9 +329,10 @@ class Query {
|
|
|
327
329
|
rows = copy;
|
|
328
330
|
}
|
|
329
331
|
|
|
330
|
-
//
|
|
332
|
+
// 缓存存储:#37 存副本,未命中路径返回的 rows 直接给调用方随意变更,
|
|
333
|
+
// 不能把同一个数组塞进缓存(否则调用方 push/改字段会污染后续命中)。
|
|
331
334
|
if (this._cache) {
|
|
332
|
-
this._cache.result = rows;
|
|
335
|
+
this._cache.result = rows.map(row => (row && typeof row === 'object' ? { ...row } : row));
|
|
333
336
|
this._cache.timestamp = Date.now();
|
|
334
337
|
}
|
|
335
338
|
|