jsql-neo 6.8.0 → 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/mongo_server.js +60 -30
- package/lib/native_client.js +26 -0
- package/lib/objectid.js +22 -1
- package/lib/sql.js +129 -30
- package/lib/table.js +78 -27
- 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 +4 -4
- package/postinstall.js +27 -32
- package/test/issue-118-136.test.js +86 -0
- package/test/issue-127.test.js +38 -0
- package/test/mongo-arrays.test.js +175 -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/mongo_server.js
CHANGED
|
@@ -15,7 +15,7 @@ const fs = require('fs');
|
|
|
15
15
|
const path = require('path');
|
|
16
16
|
const zlib = require('zlib');
|
|
17
17
|
const Database = require('./database');
|
|
18
|
-
const { ObjectId, valuesEqual, arrayIncludesValue, mapKey } = require('./objectid');
|
|
18
|
+
const { ObjectId, valuesEqual, arrayIncludesValue, mapKey, orAnyElement, anyElementRange } = require('./objectid');
|
|
19
19
|
|
|
20
20
|
const OP_MSG = 2013;
|
|
21
21
|
const OP_COMPRESSED = 2012;
|
|
@@ -148,6 +148,30 @@ function bsonReadValue(buf, pos, type, end) {
|
|
|
148
148
|
}
|
|
149
149
|
}
|
|
150
150
|
|
|
151
|
+
/* ------------------------------------------------------------------ */
|
|
152
|
+
/* 排序(find 与 aggregate $sort 共用) */
|
|
153
|
+
/* ------------------------------------------------------------------ */
|
|
154
|
+
|
|
155
|
+
function sortRows(rows, sortSpec) {
|
|
156
|
+
const sortKeys = Object.entries(sortSpec);
|
|
157
|
+
return [...rows].sort((a, b) => {
|
|
158
|
+
for (const [k, dir] of sortKeys) {
|
|
159
|
+
const av = a[k]; const bv = b[k];
|
|
160
|
+
// valuesEqual:同字节 ObjectId 不 ===,缺这一道相等短路时
|
|
161
|
+
// 相等键会破坏排序稳定性(sort+skip/limit 分页会丢/重文档)
|
|
162
|
+
if (av === bv || valuesEqual(av, bv)) continue;
|
|
163
|
+
const desc = Number(dir) < 0;
|
|
164
|
+
// Issue #47:NULL 的位置随排序方向走(升序在前、降序在后),
|
|
165
|
+
// 与 MongoDB 一致;此前固定返回 1/-1,升序时 null 恒排最后。
|
|
166
|
+
if (av == null) return desc ? 1 : -1;
|
|
167
|
+
if (bv == null) return desc ? -1 : 1;
|
|
168
|
+
const cmp = av < bv ? -1 : 1;
|
|
169
|
+
return desc ? -cmp : cmp;
|
|
170
|
+
}
|
|
171
|
+
return 0;
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
151
175
|
/* ------------------------------------------------------------------ */
|
|
152
176
|
/* Server */
|
|
153
177
|
/* ------------------------------------------------------------------ */
|
|
@@ -484,7 +508,10 @@ class MongoServer {
|
|
|
484
508
|
const coll = String(doc.findAndModify);
|
|
485
509
|
const engine = await this._ensureCollection(coll, this._dbOf(doc));
|
|
486
510
|
const q = doc.query || {};
|
|
487
|
-
|
|
511
|
+
let rows = await this._matching(engine, coll, q);
|
|
512
|
+
if (doc.sort && typeof doc.sort === 'object' && !Array.isArray(doc.sort)) {
|
|
513
|
+
rows = sortRows(rows, doc.sort);
|
|
514
|
+
}
|
|
488
515
|
const found = rows[0] || null;
|
|
489
516
|
const set = doc.update && doc.update.$set ? doc.update.$set : (doc.update || {});
|
|
490
517
|
let value = null;
|
|
@@ -535,6 +562,10 @@ class MongoServer {
|
|
|
535
562
|
const coll = String(doc.find);
|
|
536
563
|
const engine = await this._ensureCollection(coll, this._dbOf(doc));
|
|
537
564
|
let rows = await this._matching(engine, coll, doc.filter);
|
|
565
|
+
// sort 必须先于 skip/limit:否则分页取到的是存储顺序的页
|
|
566
|
+
if (doc.sort && typeof doc.sort === 'object' && !Array.isArray(doc.sort)) {
|
|
567
|
+
rows = sortRows(rows, doc.sort);
|
|
568
|
+
}
|
|
538
569
|
const skip = typeof doc.skip === 'number' ? doc.skip : 0;
|
|
539
570
|
if (skip > 0) rows = rows.slice(skip);
|
|
540
571
|
const limit = typeof doc.limit === 'number' ? doc.limit : 0;
|
|
@@ -606,23 +637,7 @@ class MongoServer {
|
|
|
606
637
|
else if (stage.$limit) rows = rows.slice(0, stage.$limit);
|
|
607
638
|
else if (stage.$skip) rows = rows.slice(Number(stage.$skip) || 0);
|
|
608
639
|
else if (stage.$sort) {
|
|
609
|
-
|
|
610
|
-
rows = [...rows].sort((a, b) => {
|
|
611
|
-
for (const [k, dir] of sortKeys) {
|
|
612
|
-
const av = a[k]; const bv = b[k];
|
|
613
|
-
// valuesEqual:同字节 ObjectId 不 ===,缺这一道相等短路时
|
|
614
|
-
// 相等键会破坏排序稳定性(sort+skip/limit 分页会丢/重文档)
|
|
615
|
-
if (av === bv || valuesEqual(av, bv)) continue;
|
|
616
|
-
const desc = Number(dir) < 0;
|
|
617
|
-
// Issue #47:NULL 的位置随排序方向走(升序在前、降序在后),
|
|
618
|
-
// 与 MongoDB 一致;此前固定返回 1/-1,升序时 null 恒排最后。
|
|
619
|
-
if (av == null) return desc ? 1 : -1;
|
|
620
|
-
if (bv == null) return desc ? -1 : 1;
|
|
621
|
-
const cmp = av < bv ? -1 : 1;
|
|
622
|
-
return desc ? -cmp : cmp;
|
|
623
|
-
}
|
|
624
|
-
return 0;
|
|
625
|
-
});
|
|
640
|
+
rows = sortRows(rows, stage.$sort);
|
|
626
641
|
}
|
|
627
642
|
else if (stage.$project) {
|
|
628
643
|
const proj = stage.$project;
|
|
@@ -806,6 +821,17 @@ class MongoServer {
|
|
|
806
821
|
if (ids.length > 0) await engine.removeByIds(coll, ids);
|
|
807
822
|
}
|
|
808
823
|
|
|
824
|
+
/** $elemMatch 单元素求值:对象元素按子文档匹配;标量/数组元素只在操作符条件下可能命中 */
|
|
825
|
+
_elemMatches(el, cond) {
|
|
826
|
+
if (el !== null && typeof el === 'object' && !Array.isArray(el)) return this._match(el, cond);
|
|
827
|
+
// 标量元素:{$elemMatch:{$gt:5}} 这类操作符条件包成 {_val: el} 求值;
|
|
828
|
+
// {$elemMatch:{k:1}} 这类子文档条件对标量元素恒为 false。
|
|
829
|
+
if (!cond || typeof cond !== 'object' || Array.isArray(cond)) return false;
|
|
830
|
+
const keys = Object.keys(cond);
|
|
831
|
+
return keys.length > 0 && keys.every(c => c[0] === '$')
|
|
832
|
+
&& this._match({ _val: el }, { _val: cond });
|
|
833
|
+
}
|
|
834
|
+
|
|
809
835
|
_match(row, filter) {
|
|
810
836
|
for (const [k, cond] of Object.entries(filter || {})) {
|
|
811
837
|
if (k === '$or') {
|
|
@@ -828,18 +854,22 @@ class MongoServer {
|
|
|
828
854
|
if (cond && typeof cond === 'object' && !Array.isArray(cond) && !(cond instanceof ObjectId)) {
|
|
829
855
|
for (const [op, v] of Object.entries(cond)) {
|
|
830
856
|
const rv = row[k];
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
if (op === '$
|
|
834
|
-
if (op === '$
|
|
835
|
-
if (op === '$
|
|
836
|
-
if (op === '$
|
|
837
|
-
if (op === '$
|
|
838
|
-
if (op === '$
|
|
857
|
+
// 等值/$in/$regex 家族带 Mongo 数组语义(任一元素命中即匹配),
|
|
858
|
+
// $ne/$nin 是取反;范围操作符 null/缺失永不命中,数组只按元素比。
|
|
859
|
+
if (op === '$eq' && !orAnyElement(rv, el => valuesEqual(el, v))) return false;
|
|
860
|
+
if (op === '$ne' && orAnyElement(rv, el => valuesEqual(el, v))) return false;
|
|
861
|
+
if (op === '$gt' && !anyElementRange(rv, el => el > v)) return false;
|
|
862
|
+
if (op === '$gte' && !anyElementRange(rv, el => el >= v)) return false;
|
|
863
|
+
if (op === '$lt' && !anyElementRange(rv, el => el < v)) return false;
|
|
864
|
+
if (op === '$lte' && !anyElementRange(rv, el => el <= v)) return false;
|
|
865
|
+
if (op === '$in' && !(Array.isArray(v) && orAnyElement(rv, el => arrayIncludesValue(v, el)))) return false;
|
|
866
|
+
if (op === '$nin' && !(Array.isArray(v) && !orAnyElement(rv, el => arrayIncludesValue(v, el)))) return false;
|
|
839
867
|
if (op === '$exists' && (v ? (rv === undefined) : (rv !== undefined))) return false;
|
|
868
|
+
if (op === '$all' && !(Array.isArray(v) && v.every(t => orAnyElement(rv, el => valuesEqual(el, t))))) return false;
|
|
840
869
|
if (op === '$regex') {
|
|
841
870
|
const flags = String(cond.$options || '').includes('i') ? 'i' : '';
|
|
842
|
-
|
|
871
|
+
const re = new RegExp(String(v), flags);
|
|
872
|
+
if (!orAnyElement(rv, el => typeof el === 'string' && re.test(el))) return false;
|
|
843
873
|
}
|
|
844
874
|
if (op === '$type') {
|
|
845
875
|
if (v === 'objectId') { if (!(rv instanceof ObjectId)) return false; continue; }
|
|
@@ -847,9 +877,9 @@ class MongoServer {
|
|
|
847
877
|
if (typeof rv !== t) return false;
|
|
848
878
|
}
|
|
849
879
|
if (op === '$size' && !(Array.isArray(rv) && rv.length === v)) return false;
|
|
850
|
-
if (op === '$elemMatch' && !(Array.isArray(rv) && rv.some((el) => this.
|
|
880
|
+
if (op === '$elemMatch' && !(Array.isArray(rv) && rv.some((el) => this._elemMatches(el, v)))) return false;
|
|
851
881
|
}
|
|
852
|
-
} else if (!
|
|
882
|
+
} else if (!orAnyElement(row[k], (el) => valuesEqual(el, cond))) {
|
|
853
883
|
return false;
|
|
854
884
|
}
|
|
855
885
|
}
|
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/objectid.js
CHANGED
|
@@ -82,6 +82,27 @@ function arrayIncludesValue(arr, v) {
|
|
|
82
82
|
return false;
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
+
/**
|
|
86
|
+
* Mongo 数组字段语义(table.js / mongo_server.js 共用):
|
|
87
|
+
* 标量条件在字段值本身命中,或数组字段时任一元素命中,都算匹配。
|
|
88
|
+
* {tags: "a"} / {$in} / {$eq} / {$regex} 走这条;$ne/$nin 是它的取反。
|
|
89
|
+
*/
|
|
90
|
+
function orAnyElement(value, pred) {
|
|
91
|
+
if (Array.isArray(value)) return pred(value) || value.some(pred);
|
|
92
|
+
return pred(value);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Mongo 范围语义:null/缺失永不参与比较(JS 的 null > -1 是 true,属
|
|
97
|
+
* 强制转换陷阱);数组字段只按元素比较(数组整体的 >/< 是字符串拼接
|
|
98
|
+
* 后的比较,无意义)。
|
|
99
|
+
*/
|
|
100
|
+
function anyElementRange(value, pred) {
|
|
101
|
+
if (value === null || value === undefined) return false;
|
|
102
|
+
if (Array.isArray(value)) return value.some(el => el !== null && el !== undefined && pred(el));
|
|
103
|
+
return pred(value);
|
|
104
|
+
}
|
|
105
|
+
|
|
85
106
|
/**
|
|
86
107
|
* Map/Set 的规范键:同字节 ObjectId 归并为同一键,且不与任何真实 BSON
|
|
87
108
|
* 字符串冲突 —— BSON 的 cstring/string 以 \0 结尾,wire 上不可能出现含
|
|
@@ -91,4 +112,4 @@ function mapKey(v) {
|
|
|
91
112
|
return v instanceof ObjectId ? '\0oid:' + v.toString() : v;
|
|
92
113
|
}
|
|
93
114
|
|
|
94
|
-
module.exports = { ObjectId, valuesEqual, arrayIncludesValue, mapKey };
|
|
115
|
+
module.exports = { ObjectId, valuesEqual, arrayIncludesValue, mapKey, orAnyElement, anyElementRange };
|
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
|
}
|