jsql-neo 6.8.1 → 6.8.2
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 +1 -1
- package/index.d.ts +4 -1
- package/index.js +1 -1
- package/lib/client.js +1 -1
- package/lib/database.js +21 -2
- package/lib/native_client.js +26 -0
- package/lib/sql.js +129 -30
- package/native/jsql-neo-native.node +0 -0
- package/nativesrc/jsql-neo-core/src/engine/hybrid.rs +7 -0
- package/nativesrc/jsql-neo-core/src/engine/memory.rs +5 -0
- package/nativesrc/jsql-neo-core/src/engine/mod.rs +2 -0
- package/nativesrc/jsql-neo-core/src/engine/table.rs +36 -0
- package/nativesrc/jsql-neo-native/src/lib.rs +5 -0
- package/nativesrc/jsql-neo-wasm/src/lib.rs +8 -0
- package/package.json +3 -3
- package/postinstall.js +27 -32
- package/test/issue-118-136.test.js +86 -0
- package/test/issue-127.test.js +38 -0
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.
|
|
6
|
+
> **v6.8.2** — 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
|

|
|
9
9
|

|
package/index.d.ts
CHANGED
|
@@ -140,7 +140,10 @@ declare namespace JSQLNeo {
|
|
|
140
140
|
run(...params: unknown[]): Promise<any>;
|
|
141
141
|
}
|
|
142
142
|
|
|
143
|
-
export class NativeJSQL extends JSQL {
|
|
143
|
+
export class NativeJSQL extends JSQL {
|
|
144
|
+
/** #126:Rust 侧列式聚合,返回 SUM/AVG/MIN/MAX 的 JSON 数值(旧二进制返回 null)。 */
|
|
145
|
+
aggregate(table: string, op: 'SUM' | 'AVG' | 'MIN' | 'MAX' | 'COUNT', field: string): Promise<number | null>;
|
|
146
|
+
}
|
|
144
147
|
|
|
145
148
|
export interface MysqlServerOptions {
|
|
146
149
|
port?: number;
|
package/index.js
CHANGED
package/lib/client.js
CHANGED
|
@@ -26,7 +26,7 @@ class JSQL {
|
|
|
26
26
|
if (this._process) return;
|
|
27
27
|
const bp = binPath();
|
|
28
28
|
if (!fs.existsSync(bp)) {
|
|
29
|
-
throw new Error(`jsql-neo-server binary not found at ${bp}.
|
|
29
|
+
throw new Error(`jsql-neo-server binary not found at ${bp}. The HTTP client needs an external jsql-neo-server; use NativeJSQL for the embedded engine.`);
|
|
30
30
|
}
|
|
31
31
|
const args = [];
|
|
32
32
|
if (this.dataDir) {
|
package/lib/database.js
CHANGED
|
@@ -28,6 +28,10 @@ function errorWithHint(codeKey, hint) {
|
|
|
28
28
|
return new JSQL_Error(t.code, msg, { codeKey });
|
|
29
29
|
}
|
|
30
30
|
const JSQLFormat = require('./jsql_format');
|
|
31
|
+
|
|
32
|
+
// live 表达到该行数后也挂上行级 LRU:此前只有从磁盘 reload 的表才有
|
|
33
|
+
// rowCache,运行时新建的大表一直整表常驻,最终被整表驱逐或 OOM(#127)。
|
|
34
|
+
const ROW_CACHE_MIN_ROWS = 1000;
|
|
31
35
|
const { valuesEqual } = require('./objectid');
|
|
32
36
|
const {
|
|
33
37
|
createHookRegistry, applyPlugin, buildPluginContext, registerHook,
|
|
@@ -364,6 +368,12 @@ class Database {
|
|
|
364
368
|
_flushTableDelta(name) {
|
|
365
369
|
const table = this._tables[name];
|
|
366
370
|
if (!table) return;
|
|
371
|
+
// live 大表首次达到阈值时走一次全量写,借机挂上行级 rowCache;
|
|
372
|
+
// 之后 delta 写入会照常更新行定位符。
|
|
373
|
+
if (this._dirMode && !table._rowCache && table._rows.length >= ROW_CACHE_MIN_ROWS) {
|
|
374
|
+
this._flushTable(name);
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
367
377
|
const dirty = typeof table._peekDirtyRows === 'function'
|
|
368
378
|
? table._peekDirtyRows()
|
|
369
379
|
: { all: true, upserts: [], deletes: [] };
|
|
@@ -410,17 +420,26 @@ class Database {
|
|
|
410
420
|
const meta = this._meta.tables[name];
|
|
411
421
|
let file = meta && meta.file ? meta.file : encodeURIComponent(name) + '.jsql';
|
|
412
422
|
const fmt = new JSQLFormat(path.join(this._filePath, file));
|
|
423
|
+
let keepHandleOpen = false;
|
|
413
424
|
try {
|
|
414
425
|
const pkField = Object.keys(table._schema).find(f => table._schema[f].primaryKey) || null;
|
|
415
426
|
fmt.writeTable(name, table._schema, table._rows, pkField);
|
|
416
427
|
this._meta.tables[name] = { file, schema: table._schema };
|
|
428
|
+
// live 大表首次全量写完后挂上行级 LRU,让后续内存淘汰按行回退。
|
|
429
|
+
if (this._dirMode && !table._rowCache && table._rows.length >= ROW_CACHE_MIN_ROWS) {
|
|
430
|
+
const locators = fmt.scanLocators(name);
|
|
431
|
+
if (locators.length > 0) {
|
|
432
|
+
table._loadRowRefs(locators, (block, off) => fmt.readRowAt(block, off), fmt);
|
|
433
|
+
keepHandleOpen = true;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
417
436
|
// 整表重写改变了每一行的物理位置,用新文件的定位符重置缓存
|
|
418
|
-
if (typeof table._resetRowLocators === 'function') {
|
|
437
|
+
if (!keepHandleOpen && typeof table._resetRowLocators === 'function') {
|
|
419
438
|
table._resetRowLocators(fmt.scanLocators(name));
|
|
420
439
|
}
|
|
421
440
|
if (typeof table._clearDirtyRows === 'function') table._clearDirtyRows();
|
|
422
441
|
} finally {
|
|
423
|
-
fmt._close();
|
|
442
|
+
if (!keepHandleOpen) fmt._close();
|
|
424
443
|
}
|
|
425
444
|
}
|
|
426
445
|
|
package/lib/native_client.js
CHANGED
|
@@ -244,7 +244,18 @@ function parseShorthandSchema(str) {
|
|
|
244
244
|
def.type = next || def.type;
|
|
245
245
|
};
|
|
246
246
|
if (/\bprimary\s+key\b/i.test(def.type)) { def.primaryKey = true; strip(/\bprimary\s+key\b/gi); }
|
|
247
|
+
let explicitNoAuto = false;
|
|
248
|
+
if (/\b(auto_?increment\s*=\s*false|not\s+auto_?increment)\b/i.test(def.type)) {
|
|
249
|
+
explicitNoAuto = true;
|
|
250
|
+
strip(/\b(auto_?increment\s*=\s*false|not\s+auto_?increment)\b/gi);
|
|
251
|
+
}
|
|
247
252
|
if (/\bauto_?increment\b/i.test(def.type)) { def.autoIncrement = true; strip(/\bauto_?increment\b/gi); }
|
|
253
|
+
// MySQL 的整型 PRIMARY KEY 等价于 ROWID:内部行 id 与主键值一致。
|
|
254
|
+
// 默认推断为自增,让 findById 走 O(1) 的 jsqlFindById,而非全表扫描(#123)。
|
|
255
|
+
if (def.primaryKey && !explicitNoAuto && def.autoIncrement === undefined
|
|
256
|
+
&& /^(big)?int(eger)?$/i.test(def.type.trim())) {
|
|
257
|
+
def.autoIncrement = true;
|
|
258
|
+
}
|
|
248
259
|
if (/\bnot\s+null\b/i.test(def.type)) { def.required = true; strip(/\bnot\s+null\b/gi); }
|
|
249
260
|
if (/\bunique\b/i.test(def.type)) { def.unique = true; strip(/\bunique\b/gi); }
|
|
250
261
|
if (/\bdefault\s+(\S+)/i.test(def.type)) {
|
|
@@ -947,6 +958,21 @@ class JSQL {
|
|
|
947
958
|
return n;
|
|
948
959
|
}
|
|
949
960
|
|
|
961
|
+
/**
|
|
962
|
+
* #126:SUM/AVG/MIN/MAX 直接走 Rust 列式聚合,避免整表拉回 JS。
|
|
963
|
+
* 旧版二进制没有导出时返回 null,调用方可回退到 SQL 聚合路径。
|
|
964
|
+
*/
|
|
965
|
+
async aggregate(table, op, field) {
|
|
966
|
+
this._flushOpsNow();
|
|
967
|
+
const has = this._multiInstance && this._handle !== null
|
|
968
|
+
? typeof native.jsqlAggregateH === 'function'
|
|
969
|
+
: typeof native.jsqlAggregate === 'function';
|
|
970
|
+
if (!has) return null;
|
|
971
|
+
const r = safeParse(this._n('jsqlAggregate', table, String(op).toUpperCase(), String(field)));
|
|
972
|
+
if (r && r.error) throw new Error(r.error);
|
|
973
|
+
return r;
|
|
974
|
+
}
|
|
975
|
+
|
|
950
976
|
async updateByIds(table, entries) {
|
|
951
977
|
const schema = this._schemas[table];
|
|
952
978
|
const pairs = [];
|
package/lib/sql.js
CHANGED
|
@@ -346,6 +346,18 @@ function tokenize(sql) {
|
|
|
346
346
|
}
|
|
347
347
|
}
|
|
348
348
|
|
|
349
|
+
// 2 进制字面量:0b1010 / 0B1010(MySQL 8.0)
|
|
350
|
+
if (c === '0' && (sql[i + 1] === 'b' || sql[i + 1] === 'B')) {
|
|
351
|
+
let j = i + 2;
|
|
352
|
+
while (j < n && (sql[j] === '0' || sql[j] === '1')) j++;
|
|
353
|
+
if (j === i + 2) throw new Error(`Invalid binary literal at position ${i}`);
|
|
354
|
+
const bits = sql.slice(i + 2, j);
|
|
355
|
+
const b = BigInt('0b' + bits);
|
|
356
|
+
tokens.push(new SQLToken('number', b <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(b) : b, i));
|
|
357
|
+
i = j;
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
|
|
349
361
|
if (/[0-9]/.test(c) || (c === '.' && /[0-9]/.test(sql[i + 1] || ''))) {
|
|
350
362
|
let j = i;
|
|
351
363
|
let isFloat = false;
|
|
@@ -2807,6 +2819,13 @@ class Parser {
|
|
|
2807
2819
|
if (this.isWord('LEADING') || this.isWord('TRAILING') || this.isWord('BOTH')) {
|
|
2808
2820
|
spec = String(this.next().value).toUpperCase();
|
|
2809
2821
|
}
|
|
2822
|
+
// TRIM({BOTH|LEADING|TRAILING} FROM str):省略 remstr,默认裁剪空格
|
|
2823
|
+
if (spec && this.isWord('FROM')) {
|
|
2824
|
+
this.next();
|
|
2825
|
+
const target = this.parseOperand();
|
|
2826
|
+
this.expect('op', ')');
|
|
2827
|
+
return { type: 'func', name: 'TRIM', args: [target, { type: 'value', value: null }, { type: 'value', value: spec }] };
|
|
2828
|
+
}
|
|
2810
2829
|
const first = this.parseOperand();
|
|
2811
2830
|
let target = null;
|
|
2812
2831
|
if (this.isWord('FROM')) {
|
|
@@ -4067,33 +4086,42 @@ function strToDate(s, fmt) {
|
|
|
4067
4086
|
const m = new RegExp('^' + pattern + '$').exec(String(s));
|
|
4068
4087
|
if (!m) return null;
|
|
4069
4088
|
let year = 1970, month = 0, day = 1, hour = 0, min = 0, sec = 0;
|
|
4089
|
+
let invalid = false;
|
|
4090
|
+
const inRange = (v, lo, hi) => Number.isFinite(v) && v >= lo && v <= hi;
|
|
4070
4091
|
order.forEach((c, idx) => {
|
|
4071
4092
|
const v = m[idx + 1];
|
|
4072
4093
|
if (v === undefined) return;
|
|
4094
|
+
const num = Number(v);
|
|
4073
4095
|
switch (c) {
|
|
4074
|
-
case 'Y': year =
|
|
4075
|
-
case 'y': year =
|
|
4076
|
-
case 'm': case 'c': month =
|
|
4096
|
+
case 'Y': year = num; if (!inRange(year, 0, 9999)) invalid = true; break;
|
|
4097
|
+
case 'y': year = num < 70 ? 2000 + num : 1900 + num; break;
|
|
4098
|
+
case 'm': case 'c': month = num - 1; if (!inRange(num, 1, 12)) invalid = true; break;
|
|
4077
4099
|
case 'M': case 'b': {
|
|
4078
4100
|
const mi = MONTH_NAMES.findIndex((x) => x.toLowerCase().startsWith(String(v).toLowerCase().slice(0, 3)));
|
|
4079
4101
|
if (mi >= 0) month = mi;
|
|
4080
4102
|
break;
|
|
4081
4103
|
}
|
|
4082
|
-
case 'd': case 'e': day =
|
|
4083
|
-
case 'H': case 'k': hour =
|
|
4104
|
+
case 'd': case 'e': day = num; if (!inRange(num, 1, 31)) invalid = true; break;
|
|
4105
|
+
case 'H': case 'k': hour = num; if (!inRange(num, 0, 23)) invalid = true; break;
|
|
4084
4106
|
case 'h': case 'I': case 'l': {
|
|
4085
|
-
|
|
4107
|
+
if (!inRange(num, 1, 12)) { invalid = true; break; }
|
|
4108
|
+
const hh = num % 12;
|
|
4086
4109
|
hour = /pm/i.test(String(s)) ? hh + 12 : hh;
|
|
4087
4110
|
break;
|
|
4088
4111
|
}
|
|
4089
|
-
case 'i': min =
|
|
4090
|
-
case 'S': case 's': sec =
|
|
4112
|
+
case 'i': min = num; if (!inRange(num, 0, 59)) invalid = true; break;
|
|
4113
|
+
case 'S': case 's': sec = num; if (!inRange(num, 0, 59)) invalid = true; break;
|
|
4091
4114
|
default: break;
|
|
4092
4115
|
}
|
|
4093
4116
|
});
|
|
4117
|
+
if (invalid) return null;
|
|
4094
4118
|
// 无时区 → UTC 墙上时间(与 parseSqlDate 一致)
|
|
4095
4119
|
const d = new Date(Date.UTC(year, month, day, hour, min, sec));
|
|
4096
|
-
|
|
4120
|
+
if (Number.isNaN(d.getTime())) return null;
|
|
4121
|
+
// 回读校验:JS 会把 2 月 30 日归一到 3 月 1 日;MySQL 对非法日历日期返回 NULL
|
|
4122
|
+
if (d.getUTCFullYear() !== year || d.getUTCMonth() !== month || d.getUTCDate() !== day ||
|
|
4123
|
+
d.getUTCHours() !== hour || d.getUTCMinutes() !== min || d.getUTCSeconds() !== sec) return null;
|
|
4124
|
+
return d;
|
|
4097
4125
|
}
|
|
4098
4126
|
|
|
4099
4127
|
/** PG DATE_PART / EXTRACT 的部件取值(UTC 部件) */
|
|
@@ -4176,6 +4204,31 @@ const MATH_SCALAR_FNS = new Set([
|
|
|
4176
4204
|
'SIN', 'COS', 'TAN', 'ASIN', 'ACOS', 'ATAN', 'ATAN2',
|
|
4177
4205
|
'DEGREES', 'RADIANS', 'COT',
|
|
4178
4206
|
]);
|
|
4207
|
+
// NULLIF 等场景需要 SQL 风格的等值比较:数字与数字字符串按数值比较,
|
|
4208
|
+
// 不能用 JS 的 ===(1 === '1' 为 false,而 MySQL 里 1 = '1' 为真)。
|
|
4209
|
+
function sqlValuesEqual(a, b) {
|
|
4210
|
+
if (a === b) return true;
|
|
4211
|
+
if (a == null || b == null) return false;
|
|
4212
|
+
const numeric = v => typeof v === 'number' || typeof v === 'bigint'
|
|
4213
|
+
|| (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v)));
|
|
4214
|
+
const hasNumericOperand = typeof a === 'number' || typeof a === 'bigint'
|
|
4215
|
+
|| typeof b === 'number' || typeof b === 'bigint';
|
|
4216
|
+
if (hasNumericOperand && numeric(a) && numeric(b)) return Number(a) === Number(b);
|
|
4217
|
+
return String(a) === String(b);
|
|
4218
|
+
}
|
|
4219
|
+
|
|
4220
|
+
// 判断表达式节点是否带有 BINARY 语义(BINARY x / CAST(x AS BINARY));
|
|
4221
|
+
// LIKE / REGEXP 默认大小写不敏感,带 BINARY 时必须按字节大小写敏感比较。
|
|
4222
|
+
function isBinaryNode(node) {
|
|
4223
|
+
if (!node || typeof node !== 'object') return false;
|
|
4224
|
+
if (node.type === 'binary') return true;
|
|
4225
|
+
if (node.type === 'cast') {
|
|
4226
|
+
const dt = typeof node.dataType === 'string' ? node.dataType : '';
|
|
4227
|
+
return /\b(BINARY|VARBINARY|BLOB)\b/i.test(dt);
|
|
4228
|
+
}
|
|
4229
|
+
return false;
|
|
4230
|
+
}
|
|
4231
|
+
|
|
4179
4232
|
function applyScalarFunction(fnNode, row, ctx) {
|
|
4180
4233
|
const name = (fnNode.name || '').toUpperCase();
|
|
4181
4234
|
const rawArgs = fnNode.args || [];
|
|
@@ -4196,12 +4249,37 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4196
4249
|
switch (name) {
|
|
4197
4250
|
case 'ABS': return v < 0n ? -v : v;
|
|
4198
4251
|
case 'SIGN': return v > 0n ? 1 : (v < 0n ? -1 : 0);
|
|
4199
|
-
case 'FLOOR': case 'CEIL': case 'CEILING':
|
|
4252
|
+
case 'FLOOR': case 'CEIL': case 'CEILING':
|
|
4200
4253
|
return v; // 整数本身就是它的 floor/ceil/round
|
|
4254
|
+
case 'ROUND': case 'TRUNCATE': {
|
|
4255
|
+
const d = args[1];
|
|
4256
|
+
if (d == null || d === 0 || d === 0n) return v;
|
|
4257
|
+
const di = typeof d === 'bigint' ? Number(d) : Math.trunc(Number(d));
|
|
4258
|
+
if (!Number.isFinite(di) || di >= 0) return v;
|
|
4259
|
+
const factor = 10n ** BigInt(-di);
|
|
4260
|
+
const q = v / factor;
|
|
4261
|
+
if (name === 'TRUNCATE') return q * factor;
|
|
4262
|
+
const r = v % factor;
|
|
4263
|
+
const ar = r < 0n ? -r : r;
|
|
4264
|
+
let rounded = q;
|
|
4265
|
+
if (ar * 2n >= factor) rounded += (v < 0n ? -1n : 1n);
|
|
4266
|
+
return rounded * factor;
|
|
4267
|
+
}
|
|
4201
4268
|
case 'MOD': {
|
|
4202
4269
|
const d = args[1];
|
|
4203
4270
|
if (d == null || d === 0 || d === 0n) return null;
|
|
4204
|
-
|
|
4271
|
+
if (typeof d === 'bigint') return v % d;
|
|
4272
|
+
const dn = Number(d);
|
|
4273
|
+
if (!Number.isFinite(dn)) return null;
|
|
4274
|
+
if (Number.isInteger(dn)) return v % BigInt(dn);
|
|
4275
|
+
// 小数除数:MySQL 按浮点语义求值,避免 BigInt(Math.trunc(...)) 截断为 0
|
|
4276
|
+
// 以及大整数经 Number() 丢失精度。用整数缩放保持精确余数。
|
|
4277
|
+
const decimals = (String(dn).split('.')[1] || '').length;
|
|
4278
|
+
const scale = 10 ** decimals;
|
|
4279
|
+
const dInt = BigInt(Math.round(dn * scale));
|
|
4280
|
+
if (dInt === 0n) return null;
|
|
4281
|
+
const remScaled = (v * BigInt(scale)) % dInt;
|
|
4282
|
+
return Number(remScaled) / scale;
|
|
4205
4283
|
}
|
|
4206
4284
|
case 'POWER': case 'POW': {
|
|
4207
4285
|
const e = args[1];
|
|
@@ -4224,6 +4302,7 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4224
4302
|
}
|
|
4225
4303
|
switch (name) {
|
|
4226
4304
|
case 'VERSION': return '8.0.0-jsql-neo';
|
|
4305
|
+
case 'PI': return Math.PI;
|
|
4227
4306
|
case 'LAST_INSERT_ID':
|
|
4228
4307
|
case 'LAST_INSERT_ROWID': {
|
|
4229
4308
|
if (args.length > 0) {
|
|
@@ -4280,10 +4359,14 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4280
4359
|
case 'TRIM': {
|
|
4281
4360
|
if (args[0] == null) return null;
|
|
4282
4361
|
const s = String(args[0]);
|
|
4362
|
+
const spec = args[2] ? String(args[2]).toUpperCase() : 'BOTH';
|
|
4283
4363
|
if (args.length === 1) return s.trim();
|
|
4284
4364
|
const chars = args[1] == null ? '' : String(args[1]);
|
|
4285
|
-
if (!chars)
|
|
4286
|
-
|
|
4365
|
+
if (!chars) {
|
|
4366
|
+
if (spec === 'LEADING') return s.replace(/^\s+/, '');
|
|
4367
|
+
if (spec === 'TRAILING') return s.replace(/\s+$/, '');
|
|
4368
|
+
return s.trim();
|
|
4369
|
+
}
|
|
4287
4370
|
const esc = chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
4288
4371
|
const head = new RegExp('^[' + esc + ']+');
|
|
4289
4372
|
const tail = new RegExp('[' + esc + ']+$');
|
|
@@ -4415,16 +4498,17 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4415
4498
|
// TIMESTAMPDIFF(MONTH,'2026-01-31','2026-03-01') = 1(1/31+1月=2/28,2/28+1月=3/28,够不到 3/1)
|
|
4416
4499
|
let months = (a.getUTCFullYear() - b.getUTCFullYear()) * 12 + (a.getUTCMonth() - b.getUTCMonth());
|
|
4417
4500
|
if (a.getUTCDate() < b.getUTCDate()) months--;
|
|
4501
|
+
// MySQL 对负差值按「向零截断」取整;Math.floor 会向 -∞ 多减 1。
|
|
4418
4502
|
switch (unit) {
|
|
4419
|
-
case 'MICROSECOND': return Math.
|
|
4420
|
-
case 'SECOND': return Math.
|
|
4421
|
-
case 'MINUTE': return Math.
|
|
4422
|
-
case 'HOUR': return Math.
|
|
4423
|
-
case 'DAY': return Math.
|
|
4424
|
-
case 'WEEK': return Math.
|
|
4503
|
+
case 'MICROSECOND': return Math.trunc(ms * 1000);
|
|
4504
|
+
case 'SECOND': return Math.trunc(ms / 1000);
|
|
4505
|
+
case 'MINUTE': return Math.trunc(ms / 60000);
|
|
4506
|
+
case 'HOUR': return Math.trunc(ms / 3600000);
|
|
4507
|
+
case 'DAY': return Math.trunc(ms / 86400000);
|
|
4508
|
+
case 'WEEK': return Math.trunc(ms / (86400000 * 7));
|
|
4425
4509
|
case 'MONTH': return months;
|
|
4426
|
-
case 'QUARTER': return Math.
|
|
4427
|
-
case 'YEAR': return Math.
|
|
4510
|
+
case 'QUARTER': return Math.trunc(months / 3);
|
|
4511
|
+
case 'YEAR': return Math.trunc(months / 12);
|
|
4428
4512
|
default: return null;
|
|
4429
4513
|
}
|
|
4430
4514
|
}
|
|
@@ -4482,7 +4566,7 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4482
4566
|
case 'MAKEDATE': {
|
|
4483
4567
|
const y = Number(args[0]);
|
|
4484
4568
|
const doy = Number(args[1]);
|
|
4485
|
-
if (!Number.isFinite(y) || !Number.isFinite(doy)) return null;
|
|
4569
|
+
if (!Number.isFinite(y) || !Number.isFinite(doy) || doy < 1) return null;
|
|
4486
4570
|
const d = new Date(Date.UTC(y, 0, 1));
|
|
4487
4571
|
d.setUTCDate(doy);
|
|
4488
4572
|
return fmtSqlDate(true, d);
|
|
@@ -4591,11 +4675,24 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4591
4675
|
const from = Math.trunc(Number(args[1])), to = Math.trunc(Number(args[2]));
|
|
4592
4676
|
if (from < 2 || from > 36 || to < 2 || to > 36) return null;
|
|
4593
4677
|
const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
4594
|
-
let n
|
|
4595
|
-
|
|
4596
|
-
|
|
4597
|
-
|
|
4598
|
-
n =
|
|
4678
|
+
let n;
|
|
4679
|
+
if (typeof args[0] === 'number' || typeof args[0] === 'bigint') {
|
|
4680
|
+
// 数值参数本身就是十进制整数;负数按 64 位无符号(补码)处理
|
|
4681
|
+
const num = typeof args[0] === 'bigint' ? args[0] : BigInt(Math.trunc(Number(args[0])));
|
|
4682
|
+
n = BigInt.asUintN(64, num);
|
|
4683
|
+
} else {
|
|
4684
|
+
let raw = String(args[0]).trim().toUpperCase();
|
|
4685
|
+
let neg = false;
|
|
4686
|
+
if (raw[0] === '-') { neg = true; raw = raw.slice(1); }
|
|
4687
|
+
else if (raw[0] === '+') raw = raw.slice(1);
|
|
4688
|
+
if (!raw) return null;
|
|
4689
|
+
n = 0n;
|
|
4690
|
+
for (const ch of raw) {
|
|
4691
|
+
const d = digits.indexOf(ch);
|
|
4692
|
+
if (d < 0 || d >= from) return null;
|
|
4693
|
+
n = n * BigInt(from) + BigInt(d);
|
|
4694
|
+
}
|
|
4695
|
+
if (neg) n = BigInt.asUintN(64, -n);
|
|
4599
4696
|
}
|
|
4600
4697
|
if (n === 0n) return '0';
|
|
4601
4698
|
let out = '';
|
|
@@ -4779,7 +4876,7 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4779
4876
|
const hit = args.find(a => a != null);
|
|
4780
4877
|
return hit === undefined ? null : hit;
|
|
4781
4878
|
}
|
|
4782
|
-
case 'NULLIF': return args[0]
|
|
4879
|
+
case 'NULLIF': return sqlValuesEqual(args[0], args[1]) ? null : args[0];
|
|
4783
4880
|
case 'IF': return args[0] ? args[1] : args[2];
|
|
4784
4881
|
case 'REPLACE': return args[0] == null ? null : String(args[0]).split(args[1]).join(args[2]);
|
|
4785
4882
|
case 'REPEAT': {
|
|
@@ -5817,7 +5914,8 @@ function evaluateExpr(expr, row, ctx) {
|
|
|
5817
5914
|
const v = resolveOperand(expr.operand, row, ctx);
|
|
5818
5915
|
// MySQL 的 LIKE 默认不区分大小写;只有显式 BINARY / ci=false 才敏感。
|
|
5819
5916
|
// 此前写成 !!expr.ci,把 likeMatch 的 ci 默认值 true 覆盖成了 false。
|
|
5820
|
-
const
|
|
5917
|
+
const binaryCmp = isBinaryNode(expr.operand) || isBinaryNode(expr.pattern);
|
|
5918
|
+
const r = likeMatch(v, expr.pattern, expr.ci !== false && !binaryCmp, expr.escape);
|
|
5821
5919
|
// #94:NULL LIKE → UNKNOWN(null);NOT (NULL LIKE) 仍为 UNKNOWN(null)。
|
|
5822
5920
|
if (r === null) return null;
|
|
5823
5921
|
return expr.not ? !r : r;
|
|
@@ -5830,7 +5928,8 @@ function evaluateExpr(expr, row, ctx) {
|
|
|
5830
5928
|
const v = resolveOperand(expr.operand, row, ctx);
|
|
5831
5929
|
if (v === null || v === undefined) return false;
|
|
5832
5930
|
// REGEXP / RLIKE 历史上就是大小写不敏感的;`~` 敏感、`~*` 不敏感
|
|
5833
|
-
const
|
|
5931
|
+
const binaryCmp = isBinaryNode(expr.operand) || isBinaryNode(expr.pattern);
|
|
5932
|
+
const re = new RegExp(String(expr.pattern), (expr.ci === false || binaryCmp) ? '' : 'i');
|
|
5834
5933
|
const r = re.test(String(v));
|
|
5835
5934
|
return expr.not ? !r : r;
|
|
5836
5935
|
}
|
|
Binary file
|
|
@@ -453,6 +453,13 @@ impl Engine for HybridEngine {
|
|
|
453
453
|
r
|
|
454
454
|
}
|
|
455
455
|
|
|
456
|
+
fn aggregate(&self, table: &str, op: &str, field: &str) -> Result<String, String> {
|
|
457
|
+
self.ensure_table(table);
|
|
458
|
+
let r = self.mem.borrow().aggregate(table, op, field);
|
|
459
|
+
if r.is_ok() { self.touch(table); }
|
|
460
|
+
r
|
|
461
|
+
}
|
|
462
|
+
|
|
456
463
|
fn update_by_id(&mut self, table: &str, id: u64, data: HashMap<String, serde_json::Value>) -> Result<bool, String> {
|
|
457
464
|
self.ensure_table(table);
|
|
458
465
|
let r = self.mem.borrow_mut().update_by_id(table, id, data)?;
|
|
@@ -107,6 +107,11 @@ impl Engine for MemoryEngine {
|
|
|
107
107
|
Ok(t.count())
|
|
108
108
|
}
|
|
109
109
|
|
|
110
|
+
fn aggregate(&self, table: &str, op: &str, field: &str) -> Result<String, String> {
|
|
111
|
+
let t = self.tables.get(table).ok_or_else(|| format!("table '{}' not found", table))?;
|
|
112
|
+
Ok(t.aggregate_json(op, field))
|
|
113
|
+
}
|
|
114
|
+
|
|
110
115
|
fn update_by_id(&mut self, table: &str, id: u64, data: HashMap<String, serde_json::Value>) -> Result<bool, String> {
|
|
111
116
|
let t = self.tables.get_mut(table).ok_or_else(|| format!("table '{}' not found", table))?;
|
|
112
117
|
t.update_row(id, data)
|
|
@@ -68,6 +68,8 @@ pub trait Engine {
|
|
|
68
68
|
Ok((json, cursor, has_more))
|
|
69
69
|
}
|
|
70
70
|
fn count(&self, table: &str) -> Result<usize, String>;
|
|
71
|
+
/// 按列聚合(#126),返回 JSON 数值字符串。
|
|
72
|
+
fn aggregate(&self, table: &str, op: &str, field: &str) -> Result<String, String>;
|
|
71
73
|
fn update_by_id(&mut self, table: &str, id: u64, data: HashMap<String, serde_json::Value>) -> Result<bool, String>;
|
|
72
74
|
fn update_by_ids(&mut self, table: &str, batch: Vec<(u64, HashMap<String, serde_json::Value>)>) -> Result<usize, String>;
|
|
73
75
|
fn remove_by_id(&mut self, table: &str, id: u64) -> Result<bool, String>;
|
|
@@ -906,6 +906,42 @@ impl Table {
|
|
|
906
906
|
self.rows.len()
|
|
907
907
|
}
|
|
908
908
|
|
|
909
|
+
/// 按列聚合 SUM/AVG/MIN/MAX(#126):直接在列式行缓冲区上单遍扫描,
|
|
910
|
+
/// 避免把整表行拉回 JS 层再聚合。返回 JSON 数值,空集/未知列返回 null。
|
|
911
|
+
pub fn aggregate_json(&self, op: &str, field: &str) -> String {
|
|
912
|
+
let col = match self.field_index.get(field) {
|
|
913
|
+
Some(i) => *i,
|
|
914
|
+
None => return "null".to_string(),
|
|
915
|
+
};
|
|
916
|
+
let mut sum = 0.0f64;
|
|
917
|
+
let mut count = 0usize;
|
|
918
|
+
let mut min: Option<f64> = None;
|
|
919
|
+
let mut max: Option<f64> = None;
|
|
920
|
+
for rs in &self.rows {
|
|
921
|
+
let vals = self.get_row_values(rs);
|
|
922
|
+
let n = match vals.get(col) {
|
|
923
|
+
Some(FieldValue::Int(i)) => *i as f64,
|
|
924
|
+
Some(FieldValue::UInt(u)) => *u as f64,
|
|
925
|
+
Some(FieldValue::Float(f)) => *f,
|
|
926
|
+
Some(FieldValue::Bool(b)) => if *b { 1.0 } else { 0.0 },
|
|
927
|
+
_ => continue,
|
|
928
|
+
};
|
|
929
|
+
if !n.is_finite() { continue; }
|
|
930
|
+
count += 1;
|
|
931
|
+
sum += n;
|
|
932
|
+
min = Some(min.map_or(n, |m| m.min(n)));
|
|
933
|
+
max = Some(max.map_or(n, |m| m.max(n)));
|
|
934
|
+
}
|
|
935
|
+
match op.to_ascii_uppercase().as_str() {
|
|
936
|
+
"COUNT" => count.to_string(),
|
|
937
|
+
"SUM" => if count == 0 { "null".to_string() } else { sum.to_string() },
|
|
938
|
+
"AVG" => if count == 0 { "null".to_string() } else { (sum / count as f64).to_string() },
|
|
939
|
+
"MIN" => min.map_or_else(|| "null".to_string(), |v| v.to_string()),
|
|
940
|
+
"MAX" => max.map_or_else(|| "null".to_string(), |v| v.to_string()),
|
|
941
|
+
_ => "null".to_string(),
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
|
|
909
945
|
// ============================================================
|
|
910
946
|
// 磁盘持久化导出 / 导入(供 HybridEngine 使用)
|
|
911
947
|
// ============================================================
|
|
@@ -317,6 +317,11 @@ napi_engine_fn!(jsql_count, jsql_count_h, (table: String) => |eng| {
|
|
|
317
317
|
}
|
|
318
318
|
});
|
|
319
319
|
|
|
320
|
+
// #126:SUM/AVG/MIN/MAX 下沉到 Rust,单遍扫描列式行缓冲区
|
|
321
|
+
napi_engine_fn!(jsql_aggregate, jsql_aggregate_h, (table: String, op: String, field: String) => |eng| {
|
|
322
|
+
safe_json_result(eng.aggregate(&table, &op, &field))
|
|
323
|
+
});
|
|
324
|
+
|
|
320
325
|
napi_engine_fn!(jsql_update_by_id, jsql_update_by_id_h,
|
|
321
326
|
(table: String, id: i64, data_json: String) => |eng| {
|
|
322
327
|
let data: HashMap<String, serde_json::Value> = match serde_json::from_str(&data_json) {
|
|
@@ -317,6 +317,14 @@ pub fn jsql_count(table: &str) -> String {
|
|
|
317
317
|
})
|
|
318
318
|
}
|
|
319
319
|
|
|
320
|
+
#[wasm_bindgen]
|
|
321
|
+
pub fn jsql_aggregate(table: &str, op: &str, field: &str) -> String {
|
|
322
|
+
ENGINE.with(|eng| match eng.borrow().aggregate(table, op, field) {
|
|
323
|
+
Ok(v) => v,
|
|
324
|
+
Err(e) => format!(r#"{{"error":"{}"}}"#, e),
|
|
325
|
+
})
|
|
326
|
+
}
|
|
327
|
+
|
|
320
328
|
#[wasm_bindgen]
|
|
321
329
|
pub fn jsql_update_by_id(table: &str, id: u64, data_json: &str) -> String {
|
|
322
330
|
ENGINE.with(|eng| {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jsql-neo",
|
|
3
|
-
"version": "6.8.
|
|
3
|
+
"version": "6.8.2",
|
|
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",
|
|
@@ -52,12 +52,12 @@
|
|
|
52
52
|
"build:native": "node scripts/build-native.js",
|
|
53
53
|
"check:release": "node scripts/check-release-metadata.js",
|
|
54
54
|
"release:prep": "node scripts/release.js",
|
|
55
|
-
"test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js",
|
|
55
|
+
"test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js",
|
|
56
56
|
"test:parser": "node test/sql-parser.test.js",
|
|
57
57
|
"test:btree": "node test/btree.test.js",
|
|
58
58
|
"test:native": "node test/native.test.js",
|
|
59
59
|
"test:regress": "node test/regress-5.1.0.js",
|
|
60
|
-
"test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js",
|
|
60
|
+
"test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js",
|
|
61
61
|
"test:coverage": "c8 --all --include='lib/**' --exclude='lib/web_ui.js' --reporter=text --reporter=lcov node test/coverage.js",
|
|
62
62
|
"test:orms": "node examples/orms/run-all.js",
|
|
63
63
|
"test:dml": "node test/dml-constraints.test.js",
|
package/postinstall.js
CHANGED
|
@@ -328,7 +328,9 @@ async function fetchExpectedHash(asset, tag) {
|
|
|
328
328
|
|
|
329
329
|
function buildNativeFromSource() {
|
|
330
330
|
const crate = path.join(ROOT, 'nativesrc', 'jsql-neo-native');
|
|
331
|
-
if (!fs.existsSync(path.join(crate, 'Cargo.toml')))
|
|
331
|
+
if (!fs.existsSync(path.join(crate, 'Cargo.toml'))) {
|
|
332
|
+
throw new Error(`native source crate not found at ${crate}; cannot build from source`);
|
|
333
|
+
}
|
|
332
334
|
console.log('[jsql-neo] building native module from source...');
|
|
333
335
|
try {
|
|
334
336
|
execSync('cargo build --release', { cwd: crate, stdio: 'inherit' });
|
|
@@ -338,14 +340,24 @@ function buildNativeFromSource() {
|
|
|
338
340
|
: process.platform === 'darwin'
|
|
339
341
|
? path.join(rel, 'libjsql_neo_native.dylib')
|
|
340
342
|
: path.join(rel, 'libjsql_neo_native.so');
|
|
341
|
-
if (fs.existsSync(src)) {
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
343
|
+
if (!fs.existsSync(src)) throw new Error(`cargo build produced no module at ${src}`);
|
|
344
|
+
fs.mkdirSync(path.dirname(NATIVE_PATH), { recursive: true });
|
|
345
|
+
fs.copyFileSync(src, NATIVE_PATH);
|
|
346
|
+
fs.chmodSync(NATIVE_PATH, 0o755);
|
|
347
|
+
console.log(`[jsql-neo] native module built: native/jsql-neo-native.node`);
|
|
348
|
+
} catch (e) {
|
|
349
|
+
throw new Error(`native source build failed: ${e.message}`);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// 源码编译失败必须出声,但不能让 npm install 整体崩掉(WASM/JS 兜底仍可用)
|
|
354
|
+
function tryBuildNativeFromSource() {
|
|
355
|
+
try {
|
|
356
|
+
buildNativeFromSource();
|
|
357
|
+
return true;
|
|
347
358
|
} catch (e) {
|
|
348
|
-
console.warn(
|
|
359
|
+
console.warn(`[jsql-neo] ${e.message}; using WASM/JS engine.`);
|
|
360
|
+
return false;
|
|
349
361
|
}
|
|
350
362
|
}
|
|
351
363
|
|
|
@@ -529,7 +541,7 @@ async function ensureNativeNode() {
|
|
|
529
541
|
console.log('[jsql-neo] native module ready: native/jsql-neo-native.node');
|
|
530
542
|
return;
|
|
531
543
|
}
|
|
532
|
-
|
|
544
|
+
tryBuildNativeFromSource();
|
|
533
545
|
return;
|
|
534
546
|
}
|
|
535
547
|
|
|
@@ -553,7 +565,7 @@ async function ensureNativeNode() {
|
|
|
553
565
|
return;
|
|
554
566
|
}
|
|
555
567
|
console.warn('[jsql-neo] could not fetch a verified native module; falling back to source build / WASM.');
|
|
556
|
-
|
|
568
|
+
tryBuildNativeFromSource();
|
|
557
569
|
}
|
|
558
570
|
|
|
559
571
|
/**
|
|
@@ -655,28 +667,11 @@ function ensureServerBinary() {
|
|
|
655
667
|
console.log(`[jsql-neo] binary ready: ${BP}`);
|
|
656
668
|
return;
|
|
657
669
|
}
|
|
658
|
-
|
|
659
|
-
//
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
try {
|
|
664
|
-
execSync('cargo build --release', { cwd: serverDir, stdio: 'inherit' });
|
|
665
|
-
const src = path.join(serverDir, 'target', 'release', BIN_NAME);
|
|
666
|
-
if (fs.existsSync(src)) {
|
|
667
|
-
fs.mkdirSync(path.join(ROOT, 'bin'), { recursive: true });
|
|
668
|
-
fs.copyFileSync(src, BP);
|
|
669
|
-
fs.chmodSync(BP, 0o755);
|
|
670
|
-
console.log(`[jsql-neo] binary built: ${BP}`);
|
|
671
|
-
return;
|
|
672
|
-
}
|
|
673
|
-
} catch (e) {
|
|
674
|
-
console.warn('[jsql-neo] cargo build failed:', e.message);
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
|
|
678
|
-
console.warn(`[jsql-neo] server binary not found at ${BP}`);
|
|
679
|
-
console.warn('[jsql-neo] install Rust from https://rustup.rs and run: npm run build');
|
|
670
|
+
// HTTP 服务端二进制不随 npm release 提供,旧版本里指向的同名源码目录
|
|
671
|
+
// (ROOT/../jsql-neo-server)也早已不存在。这里给出明确指引而不是走死路径。
|
|
672
|
+
console.warn(`[jsql-neo] optional HTTP server binary not found at ${BP}`);
|
|
673
|
+
console.warn('[jsql-neo] It is not shipped in npm releases; use NativeJSQL (embedded engine) or run an external jsql-neo-server.');
|
|
674
|
+
console.warn('[jsql-neo] To build the embedded native module from source (Rust required), run: npm run build:native');
|
|
680
675
|
}
|
|
681
676
|
|
|
682
677
|
async function main() {
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/* 回归测试:issue #118 #119 #125 #129 #130 #131 #132 #133 #134 #135 #136 */
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const ROOT = path.join(__dirname, '..');
|
|
4
|
+
const { executeSQL, tokenize } = require(path.join(ROOT, 'lib', 'sql.js'));
|
|
5
|
+
|
|
6
|
+
let pass = 0, fail = 0;
|
|
7
|
+
function ok(name, cond, got) {
|
|
8
|
+
if (cond) { pass++; console.log('[OK] ' + name); }
|
|
9
|
+
else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const engine = {
|
|
13
|
+
hasTable: () => true,
|
|
14
|
+
truncate: async () => {},
|
|
15
|
+
flush: async () => {},
|
|
16
|
+
find: async () => [],
|
|
17
|
+
getTableSchema: async () => ({}),
|
|
18
|
+
};
|
|
19
|
+
async function q(sql) {
|
|
20
|
+
const r = await executeSQL(engine, sql, { safety: false });
|
|
21
|
+
return r.rows[0][0];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
(async () => {
|
|
25
|
+
// #118: 0b 二进制整数字面量
|
|
26
|
+
const toks = tokenize('0b1010');
|
|
27
|
+
ok('#118 tokenize 0b1010 为单个 number token', toks[0].type === 'number' && toks[0].value === 10 && toks[1].type === 'eof', toks);
|
|
28
|
+
ok('#118 SELECT 0b1010', await q('SELECT 0b1010') === 10);
|
|
29
|
+
ok('#118 SELECT 0b1111', await q('SELECT 0b1111') === 15);
|
|
30
|
+
ok('#118 SELECT 0b1010+0', await q('SELECT 0b1010+0') === 10);
|
|
31
|
+
|
|
32
|
+
// #119: BINARY / CAST AS BINARY 让 LIKE / REGEXP 大小写敏感
|
|
33
|
+
ok('#119 BINARY = 仍大小写敏感', await q("SELECT BINARY 'abc' = 'ABC'") === 0);
|
|
34
|
+
ok('#119 BINARY LIKE 大小写敏感', await q("SELECT BINARY 'abc' LIKE 'ABC'") === 0);
|
|
35
|
+
ok('#119 BINARY LIKE 反向', await q("SELECT BINARY 'ABC' LIKE 'abc'") === 0);
|
|
36
|
+
ok('#119 BINARY REGEXP 大小写敏感', await q("SELECT BINARY 'a' REGEXP 'A'") === 0);
|
|
37
|
+
ok('#119 CAST AS BINARY LIKE', await q("SELECT CAST('abc' AS BINARY) LIKE 'ABC'") === 0);
|
|
38
|
+
ok('#119 普通 LIKE 仍不敏感', await q("SELECT 'abc' LIKE 'ABC'") === 1);
|
|
39
|
+
|
|
40
|
+
// #125: PI()
|
|
41
|
+
ok('#125 PI()', Math.abs(await q('SELECT PI()') - Math.PI) < 1e-12);
|
|
42
|
+
|
|
43
|
+
// #129: TIMESTAMPDIFF 负差值向零截断
|
|
44
|
+
ok('#129 YEAR 官方示例', await q("SELECT TIMESTAMPDIFF(YEAR,'2002-05-01','2001-01-01')") === -1);
|
|
45
|
+
ok('#129 DAY', await q("SELECT TIMESTAMPDIFF(DAY,'2024-01-02 12:00:00','2024-01-01 00:00:00')") === -1);
|
|
46
|
+
ok('#129 HOUR', await q("SELECT TIMESTAMPDIFF(HOUR,'2024-01-01 01:30:00','2024-01-01 00:00:00')") === -1);
|
|
47
|
+
ok('#129 正差值不变', await q("SELECT TIMESTAMPDIFF(YEAR,'2001-01-01','2002-05-01')") === 1);
|
|
48
|
+
|
|
49
|
+
// #130: MAKEDATE dayofyear<=0 返回 NULL
|
|
50
|
+
ok('#130 MAKEDATE(y,0)', await q('SELECT MAKEDATE(2011,0)') === null);
|
|
51
|
+
ok('#130 MAKEDATE(y,-1)', await q('SELECT MAKEDATE(2024,-1)') === null);
|
|
52
|
+
|
|
53
|
+
// #131: MOD(bigint, 小数)
|
|
54
|
+
ok('#131 MOD(bigint,0.5)', await q('SELECT MOD(9007199254740993,0.5)') === 0);
|
|
55
|
+
ok('#131 MOD(bigint,2.5)', await q('SELECT MOD(9007199254740993,2.5)') === 0.5);
|
|
56
|
+
|
|
57
|
+
// #132: NULLIF 跨类型等值
|
|
58
|
+
ok('#132 NULLIF(1,1)', await q("SELECT NULLIF(1,'1')") === null);
|
|
59
|
+
ok("#132 NULLIF('1',1)", await q("SELECT NULLIF('1',1)") === null);
|
|
60
|
+
ok('#132 NULLIF(1,2) 不相等保留原值', await q('SELECT NULLIF(1,2)') === 1);
|
|
61
|
+
|
|
62
|
+
// #133: STR_TO_DATE 非法日历日期
|
|
63
|
+
ok('#133 2024-02-30', await q("SELECT STR_TO_DATE('2024-02-30','%Y-%m-%d')") === null);
|
|
64
|
+
ok('#133 2024-13-01', await q("SELECT STR_TO_DATE('2024-13-01','%Y-%m-%d')") === null);
|
|
65
|
+
ok('#133 13:00 PM', await q("SELECT STR_TO_DATE('13:00 PM','%h:%i %p')") === null);
|
|
66
|
+
ok('#133 合法日期仍可解析', await q("SELECT STR_TO_DATE('2024-02-29','%Y-%m-%d')") === '2024-02-29');
|
|
67
|
+
|
|
68
|
+
// #134: TRUNCATE/ROUND BigInt 第二参数
|
|
69
|
+
ok('#134 TRUNCATE(bigint,-2)', await q('SELECT TRUNCATE(9007199254740993,-2)') === '9007199254740900');
|
|
70
|
+
ok('#134 ROUND(bigint,-2)', await q('SELECT ROUND(9007199254740993,-2)') === '9007199254741000');
|
|
71
|
+
ok('#134 TRUNCATE(number,-2)', await q('SELECT TRUNCATE(123456789,-2)') === 123456700);
|
|
72
|
+
|
|
73
|
+
// #135: CONV 负数按 64 位补码
|
|
74
|
+
ok('#135 CONV(-1,10,2)', await q('SELECT CONV(-1,10,2)') === '1'.repeat(64));
|
|
75
|
+
ok('#135 CONV(-10,10,16)', await q('SELECT CONV(-10,10,16)') === 'FFFFFFFFFFFFFFF6');
|
|
76
|
+
ok('#135 CONV(255,10,16)', await q('SELECT CONV(255,10,16)') === 'FF');
|
|
77
|
+
|
|
78
|
+
// #136: TRIM 省略 remstr
|
|
79
|
+
ok('#136 TRIM(LEADING FROM)', await q("SELECT TRIM(LEADING FROM ' x ')") === 'x ');
|
|
80
|
+
ok('#136 TRIM(TRAILING FROM)', await q("SELECT TRIM(TRAILING FROM ' x ')") === ' x');
|
|
81
|
+
ok('#136 TRIM(BOTH FROM)', await q("SELECT TRIM(BOTH FROM ' x ')") === 'x');
|
|
82
|
+
ok('#136 TRIM(LEADING rem FROM) 仍正常', await q("SELECT TRIM(LEADING 'x' FROM 'xxxabcxxx')") === 'abcxxx');
|
|
83
|
+
|
|
84
|
+
console.log(`\n${pass} passed, ${fail} failed`);
|
|
85
|
+
process.exitCode = fail ? 1 : 0;
|
|
86
|
+
})().catch(e => { console.error(e); process.exitCode = 1; });
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/* 回归测试:issue #127 live 新建大表也要挂行级 LRU(rowCache) */
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const os = require('os');
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const ROOT = path.join(__dirname, '..');
|
|
6
|
+
const Database = require(path.join(ROOT, 'lib', 'database'));
|
|
7
|
+
|
|
8
|
+
let pass = 0, fail = 0;
|
|
9
|
+
function ok(name, cond, got) {
|
|
10
|
+
if (cond) { pass++; console.log('[OK] ' + name); }
|
|
11
|
+
else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
(async () => {
|
|
15
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-issue127-'));
|
|
16
|
+
const db = new Database(dir, { mode: 'hybrid', flushInterval: 0 });
|
|
17
|
+
await db.createTable('t', {
|
|
18
|
+
id: { type: 'integer', primaryKey: true, autoIncrement: true },
|
|
19
|
+
v: { type: 'integer' },
|
|
20
|
+
});
|
|
21
|
+
const rows = [];
|
|
22
|
+
for (let i = 1; i <= 1500; i++) rows.push({ v: i });
|
|
23
|
+
await db.insertMany('t', rows);
|
|
24
|
+
await db.flush();
|
|
25
|
+
|
|
26
|
+
const table = db._tables['t'];
|
|
27
|
+
ok('#127 live 大表挂上 rowCache', !!table._rowCache);
|
|
28
|
+
ok('#127 数据量正确', table.find().length === 1500);
|
|
29
|
+
ok('#127 淘汰前可读', table.find({ v: 1234 })[0].v === 1234);
|
|
30
|
+
|
|
31
|
+
const evicted = table._evictRows(Infinity);
|
|
32
|
+
ok('#127 行级 LRU 可逐行淘汰', evicted === 1500, evicted);
|
|
33
|
+
ok('#127 淘汰后回读正确', table.find({ v: 1234 })[0].v === 1234);
|
|
34
|
+
|
|
35
|
+
await db.close();
|
|
36
|
+
console.log(`\n${pass} passed, ${fail} failed`);
|
|
37
|
+
process.exitCode = fail ? 1 : 0;
|
|
38
|
+
})().catch(e => { console.error(e); process.exitCode = 1; });
|