jsql-neo 6.6.3 → 6.6.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/index.js +1 -1
- package/lib/sql.js +202 -77
- package/package.json +3 -3
- package/test/bigint-math.test.js +63 -0
- package/test/issue-101-103.test.js +204 -0
- package/test/issue-105.test.js +87 -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.6.
|
|
6
|
+
> **v6.6.5** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
|
|
7
7
|
|
|
8
8
|

|
|
9
9
|

|
package/index.js
CHANGED
package/lib/sql.js
CHANGED
|
@@ -179,30 +179,35 @@ function nameOfToken(t) {
|
|
|
179
179
|
* 但此前把 '$' 开头的路径当成字面键名去取(v['$.name']),永远取不到 ——
|
|
180
180
|
* 所以抽出来共用,避免两处实现漂移。
|
|
181
181
|
*/
|
|
182
|
-
function jsonPathGet(data, path) {
|
|
182
|
+
function jsonPathGet(data, path, notFound) {
|
|
183
|
+
// notFound 哨兵:调用方需要区分「路径不存在」与「该路径的值恰好是 JSON null」时
|
|
184
|
+
// 传入一个私有对象;默认仍返回 null,保持 JSON_EXTRACT 等既有行为不变。
|
|
185
|
+
const miss = arguments.length >= 3 ? notFound : null;
|
|
183
186
|
const p = path == null ? '' : String(path);
|
|
184
187
|
if (p === '$' || p === '') return data;
|
|
185
|
-
|
|
186
|
-
|
|
188
|
+
// 支持 $.a.b、$[1]、$.a[0]。此前 /^\$\.?([^.\[]+)/ 要求 $ 后必须紧跟
|
|
189
|
+
// 非 '[' 的字符,导致纯数组索引 $[1] 被直接判为找不到。
|
|
190
|
+
const m = p.match(/^\$(?:\.|\[|$)/);
|
|
191
|
+
if (!m) return miss;
|
|
187
192
|
let current = data;
|
|
188
193
|
for (const seg of p.replace(/^\$\.?/, '').split('.')) {
|
|
189
|
-
if (current === null || current === undefined) return
|
|
194
|
+
if (current === null || current === undefined) return miss;
|
|
190
195
|
const arrMatch = seg.match(/^([^\[]*)\[(\d+)\]$/);
|
|
191
196
|
if (arrMatch) {
|
|
192
197
|
const key = arrMatch[1];
|
|
193
198
|
const idx = parseInt(arrMatch[2], 10);
|
|
194
199
|
if (key) {
|
|
195
|
-
if (typeof current !== 'object' || current === null) return
|
|
200
|
+
if (typeof current !== 'object' || current === null) return miss;
|
|
196
201
|
current = current[key];
|
|
197
202
|
}
|
|
198
|
-
if (!Array.isArray(current)) return
|
|
203
|
+
if (!Array.isArray(current)) return miss;
|
|
199
204
|
current = current[idx];
|
|
200
205
|
} else {
|
|
201
|
-
if (typeof current !== 'object' || current === null) return
|
|
206
|
+
if (typeof current !== 'object' || current === null) return miss;
|
|
202
207
|
current = current[seg];
|
|
203
208
|
}
|
|
204
209
|
}
|
|
205
|
-
return current === undefined ?
|
|
210
|
+
return current === undefined ? miss : current;
|
|
206
211
|
}
|
|
207
212
|
|
|
208
213
|
/**
|
|
@@ -3356,6 +3361,11 @@ function numericIfNumeric(v) {
|
|
|
3356
3361
|
*/
|
|
3357
3362
|
function mysqlNum(v) {
|
|
3358
3363
|
if (typeof v === 'number') return Number.isFinite(v) ? v : 0;
|
|
3364
|
+
// BigInt 是 issue #38 用来保 >2^53 整数精度的内部表示。此前没有这个分支,
|
|
3365
|
+
// 会掉到最后的 `return 0` —— 于是 SELECT -9223372036854775807 静默变成 0。
|
|
3366
|
+
// 这里转成 number 会让超出 2^53 的值丢精度,但至少不再是「悄悄变 0」;
|
|
3367
|
+
// 需要精确保留的一元负号路径在 case 'negate' 里单独短路。
|
|
3368
|
+
if (typeof v === 'bigint') return Number(v);
|
|
3359
3369
|
if (typeof v === 'boolean') return v ? 1 : 0;
|
|
3360
3370
|
if (typeof v === 'string') {
|
|
3361
3371
|
const m = v.trim().match(/^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?/);
|
|
@@ -3452,6 +3462,30 @@ function bigintExactArith(l, r, op) {
|
|
|
3452
3462
|
}
|
|
3453
3463
|
}
|
|
3454
3464
|
|
|
3465
|
+
/**
|
|
3466
|
+
* 统一的 SQL 标量排序比较器(普通 ORDER BY / 窗口函数 / 组合查询共用,#103)。
|
|
3467
|
+
*
|
|
3468
|
+
* NULL 排序策略:ASC 时 NULL 排在最前,DESC 时 NULL 排在最后
|
|
3469
|
+
* (MySQL / SQLite 的默认语义)。此前窗口函数的比较器把 NULL 硬编码成
|
|
3470
|
+
* 恒小,于是 ORDER BY col DESC 时 NULL 跑到最前,与普通 SELECT 的 ORDER BY
|
|
3471
|
+
* 不一致;抽成一个函数后两条排序路径不会再各写一套。
|
|
3472
|
+
*/
|
|
3473
|
+
function compareSqlValues(av, bv, dir) {
|
|
3474
|
+
const desc = dir === 'desc';
|
|
3475
|
+
if (av === bv) return 0;
|
|
3476
|
+
const aNull = av === null || av === undefined;
|
|
3477
|
+
const bNull = bv === null || bv === undefined;
|
|
3478
|
+
if (aNull || bNull) {
|
|
3479
|
+
if (aNull && bNull) return 0;
|
|
3480
|
+
const r = aNull ? -1 : 1;
|
|
3481
|
+
return desc ? -r : r;
|
|
3482
|
+
}
|
|
3483
|
+
const r = typeof av === 'number' && typeof bv === 'number'
|
|
3484
|
+
? av - bv
|
|
3485
|
+
: (String(av) < String(bv) ? -1 : String(av) > String(bv) ? 1 : 0);
|
|
3486
|
+
return desc ? -r : r;
|
|
3487
|
+
}
|
|
3488
|
+
|
|
3455
3489
|
function resolveOperand(operand, row, ctx) {
|
|
3456
3490
|
if (operand === null || operand === undefined) return null;
|
|
3457
3491
|
if (typeof operand === 'string') return resolveOperand({ type: 'column', name: operand }, row, ctx);
|
|
@@ -3583,6 +3617,10 @@ function resolveOperand(operand, row, ctx) {
|
|
|
3583
3617
|
case 'negate': {
|
|
3584
3618
|
const v = resolveOperand(operand.operand, row, ctx);
|
|
3585
3619
|
if (v === null || v === undefined) return null;
|
|
3620
|
+
// 保精度:大整数是 BigInt,直接取负仍然是 BigInt,交给
|
|
3621
|
+
// finalizeResultBigInts 转成字符串输出,与正数路径一致。
|
|
3622
|
+
// 走 mysqlNum 会先转成 number,把 >2^53 的值弄丢精度。
|
|
3623
|
+
if (typeof v === 'bigint') return operand.positive ? v : -v;
|
|
3586
3624
|
const n = mysqlNum(v);
|
|
3587
3625
|
return operand.positive ? n : -n;
|
|
3588
3626
|
}
|
|
@@ -3966,6 +4004,20 @@ function pgAge(from, to) {
|
|
|
3966
4004
|
function finiteOrNull(x) {
|
|
3967
4005
|
return (typeof x === 'number' && !Number.isFinite(x)) ? null : x;
|
|
3968
4006
|
}
|
|
4007
|
+
|
|
4008
|
+
/** 整数语义、必须用 BigInt 精确算的数学函数(见 applyScalarFunction)。 */
|
|
4009
|
+
const INTEGER_MATH_FNS = new Set([
|
|
4010
|
+
'ABS', 'SIGN', 'FLOOR', 'CEIL', 'CEILING', 'ROUND', 'TRUNCATE', 'MOD',
|
|
4011
|
+
'POWER', 'POW',
|
|
4012
|
+
]);
|
|
4013
|
+
|
|
4014
|
+
/** 入参需要 number(不能是 BigInt)的数学标量函数,见 applyScalarFunction。 */
|
|
4015
|
+
const MATH_SCALAR_FNS = new Set([
|
|
4016
|
+
'ABS', 'SIGN', 'SQRT', 'POWER', 'POW', 'FLOOR', 'CEIL', 'CEILING', 'MOD',
|
|
4017
|
+
'ROUND', 'TRUNCATE', 'LOG', 'LOG10', 'LOG2', 'LN', 'EXP',
|
|
4018
|
+
'SIN', 'COS', 'TAN', 'ASIN', 'ACOS', 'ATAN', 'ATAN2',
|
|
4019
|
+
'DEGREES', 'RADIANS', 'COT',
|
|
4020
|
+
]);
|
|
3969
4021
|
function applyScalarFunction(fnNode, row, ctx) {
|
|
3970
4022
|
const name = (fnNode.name || '').toUpperCase();
|
|
3971
4023
|
const rawArgs = fnNode.args || [];
|
|
@@ -3973,6 +4025,41 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
3973
4025
|
const args = rawArgs.map(a => (a && a.type === 'interval')
|
|
3974
4026
|
? { __interval: true, value: a.value, unit: a.unit }
|
|
3975
4027
|
: resolveOperand(a, row, ctx));
|
|
4028
|
+
|
|
4029
|
+
// >2^53 的整数在 jsql 内部是 BigInt(issue #38)。Math.* 不接受 BigInt,
|
|
4030
|
+
// 直接传会抛 "Cannot convert a BigInt value to a number";一律降级成
|
|
4031
|
+
// number 又会把 MOD(9007199254740993, 2) 算成 0(正确是 1)—— 静默错值
|
|
4032
|
+
// 比抛错更糟。所以分两类:
|
|
4033
|
+
// a) 整数语义的函数走 BigInt 精确路径,保留精度;
|
|
4034
|
+
// b) 真正的浮点运算(SQRT/LOG/三角…)降级为 number,MySQL 下本就返回 DOUBLE。
|
|
4035
|
+
if (args.length && args.some(a => typeof a === 'bigint') && INTEGER_MATH_FNS.has(name)) {
|
|
4036
|
+
const v = args[0];
|
|
4037
|
+
if (typeof v === 'bigint') {
|
|
4038
|
+
switch (name) {
|
|
4039
|
+
case 'ABS': return v < 0n ? -v : v;
|
|
4040
|
+
case 'SIGN': return v > 0n ? 1 : (v < 0n ? -1 : 0);
|
|
4041
|
+
case 'FLOOR': case 'CEIL': case 'CEILING': case 'ROUND': case 'TRUNCATE':
|
|
4042
|
+
return v; // 整数本身就是它的 floor/ceil/round
|
|
4043
|
+
case 'MOD': {
|
|
4044
|
+
const d = args[1];
|
|
4045
|
+
if (d == null || d === 0 || d === 0n) return null;
|
|
4046
|
+
return v % (typeof d === 'bigint' ? d : BigInt(Math.trunc(Number(d))));
|
|
4047
|
+
}
|
|
4048
|
+
case 'POWER': case 'POW': {
|
|
4049
|
+
const e = args[1];
|
|
4050
|
+
if (typeof e === 'bigint' || (typeof e === 'number' && Number.isInteger(e) && e >= 0)) {
|
|
4051
|
+
return v ** BigInt(e);
|
|
4052
|
+
}
|
|
4053
|
+
break; // 非整数指数 → 落到下面的浮点路径
|
|
4054
|
+
}
|
|
4055
|
+
}
|
|
4056
|
+
}
|
|
4057
|
+
}
|
|
4058
|
+
if (MATH_SCALAR_FNS.has(name)) {
|
|
4059
|
+
for (let i = 0; i < args.length; i++) {
|
|
4060
|
+
if (typeof args[i] === 'bigint') args[i] = Number(args[i]);
|
|
4061
|
+
}
|
|
4062
|
+
}
|
|
3976
4063
|
const session = ctx && ctx.session;
|
|
3977
4064
|
if (ctx && ctx.functions && Object.prototype.hasOwnProperty.call(ctx.functions, name)) {
|
|
3978
4065
|
return ctx.functions[name].apply(null, args);
|
|
@@ -4856,10 +4943,14 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4856
4943
|
if (typeof json === 'string') {
|
|
4857
4944
|
try { data = JSON.parse(json); } catch (e) { return null; }
|
|
4858
4945
|
}
|
|
4859
|
-
|
|
4946
|
+
// MySQL 的 search_str 是 **LIKE 模式**(% 任意串、_ 单字符,\ 转义),
|
|
4947
|
+
// 且 JSON_SEARCH 大小写敏感(#105)。旧实现用 String.includes +
|
|
4948
|
+
// toLowerCase:既不支持通配符,又把 'hello' 错配到 'Hello'。
|
|
4949
|
+
// 复用 likeMatch(ci=false),与 SQL 的 LIKE 语义保持一致。
|
|
4950
|
+
const searchStr = String(search);
|
|
4860
4951
|
const results = [];
|
|
4861
4952
|
function searchObj(obj, currentPath) {
|
|
4862
|
-
if (typeof obj === 'string' && obj
|
|
4953
|
+
if (typeof obj === 'string' && likeMatch(obj, searchStr, false) === true) {
|
|
4863
4954
|
results.push(currentPath);
|
|
4864
4955
|
} else if (Array.isArray(obj)) {
|
|
4865
4956
|
obj.forEach((item, i) => searchObj(item, currentPath + '[' + i + ']'));
|
|
@@ -4875,15 +4966,38 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4875
4966
|
return results;
|
|
4876
4967
|
}
|
|
4877
4968
|
case 'JSON_CONTAINS': {
|
|
4878
|
-
// JSON_CONTAINS(
|
|
4969
|
+
// MySQL: JSON_CONTAINS(target, candidate[, path]) → 1 / 0
|
|
4970
|
+
//
|
|
4971
|
+
// 旧实现是 `JSON.stringify(data).includes(JSON.stringify(val))`,
|
|
4972
|
+
// 有两个错(#105):
|
|
4973
|
+
// 1. candidate 是 JSON 文本,从未被解析 —— '2' 一直是字符串 "2",
|
|
4974
|
+
// 所以 '[1,2,3]' 里找不到 '"2"';只有数值字面量 2 碰巧能命中。
|
|
4975
|
+
// 2. 可选的第三个 path 参数被完全忽略。
|
|
4976
|
+
// 同文件里本来就有正确的 jsonContainsValue()(数组/对象/标量递归),
|
|
4977
|
+
// 只是这里没用。现在解析 candidate、用 jsonPathGet 应用 path,再委托它。
|
|
4879
4978
|
const json = args[0];
|
|
4880
4979
|
const val = args[1];
|
|
4881
|
-
|
|
4980
|
+
const path = args[2];
|
|
4981
|
+
if (json == null || val === undefined) return null;
|
|
4882
4982
|
let data = json;
|
|
4883
4983
|
if (typeof json === 'string') {
|
|
4884
4984
|
try { data = JSON.parse(json); } catch (e) { return null; }
|
|
4885
4985
|
}
|
|
4886
|
-
|
|
4986
|
+
if (path != null && String(path) !== '$' && String(path) !== '') {
|
|
4987
|
+
// 用哨兵区分「路径不存在」和「该路径的值恰好是 JSON null」。
|
|
4988
|
+
// jsonPathGet 默认把两者都返回 null;直接判 === null 会把合法的
|
|
4989
|
+
// JSON null 误判成找不到(JSON_CONTAINS('{"a":null}','null','$.a')
|
|
4990
|
+
// 会错返回 0)。
|
|
4991
|
+
const MISSING = {};
|
|
4992
|
+
const sliced = jsonPathGet(data, String(path), MISSING);
|
|
4993
|
+
if (sliced === MISSING) return 0;
|
|
4994
|
+
data = sliced;
|
|
4995
|
+
}
|
|
4996
|
+
let candidate = val;
|
|
4997
|
+
if (typeof val === 'string') {
|
|
4998
|
+
try { candidate = JSON.parse(val); } catch (e) { /* 非法 JSON 文本按字面字符串处理 */ }
|
|
4999
|
+
}
|
|
5000
|
+
return jsonContainsValue(data, candidate) ? 1 : 0;
|
|
4887
5001
|
}
|
|
4888
5002
|
default:
|
|
4889
5003
|
return null;
|
|
@@ -4960,9 +5074,12 @@ function jsonContainsValue(container, target) {
|
|
|
4960
5074
|
if (container === null || typeof container !== 'object' || Array.isArray(container)) return false;
|
|
4961
5075
|
return Object.keys(target).every(k => Object.prototype.hasOwnProperty.call(container, k) && jsonContainsValue(container[k], target[k]));
|
|
4962
5076
|
}
|
|
4963
|
-
|
|
5077
|
+
// JSON 包含是**类型敏感**的:数字 2 与字符串 "2" 是不同值(MySQL / PG
|
|
5078
|
+
// 都如此)。此前用 String(c) === String(target) 做宽松比较,导致
|
|
5079
|
+
// JSON_CONTAINS('[1,2,3]', '"2"') 错返回 1。PG 的 @> 同样受益于此修正。
|
|
5080
|
+
if (Array.isArray(container)) return container.some(c => c === target);
|
|
4964
5081
|
if (container !== null && typeof container === 'object') return false;
|
|
4965
|
-
return container === target
|
|
5082
|
+
return container === target;
|
|
4966
5083
|
}
|
|
4967
5084
|
|
|
4968
5085
|
/** JSON 键存在(PG 的 ? / ?| / ?&)。keys 为单个键名或 '{a,b}' 形式的键列表。 */
|
|
@@ -7930,11 +8047,8 @@ class SQLExecutor {
|
|
|
7930
8047
|
for (const o of orderBy) {
|
|
7931
8048
|
const av = resolveOperand(o.column, ra, this.ctx);
|
|
7932
8049
|
const bv = resolveOperand(o.column, rb, this.ctx);
|
|
7933
|
-
|
|
7934
|
-
if (
|
|
7935
|
-
if (bv === undefined || bv === null) return 1;
|
|
7936
|
-
const d = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv));
|
|
7937
|
-
if (d !== 0) return o.dir === 'asc' ? d : -d;
|
|
8050
|
+
const d = compareSqlValues(av, bv, o.dir);
|
|
8051
|
+
if (d !== 0) return d;
|
|
7938
8052
|
}
|
|
7939
8053
|
return ia - ib;
|
|
7940
8054
|
});
|
|
@@ -7977,16 +8091,35 @@ class SQLExecutor {
|
|
|
7977
8091
|
const argNode = toNode((w.spec && (w.spec.column || (w.spec.args && w.spec.args[0]))) || w.col.column || w.col.expr);
|
|
7978
8092
|
const valAt = (rowIdx, node) => resolveOperand(node || { type: 'value', value: 1 }, rows[rowIdx], this.ctx);
|
|
7979
8093
|
|
|
8094
|
+
// #102:RANK 值按需计算,PERCENT_RANK / CUME_DIST 复用
|
|
8095
|
+
const rankAt = (pos) => {
|
|
8096
|
+
let rank = 1;
|
|
8097
|
+
for (let k = 0; k < pos; k++) {
|
|
8098
|
+
if (this._windowPeerCmp(rows[ordered[k]], rows[ordered[pos]], orderBy, this.ctx) !== 0) rank++;
|
|
8099
|
+
}
|
|
8100
|
+
return rank;
|
|
8101
|
+
};
|
|
8102
|
+
|
|
7980
8103
|
ordered.forEach((rowIdx, pos) => {
|
|
7981
8104
|
let v = null;
|
|
7982
8105
|
switch (w.fn) {
|
|
7983
8106
|
case 'ROW_NUMBER': v = pos + 1; break;
|
|
7984
|
-
case 'RANK':
|
|
7985
|
-
|
|
7986
|
-
|
|
7987
|
-
|
|
7988
|
-
|
|
7989
|
-
|
|
8107
|
+
case 'RANK': v = rankAt(pos); break;
|
|
8108
|
+
case 'PERCENT_RANK': {
|
|
8109
|
+
// (rank - 1) / (total_rows - 1),单行 / 无 ORDER BY 分区返回 0
|
|
8110
|
+
const rank = rankAt(pos);
|
|
8111
|
+
const total = ordered.length;
|
|
8112
|
+
v = total > 1 ? (rank - 1) / (total - 1) : 0;
|
|
8113
|
+
break;
|
|
8114
|
+
}
|
|
8115
|
+
case 'CUME_DIST': {
|
|
8116
|
+
// 分区内 值 <= 当前行 的行数占比(所有 peer 同值)
|
|
8117
|
+
const total = ordered.length;
|
|
8118
|
+
const curKey = this._windowPeerKey(rows[rowIdx], orderBy, this.ctx);
|
|
8119
|
+
let end = pos;
|
|
8120
|
+
while (end + 1 < total &&
|
|
8121
|
+
this._windowPeerKey(rows[ordered[end + 1]], orderBy, this.ctx) === curKey) end++;
|
|
8122
|
+
v = total > 0 ? (end + 1) / total : null;
|
|
7990
8123
|
break;
|
|
7991
8124
|
}
|
|
7992
8125
|
case 'DENSE_RANK': {
|
|
@@ -8045,7 +8178,9 @@ class SQLExecutor {
|
|
|
8045
8178
|
|
|
8046
8179
|
_windowPeerKey(row, orderBy, ctx) {
|
|
8047
8180
|
if (!orderBy.length) return '';
|
|
8048
|
-
|
|
8181
|
+
// null 与 undefined 视为同一取值(都是 SQL NULL),否则二者会被当成不同 peer
|
|
8182
|
+
const norm = (v) => (v === null || v === undefined ? 'null' : JSON.stringify(v));
|
|
8183
|
+
return orderBy.map(o => norm(resolveOperand(o.column, row, ctx))).join('');
|
|
8049
8184
|
}
|
|
8050
8185
|
|
|
8051
8186
|
_windowPeerCmp(rowA, rowB, orderBy, ctx) {
|
|
@@ -8053,10 +8188,7 @@ class SQLExecutor {
|
|
|
8053
8188
|
for (const o of orderBy) {
|
|
8054
8189
|
const av = resolveOperand(o.column, rowA, ctx);
|
|
8055
8190
|
const bv = resolveOperand(o.column, rowB, ctx);
|
|
8056
|
-
|
|
8057
|
-
if (av === undefined || av === null) return -1;
|
|
8058
|
-
if (bv === undefined || bv === null) return 1;
|
|
8059
|
-
const d = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv));
|
|
8191
|
+
const d = compareSqlValues(av, bv, o.dir);
|
|
8060
8192
|
if (d !== 0) return d;
|
|
8061
8193
|
}
|
|
8062
8194
|
return 0;
|
|
@@ -8143,18 +8275,8 @@ class SQLExecutor {
|
|
|
8143
8275
|
};
|
|
8144
8276
|
keyed.sort((a, b) => {
|
|
8145
8277
|
for (const o of orderBy) {
|
|
8146
|
-
const
|
|
8147
|
-
|
|
8148
|
-
if (av === bv) continue;
|
|
8149
|
-
const aNull = av === null || av === undefined;
|
|
8150
|
-
const bNull = bv === null || bv === undefined;
|
|
8151
|
-
if (aNull || bNull) {
|
|
8152
|
-
const r = aNull && bNull ? 0 : (aNull ? -1 : 1);
|
|
8153
|
-
return o.dir === 'desc' ? -r : r;
|
|
8154
|
-
}
|
|
8155
|
-
const d = typeof av === 'number' && typeof bv === 'number'
|
|
8156
|
-
? av - bv : String(av).localeCompare(String(bv));
|
|
8157
|
-
if (d !== 0) return o.dir === 'desc' ? -d : d;
|
|
8278
|
+
const d = compareSqlValues(keyOf(a, o), keyOf(b, o), o.dir);
|
|
8279
|
+
if (d !== 0) return d;
|
|
8158
8280
|
}
|
|
8159
8281
|
return a.i - b.i;
|
|
8160
8282
|
});
|
|
@@ -8237,29 +8359,42 @@ class SQLExecutor {
|
|
|
8237
8359
|
all = [{ _virtual: true }];
|
|
8238
8360
|
} else {
|
|
8239
8361
|
const items = statement.from.tables.concat(statement.from.joins.map(j => j.item));
|
|
8240
|
-
//
|
|
8241
|
-
//
|
|
8242
|
-
|
|
8362
|
+
// #101:自连接(同一张表在 FROM 中出现多次)时,行前缀的分配规则:
|
|
8363
|
+
// - 显式别名优先;
|
|
8364
|
+
// - 无别名的实例默认仍用**表名**作为前缀,这样 SQL 里写的 `t.col` 才能解析到;
|
|
8365
|
+
// - 只有当这个名字已经被前面的实例占用时,才生成 t1/t2 这类自动别名,
|
|
8366
|
+
// 并且跳过所有已被显式别名占用的名字。
|
|
8367
|
+
// 此前对「同表出现多次」一律自动别名 t1/t2,导致查询里用原表名限定的
|
|
8368
|
+
// `t.id` 完全解析不到(行里只有 t1.id/t2.id),JOIN ON 恒假 → INNER 空、LEFT 全 NULL。
|
|
8369
|
+
const autoAliasMap = new Map();
|
|
8370
|
+
const usedPrefixes = new Set();
|
|
8371
|
+
// 先把显式别名登记为保留名,自动别名不能撞上
|
|
8372
|
+
const reservedPrefixes = new Set();
|
|
8243
8373
|
for (const item of items) {
|
|
8244
|
-
if (item
|
|
8245
|
-
|
|
8246
|
-
|
|
8247
|
-
}
|
|
8374
|
+
if (!item) continue;
|
|
8375
|
+
if (item.alias) reservedPrefixes.add(String(item.alias).toLowerCase());
|
|
8376
|
+
else if (item.subquery && item.subquery.alias) reservedPrefixes.add(String(item.subquery.alias).toLowerCase());
|
|
8248
8377
|
}
|
|
8249
|
-
const autoAliasMap = new Map();
|
|
8250
8378
|
let autoIdx = 0;
|
|
8379
|
+
const nextAutoAlias = () => {
|
|
8380
|
+
let name;
|
|
8381
|
+
do { autoIdx++; name = `t${autoIdx}`; }
|
|
8382
|
+
while (reservedPrefixes.has(name.toLowerCase()) || usedPrefixes.has(name.toLowerCase()));
|
|
8383
|
+
return name;
|
|
8384
|
+
};
|
|
8251
8385
|
const prefix = item => {
|
|
8252
|
-
if (item
|
|
8253
|
-
if (item
|
|
8254
|
-
|
|
8255
|
-
if (item.
|
|
8256
|
-
|
|
8257
|
-
|
|
8258
|
-
|
|
8259
|
-
|
|
8260
|
-
|
|
8261
|
-
|
|
8262
|
-
|
|
8386
|
+
if (!item) return null;
|
|
8387
|
+
if (autoAliasMap.has(item)) return autoAliasMap.get(item);
|
|
8388
|
+
let p;
|
|
8389
|
+
if (item.alias) p = item.alias;
|
|
8390
|
+
else if (item.subquery) p = item.subquery.alias || item.alias || nextAutoAlias();
|
|
8391
|
+
else if (item.table) {
|
|
8392
|
+
p = item.table;
|
|
8393
|
+
if (usedPrefixes.has(String(p).toLowerCase())) p = nextAutoAlias();
|
|
8394
|
+
} else p = nextAutoAlias();
|
|
8395
|
+
usedPrefixes.add(String(p).toLowerCase());
|
|
8396
|
+
autoAliasMap.set(item, p);
|
|
8397
|
+
return p;
|
|
8263
8398
|
};
|
|
8264
8399
|
|
|
8265
8400
|
// 读第一表
|
|
@@ -8626,13 +8761,8 @@ class SQLExecutor {
|
|
|
8626
8761
|
};
|
|
8627
8762
|
const cmp = (a, b) => {
|
|
8628
8763
|
for (const o of statement.orderBy) {
|
|
8629
|
-
const
|
|
8630
|
-
|
|
8631
|
-
if (av === bv || (av === undefined && bv === undefined)) continue;
|
|
8632
|
-
if (av === undefined || av === null) return o.dir === 'asc' ? -1 : 1;
|
|
8633
|
-
if (bv === undefined || bv === null) return o.dir === 'asc' ? 1 : -1;
|
|
8634
|
-
const r = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv));
|
|
8635
|
-
if (r !== 0) return o.dir === 'asc' ? r : -r;
|
|
8764
|
+
const r = compareSqlValues(ordVal(a.row, o), ordVal(b.row, o), o.dir);
|
|
8765
|
+
if (r !== 0) return r;
|
|
8636
8766
|
}
|
|
8637
8767
|
return 0;
|
|
8638
8768
|
};
|
|
@@ -8709,14 +8839,9 @@ class SQLExecutor {
|
|
|
8709
8839
|
const cmp = (a, b) => {
|
|
8710
8840
|
for (let i = 0; i < ordKeys.length; i++) {
|
|
8711
8841
|
const k = ordKeys[i];
|
|
8712
|
-
|
|
8713
|
-
const
|
|
8714
|
-
if (
|
|
8715
|
-
if (av === undefined || av === null) return -1 * k.dir;
|
|
8716
|
-
if (bv === undefined || bv === null) return 1 * k.dir;
|
|
8717
|
-
// P2-1: localeCompare 对字符串排序受 locale 影响,应使用简单字符串比较
|
|
8718
|
-
const r = typeof av === 'number' && typeof bv === 'number' ? av - bv : (String(av) < String(bv) ? -1 : String(av) > String(bv) ? 1 : 0);
|
|
8719
|
-
if (r !== 0) return r * k.dir;
|
|
8842
|
+
// P2-1: 字符串排序不走 localeCompare(受 locale 影响),统一在 compareSqlValues 里处理
|
|
8843
|
+
const r = compareSqlValues(k.at(a), k.at(b), k.dir === 1 ? 'asc' : 'desc');
|
|
8844
|
+
if (r !== 0) return r;
|
|
8720
8845
|
}
|
|
8721
8846
|
return 0;
|
|
8722
8847
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jsql-neo",
|
|
3
|
-
"version": "6.6.
|
|
3
|
+
"version": "6.6.5",
|
|
4
4
|
"description": "JSQL-NEO — Rust-powered embedded database with WASM, REST API, B-Tree indexes, WAL, crash recovery",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
@@ -50,12 +50,12 @@
|
|
|
50
50
|
"scripts": {
|
|
51
51
|
"postinstall": "node postinstall.js",
|
|
52
52
|
"build:native": "node scripts/build-native.js",
|
|
53
|
-
"test": "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",
|
|
53
|
+
"test": "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",
|
|
54
54
|
"test:parser": "node test/sql-parser.test.js",
|
|
55
55
|
"test:btree": "node test/btree.test.js",
|
|
56
56
|
"test:native": "node test/native.test.js",
|
|
57
57
|
"test:regress": "node test/regress-5.1.0.js",
|
|
58
|
-
"test:all": "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",
|
|
58
|
+
"test:all": "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",
|
|
59
59
|
"test:coverage": "c8 --all --include='lib/**' --exclude='lib/web_ui.js' --reporter=text --reporter=lcov node test/coverage.js",
|
|
60
60
|
"test:orms": "node examples/orms/run-all.js",
|
|
61
61
|
"test:dml": "node test/dml-constraints.test.js",
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/* ---- BigInt 在数学标量函数与一元负号里的精度回归 ---- */
|
|
2
|
+
/*
|
|
3
|
+
* 起点:SELECT -9223372036854775807 静默返回 0。
|
|
4
|
+
* 根因:mysqlNum() 没有 bigint 分支,掉到最后的 `return 0`;negate 又
|
|
5
|
+
* 把所有入参都过一遍 mysqlNum。修完后顺带发现 Math.* 不接受 BigInt
|
|
6
|
+
* (ABS/SQRT/POWER/FLOOR/CEIL/MOD 抛 TypeError),以及「一律降级 number」
|
|
7
|
+
* 会把 MOD(9007199254740993, 2) 算成 0 这种更糟的静默错值。
|
|
8
|
+
*
|
|
9
|
+
* 现在分两类:整数语义函数走 BigInt 精确路径,浮点函数降级为 DOUBLE。
|
|
10
|
+
*/
|
|
11
|
+
const path = require('path');
|
|
12
|
+
const ROOT = path.join(__dirname, '..');
|
|
13
|
+
const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
|
|
14
|
+
|
|
15
|
+
let pass = 0, fail = 0;
|
|
16
|
+
function ok(name, cond, got) {
|
|
17
|
+
if (cond) { pass++; console.log('[OK] ' + name); }
|
|
18
|
+
else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got, (k, v) => typeof v === 'bigint' ? v.toString() + 'n' : v)); }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
(async () => {
|
|
22
|
+
const db = new Database(':memory:', { autoSave: false });
|
|
23
|
+
const q = async (sql) => {
|
|
24
|
+
const r = await executeSQL(db, sql, { safety: false });
|
|
25
|
+
return r.rows[0][0];
|
|
26
|
+
};
|
|
27
|
+
const BIG = '9223372036854775807'; // int64 max
|
|
28
|
+
const ODD = '9007199254740993'; // 2^53 + 1,float64 无法精确表示
|
|
29
|
+
|
|
30
|
+
// ---------- 一元负号保精度 ----------
|
|
31
|
+
ok('正的大整数仍精确', await q(`SELECT ${BIG}`) === BIG, null);
|
|
32
|
+
ok('负的大整数精确取负(此前静默变 0)', await q(`SELECT -${BIG}`) === '-' + BIG, null);
|
|
33
|
+
ok('int64 min 取负', await q('SELECT -9223372036854775808') === '-9223372036854775808', null);
|
|
34
|
+
ok('普通负数仍是 number', await q('SELECT -5') === -5, null);
|
|
35
|
+
ok('普通负小数仍是 number', await q('SELECT -1.5') === -1.5, null);
|
|
36
|
+
|
|
37
|
+
// ---------- 整数语义的数学函数:BigInt 精确路径 ----------
|
|
38
|
+
ok('ABS 大负数精确', await q(`SELECT ABS(-${BIG})`) === BIG, null);
|
|
39
|
+
ok('ABS 普通负数', await q('SELECT ABS(-5)') === 5, null);
|
|
40
|
+
ok('SIGN 大正数', await q(`SELECT SIGN(${BIG})`) === 1, null);
|
|
41
|
+
ok('SIGN 大负数', await q(`SELECT SIGN(-${BIG})`) === -1, null);
|
|
42
|
+
ok(`MOD(${ODD}, 2) = 1(降级 number 会算成 0)`,
|
|
43
|
+
String(await q(`SELECT MOD(${ODD}, 2)`)) === '1', null);
|
|
44
|
+
ok('MOD 被自身整除 = 0', String(await q(`SELECT MOD(${ODD}, ${ODD})`)) === '0', null);
|
|
45
|
+
ok('FLOOR 大整数不变', String(await q(`SELECT FLOOR(${ODD})`)) === ODD, null);
|
|
46
|
+
ok('CEIL 大整数不变', String(await q(`SELECT CEIL(${ODD})`)) === ODD, null);
|
|
47
|
+
ok('POWER 大整数指数 1 精确', String(await q(`SELECT POWER(${ODD}, 1)`)) === ODD, null);
|
|
48
|
+
ok('MOD 除零仍 NULL', await q('SELECT MOD(5, 0)') === null, null);
|
|
49
|
+
|
|
50
|
+
// ---------- 浮点运算:降级 DOUBLE,不抛错也不静默给 0 ----------
|
|
51
|
+
const sq = await q(`SELECT SQRT(${ODD})`);
|
|
52
|
+
ok('SQRT 大整数返回有限数值', typeof sq === 'number' && Number.isFinite(sq) && sq > 0, sq);
|
|
53
|
+
const lg = await q(`SELECT LOG(${ODD})`);
|
|
54
|
+
ok('LOG 大整数不再抛 TypeError', lg === null || (typeof lg === 'number' && Number.isFinite(lg)), lg);
|
|
55
|
+
ok('#65 SQRT(-1) 仍返回 NULL', await q('SELECT SQRT(-1)') === null, null);
|
|
56
|
+
ok('#65 POWER(-2,0.5) 仍返回 NULL', await q('SELECT POWER(-2,0.5)') === null, null);
|
|
57
|
+
|
|
58
|
+
console.log(`\n${pass} passed, ${fail} failed`);
|
|
59
|
+
process.exit(fail === 0 ? 0 : 1);
|
|
60
|
+
})().catch(e => {
|
|
61
|
+
console.log('[FAIL] unexpected exception: ' + e.stack.split('\n').slice(0, 3).join('\n'));
|
|
62
|
+
process.exit(1);
|
|
63
|
+
});
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Regression tests for issues #101 / #102 / #103.
|
|
3
|
+
*
|
|
4
|
+
* node test/issue-101-103.test.js
|
|
5
|
+
*
|
|
6
|
+
* #101 自连接:左表未起别名、SQL 里用原表名(t.col)引用列
|
|
7
|
+
* → INNER JOIN 必须返回匹配行,LEFT JOIN 必须保留左表行
|
|
8
|
+
* #102 窗口函数 PERCENT_RANK() / CUME_DIST() 此前落到 default 分支恒返回 NULL
|
|
9
|
+
* #103 窗口函数 ORDER BY col DESC 的 NULL 排序必须与普通 ORDER BY 一致
|
|
10
|
+
*/
|
|
11
|
+
const path = require('path');
|
|
12
|
+
|
|
13
|
+
const ROOT = path.join(__dirname, '..');
|
|
14
|
+
const Database = require(path.join(ROOT, 'lib/database'));
|
|
15
|
+
const { executeSQL } = require(path.join(ROOT, 'lib/sql'));
|
|
16
|
+
|
|
17
|
+
let passed = 0, failed = 0;
|
|
18
|
+
function ok(name, cond, extra) {
|
|
19
|
+
if (cond) { passed++; console.log('[OK]', name); }
|
|
20
|
+
else { failed++; console.log('[FAIL]', name, extra !== undefined ? '-> ' + JSON.stringify(extra) : ''); }
|
|
21
|
+
}
|
|
22
|
+
function eq(a, b) { return JSON.stringify(a) === JSON.stringify(b); }
|
|
23
|
+
|
|
24
|
+
function near(a, b) { return typeof a === 'number' && typeof b === 'number' && Math.abs(a - b) < 1e-9; }
|
|
25
|
+
|
|
26
|
+
(async () => {
|
|
27
|
+
/* ===================== #101 自连接 ===================== */
|
|
28
|
+
{
|
|
29
|
+
const db = new Database(':memory:', { autoSave: false });
|
|
30
|
+
await executeSQL(db, 'CREATE TABLE t (id INT, v INT)');
|
|
31
|
+
await executeSQL(db, 'INSERT INTO t VALUES (1,10),(2,20),(3,30)');
|
|
32
|
+
const q = sql => executeSQL(db, sql);
|
|
33
|
+
|
|
34
|
+
let r = await q('SELECT t.id, b.id AS bid FROM t JOIN t b ON t.id = b.id ORDER BY t.id');
|
|
35
|
+
ok('#101 INNER 自连接(左表用原表名限定)返回匹配行',
|
|
36
|
+
eq(r.rows, [[1, 1], [2, 2], [3, 3]]), r.rows);
|
|
37
|
+
|
|
38
|
+
r = await q('SELECT t.id, b.id AS bid FROM t LEFT JOIN t b ON t.id = b.id ORDER BY t.id');
|
|
39
|
+
ok('#101 LEFT 自连接(左表用原表名限定)左表行保留且不全是 NULL',
|
|
40
|
+
eq(r.rows, [[1, 1], [2, 2], [3, 3]]), r.rows);
|
|
41
|
+
|
|
42
|
+
r = await q('SELECT t.id, b.v AS bv FROM t JOIN t b ON t.id = b.id - 1 ORDER BY t.id');
|
|
43
|
+
ok('#101 自连接 ON 条件不对称(b.id = t.id + 1)',
|
|
44
|
+
eq(r.rows, [[1, 20], [2, 30]]), r.rows);
|
|
45
|
+
|
|
46
|
+
r = await q('SELECT t.id, b.id AS bid FROM t LEFT JOIN t b ON t.id = b.id - 1 ORDER BY t.id');
|
|
47
|
+
ok('#101 LEFT 自连接存在未匹配行时右侧补 NULL',
|
|
48
|
+
eq(r.rows, [[1, 2], [2, 3], [3, null]]), r.rows);
|
|
49
|
+
|
|
50
|
+
// 双侧显式别名仍然正常
|
|
51
|
+
r = await q('SELECT a.id, b.id AS bid FROM t a JOIN t b ON a.id = b.id ORDER BY a.id');
|
|
52
|
+
ok('#101 双侧都起别名不受影响', eq(r.rows, [[1, 1], [2, 2], [3, 3]]), r.rows);
|
|
53
|
+
|
|
54
|
+
// 左表别名 + 右表原表名
|
|
55
|
+
r = await q('SELECT a.id, t.id AS tid FROM t a JOIN t ON a.id = t.id ORDER BY a.id');
|
|
56
|
+
ok('#101 左表别名 + 右表用原表名', eq(r.rows, [[1, 1], [2, 2], [3, 3]]), r.rows);
|
|
57
|
+
|
|
58
|
+
// 同名表三实例:第一实例用表名,后面用自动别名
|
|
59
|
+
r = await q('SELECT t.id FROM t JOIN t b ON t.id = b.id JOIN t c ON t.id = c.id ORDER BY t.id');
|
|
60
|
+
ok('#101 三个自连接实例', eq(r.rows, [[1], [2], [3]]), r.rows);
|
|
61
|
+
|
|
62
|
+
// 非自连接的表名限定引用不该受影响
|
|
63
|
+
await executeSQL(db, 'CREATE TABLE u (id INT, t_id INT)');
|
|
64
|
+
await executeSQL(db, 'INSERT INTO u VALUES (7,2),(8,3)');
|
|
65
|
+
r = await q('SELECT t.id, u.id AS uid FROM t JOIN u ON u.t_id = t.id ORDER BY t.id');
|
|
66
|
+
ok('#101 普通 JOIN 不受影响', eq(r.rows, [[2, 7], [3, 8]]), r.rows);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/* ===================== #102 PERCENT_RANK / CUME_DIST ===================== */
|
|
70
|
+
{
|
|
71
|
+
const db = new Database(':memory:', { autoSave: false });
|
|
72
|
+
await executeSQL(db, 'CREATE TABLE w (id INT, g TEXT, v INT)');
|
|
73
|
+
await executeSQL(db, "INSERT INTO w VALUES (1,'a',10),(2,'a',20),(3,'a',20),(4,'a',30),(5,'b',5)");
|
|
74
|
+
const q = sql => executeSQL(db, sql);
|
|
75
|
+
|
|
76
|
+
let r = await q("SELECT id, PERCENT_RANK() OVER (PARTITION BY g ORDER BY v) AS pr FROM w WHERE g='a' ORDER BY id");
|
|
77
|
+
ok('#102 PERCENT_RANK 含并列值',
|
|
78
|
+
eq(r.rows, [[1, 0], [2, 1 / 3], [3, 1 / 3], [4, 1]]), r.rows);
|
|
79
|
+
|
|
80
|
+
r = await q("SELECT id, CUME_DIST() OVER (PARTITION BY g ORDER BY v) AS cd FROM w WHERE g='a' ORDER BY id");
|
|
81
|
+
ok('#102 CUME_DIST 含并列值',
|
|
82
|
+
eq(r.rows, [[1, 0.25], [2, 0.75], [3, 0.75], [4, 1]]), r.rows);
|
|
83
|
+
|
|
84
|
+
// 多分区
|
|
85
|
+
r = await q('SELECT id, PERCENT_RANK() OVER (PARTITION BY g ORDER BY v) AS pr FROM w ORDER BY g, id');
|
|
86
|
+
ok('#102 PERCENT_RANK 多分区(b 分区单行 → 0)',
|
|
87
|
+
eq(r.rows, [[1, 0], [2, 1 / 3], [3, 1 / 3], [4, 1], [5, 0]]), r.rows);
|
|
88
|
+
|
|
89
|
+
r = await q('SELECT id, CUME_DIST() OVER (PARTITION BY g ORDER BY v) AS cd FROM w ORDER BY g, id');
|
|
90
|
+
ok('#102 CUME_DIST 多分区(b 分区单行 → 1)',
|
|
91
|
+
eq(r.rows, [[1, 0.25], [2, 0.75], [3, 0.75], [4, 1], [5, 1]]), r.rows);
|
|
92
|
+
|
|
93
|
+
// 单行分区
|
|
94
|
+
await executeSQL(db, 'CREATE TABLE s1 (id INT, v INT)');
|
|
95
|
+
await executeSQL(db, 'INSERT INTO s1 VALUES (1, 42)');
|
|
96
|
+
r = await q('SELECT PERCENT_RANK() OVER (ORDER BY v) AS pr, CUME_DIST() OVER (ORDER BY v) AS cd FROM s1');
|
|
97
|
+
ok('#102 单行分区:PERCENT_RANK=0,CUME_DIST=1(无除零)',
|
|
98
|
+
eq(r.rows, [[0, 1]]), r.rows);
|
|
99
|
+
|
|
100
|
+
// 全同值
|
|
101
|
+
await executeSQL(db, 'CREATE TABLE same (id INT, v INT)');
|
|
102
|
+
await executeSQL(db, 'INSERT INTO same VALUES (1,5),(2,5),(3,5)');
|
|
103
|
+
r = await q('SELECT id, PERCENT_RANK() OVER (ORDER BY v) AS pr, CUME_DIST() OVER (ORDER BY v) AS cd FROM same ORDER BY id');
|
|
104
|
+
ok('#102 全同值:PERCENT_RANK 全 0,CUME_DIST 全 1',
|
|
105
|
+
eq(r.rows, [[1, 0, 1], [2, 0, 1], [3, 0, 1]]), r.rows);
|
|
106
|
+
|
|
107
|
+
// 乱序插入
|
|
108
|
+
await executeSQL(db, 'CREATE TABLE unsorted (id INT, v INT)');
|
|
109
|
+
await executeSQL(db, 'INSERT INTO unsorted VALUES (1,30),(2,10),(3,20),(4,40)');
|
|
110
|
+
r = await q('SELECT id, PERCENT_RANK() OVER (ORDER BY v) AS pr, CUME_DIST() OVER (ORDER BY v) AS cd FROM unsorted ORDER BY id');
|
|
111
|
+
ok('#102 乱序插入',
|
|
112
|
+
eq(r.rows, [[1, 2 / 3, 0.75], [2, 0, 0.25], [3, 1 / 3, 0.5], [4, 1, 1]]), r.rows);
|
|
113
|
+
|
|
114
|
+
// NULL 值(NULL 属于同一 peer 组;ASC 时 NULL 排最前)
|
|
115
|
+
await executeSQL(db, 'CREATE TABLE withnull (id INT, v INT)');
|
|
116
|
+
await executeSQL(db, 'INSERT INTO withnull VALUES (1,NULL),(2,10),(3,NULL),(4,20)');
|
|
117
|
+
r = await q('SELECT id, PERCENT_RANK() OVER (ORDER BY v) AS pr, CUME_DIST() OVER (ORDER BY v) AS cd FROM withnull ORDER BY id');
|
|
118
|
+
ok('#102 含 NULL:NULL 视为同一组,ASC 排最前',
|
|
119
|
+
eq(r.rows, [[1, 0, 0.5], [2, 2 / 3, 0.75], [3, 0, 0.5], [4, 1, 1]]), r.rows);
|
|
120
|
+
|
|
121
|
+
// 无 ORDER BY:全部互为 peer
|
|
122
|
+
r = await q('SELECT id, PERCENT_RANK() OVER () AS pr, CUME_DIST() OVER () AS cd FROM unsorted ORDER BY id');
|
|
123
|
+
ok('#102 无 ORDER BY:PERCENT_RANK=0 / CUME_DIST=1',
|
|
124
|
+
eq(r.rows, [[1, 0, 1], [2, 0, 1], [3, 0, 1], [4, 0, 1]]), r.rows);
|
|
125
|
+
|
|
126
|
+
// 与 RANK 的一致性:PR = (RANK-1)/(n-1)
|
|
127
|
+
r = await q('SELECT id, RANK() OVER (ORDER BY v) AS rk, PERCENT_RANK() OVER (ORDER BY v) AS pr FROM unsorted ORDER BY id');
|
|
128
|
+
ok('#102 PERCENT_RANK == (RANK-1)/(n-1)',
|
|
129
|
+
r.rows.every(([, rk, pr]) => near(pr, (rk - 1) / 3)), r.rows);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/* ===================== #103 窗口 ORDER BY DESC 的 NULL 排序 ===================== */
|
|
133
|
+
{
|
|
134
|
+
const db = new Database(':memory:', { autoSave: false });
|
|
135
|
+
await executeSQL(db, 'CREATE TABLE n (id INT, v INT)');
|
|
136
|
+
await executeSQL(db, 'INSERT INTO n VALUES (1,10),(2,NULL),(3,30),(4,NULL),(5,20)');
|
|
137
|
+
const q = sql => executeSQL(db, sql);
|
|
138
|
+
|
|
139
|
+
// 普通 ORDER BY 的基准行为:ASC → NULL 最前;DESC → NULL 最后
|
|
140
|
+
let r = await q('SELECT id, v FROM n ORDER BY v ASC, id');
|
|
141
|
+
ok('#103 基线:普通 ORDER BY ASC NULL 在前',
|
|
142
|
+
eq(r.rows, [[2, null], [4, null], [1, 10], [5, 20], [3, 30]]), r.rows);
|
|
143
|
+
|
|
144
|
+
r = await q('SELECT id, v FROM n ORDER BY v DESC, id');
|
|
145
|
+
ok('#103 基线:普通 ORDER BY DESC NULL 在后',
|
|
146
|
+
eq(r.rows, [[3, 30], [5, 20], [1, 10], [2, null], [4, null]]), r.rows);
|
|
147
|
+
|
|
148
|
+
// ROW_NUMBER:DESC 时 NULL 应拿最后的名次
|
|
149
|
+
r = await q('SELECT id, ROW_NUMBER() OVER (ORDER BY v DESC, id) AS rn FROM n ORDER BY id');
|
|
150
|
+
ok('#103 ROW_NUMBER OVER (ORDER BY v DESC) NULL 拿到最后名次',
|
|
151
|
+
eq(r.rows, [[1, 3], [2, 4], [3, 1], [4, 5], [5, 2]]), r.rows);
|
|
152
|
+
|
|
153
|
+
r = await q('SELECT id, ROW_NUMBER() OVER (ORDER BY v ASC, id) AS rn FROM n ORDER BY id');
|
|
154
|
+
ok('#103 ROW_NUMBER OVER (ORDER BY v ASC) NULL 拿到最前名次',
|
|
155
|
+
eq(r.rows, [[1, 3], [2, 1], [3, 5], [4, 2], [5, 4]]), r.rows);
|
|
156
|
+
|
|
157
|
+
// LAG / LEAD 跟随同一排序
|
|
158
|
+
r = await q('SELECT id, LAG(v) OVER (ORDER BY v DESC) AS lg FROM n ORDER BY id');
|
|
159
|
+
ok('#103 LAG OVER (ORDER BY v DESC) 与普通 DESC 顺序一致',
|
|
160
|
+
eq(r.rows, [[1, 20], [2, 10], [3, null], [4, null], [5, 30]]), r.rows);
|
|
161
|
+
|
|
162
|
+
r = await q('SELECT id, LEAD(v) OVER (ORDER BY v DESC) AS ld FROM n ORDER BY id');
|
|
163
|
+
ok('#103 LEAD OVER (ORDER BY v DESC) 与普通 DESC 顺序一致',
|
|
164
|
+
eq(r.rows, [[1, null], [2, null], [3, 20], [4, null], [5, 10]]), r.rows);
|
|
165
|
+
|
|
166
|
+
// RANK / DENSE_RANK:两个 NULL 并列,且排在最后
|
|
167
|
+
r = await q('SELECT id, RANK() OVER (ORDER BY v DESC) AS rk, DENSE_RANK() OVER (ORDER BY v DESC) AS dr FROM n ORDER BY id');
|
|
168
|
+
ok('#103 RANK/DENSE_RANK DESC:NULL 并列且排在最后',
|
|
169
|
+
eq(r.rows, [[1, 3, 3], [2, 4, 4], [3, 1, 1], [4, 4, 4], [5, 2, 2]]), r.rows);
|
|
170
|
+
|
|
171
|
+
r = await q('SELECT id, RANK() OVER (ORDER BY v ASC) AS rk, DENSE_RANK() OVER (ORDER BY v ASC) AS dr FROM n ORDER BY id');
|
|
172
|
+
ok('#103 RANK/DENSE_RANK ASC:NULL 并列且排在最前',
|
|
173
|
+
eq(r.rows, [[1, 3, 2], [2, 1, 1], [3, 5, 4], [4, 1, 1], [5, 4, 3]]), r.rows);
|
|
174
|
+
|
|
175
|
+
// 累计帧(SUM OVER ORDER BY DESC)也要走同一排序
|
|
176
|
+
r = await q('SELECT id, SUM(v) OVER (ORDER BY v DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS s FROM n ORDER BY id');
|
|
177
|
+
ok('#103 SUM OVER (ORDER BY v DESC) 累计帧:NULL 在最后且被 SUM 忽略',
|
|
178
|
+
eq(r.rows, [[1, 60], [2, 60], [3, 30], [4, 60], [5, 50]]), r.rows);
|
|
179
|
+
|
|
180
|
+
// 多分区 + DESC + NULL
|
|
181
|
+
await executeSQL(db, 'CREATE TABLE p (id INT, g TEXT, v INT)');
|
|
182
|
+
await executeSQL(db, "INSERT INTO p VALUES (1,'a',10),(2,'a',NULL),(3,'b',20),(4,'b',NULL),(5,'b',30)");
|
|
183
|
+
r = await q('SELECT id, ROW_NUMBER() OVER (PARTITION BY g ORDER BY v DESC, id) AS rn FROM p ORDER BY id');
|
|
184
|
+
ok('#103 PARTITION BY + DESC:每个分区内 NULL 都排最后',
|
|
185
|
+
eq(r.rows, [[1, 1], [2, 2], [3, 2], [4, 3], [5, 1]]), r.rows);
|
|
186
|
+
|
|
187
|
+
// NULL 在首/中/尾三种位置都覆盖
|
|
188
|
+
await executeSQL(db, 'CREATE TABLE mix (id INT, v INT)');
|
|
189
|
+
await executeSQL(db, 'INSERT INTO mix VALUES (1,NULL),(2,5),(3,NULL),(4,10),(5,NULL)');
|
|
190
|
+
r = await q('SELECT id, ROW_NUMBER() OVER (ORDER BY v DESC, id) AS rn FROM mix ORDER BY id');
|
|
191
|
+
ok('#103 NULL 在首/中/尾:DESC 时全部聚在尾部',
|
|
192
|
+
eq(r.rows, [[1, 3], [2, 2], [3, 4], [4, 1], [5, 5]]), r.rows);
|
|
193
|
+
|
|
194
|
+
r = await q('SELECT id, ROW_NUMBER() OVER (ORDER BY v ASC, id) AS rn FROM mix ORDER BY id');
|
|
195
|
+
ok('#103 NULL 在首/中/尾:ASC 时全部聚在头部',
|
|
196
|
+
eq(r.rows, [[1, 1], [2, 4], [3, 2], [4, 5], [5, 3]]), r.rows);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
console.log(`\n${passed} passed, ${failed} failed`);
|
|
200
|
+
process.exit(failed === 0 ? 0 : 1);
|
|
201
|
+
})().catch(e => {
|
|
202
|
+
console.error('[FATAL]', e && e.stack || e);
|
|
203
|
+
process.exit(1);
|
|
204
|
+
});
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/* ---- issue #105 + JSON 包含/搜索的语义回归 ---- */
|
|
2
|
+
/*
|
|
3
|
+
* #105:JSON_CONTAINS 用字符串 includes 实现(candidate 不解析、path 被忽略),
|
|
4
|
+
* JSON_SEARCH 用 toLowerCase + includes(大小写不敏感、不支持 LIKE 通配符)。
|
|
5
|
+
*
|
|
6
|
+
* 顺带钉死两个差分发现的 bug:
|
|
7
|
+
* - jsonContainsValue 用 String() 宽松比较,字符串 "2" 能命中数字 2
|
|
8
|
+
* - JSON_SEARCH 不认 % / _ 通配符
|
|
9
|
+
* 参考语义:MySQL 8.0 JSON_CONTAINS / JSON_SEARCH(大小写敏感、LIKE 模式)。
|
|
10
|
+
*/
|
|
11
|
+
const path = require('path');
|
|
12
|
+
const ROOT = path.join(__dirname, '..');
|
|
13
|
+
const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
|
|
14
|
+
|
|
15
|
+
let pass = 0, fail = 0;
|
|
16
|
+
function ok(name, cond, got) {
|
|
17
|
+
if (cond) { pass++; console.log('[OK] ' + name); }
|
|
18
|
+
else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
(async () => {
|
|
22
|
+
const db = new Database(':memory:', { autoSave: false });
|
|
23
|
+
const q = async (sql) => {
|
|
24
|
+
const r = await executeSQL(db, sql, { safety: false });
|
|
25
|
+
return r.rows[0][0];
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
// ---------- #105 JSON_CONTAINS ----------
|
|
29
|
+
ok('#105 字符串候选命中数组元素',
|
|
30
|
+
await q("SELECT JSON_CONTAINS('[1,2,3]', '2')") === 1, null);
|
|
31
|
+
ok('#105 第三个 path 参数生效',
|
|
32
|
+
await q("SELECT JSON_CONTAINS('{\"a\":1}', '1', '$.a')") === 1, null);
|
|
33
|
+
ok('#105 嵌套 path',
|
|
34
|
+
await q("SELECT JSON_CONTAINS('{\"a\":{\"b\":1}}', '1', '$.a.b')") === 1, null);
|
|
35
|
+
ok('数值字面量候选仍命中',
|
|
36
|
+
await q("SELECT JSON_CONTAINS('[1,2,3]', 2)") === 1, null);
|
|
37
|
+
ok('path 不存在返回 0',
|
|
38
|
+
await q("SELECT JSON_CONTAINS('{\"a\":1}', '1', '$.b')") === 0, null);
|
|
39
|
+
ok('对象包含(子集)',
|
|
40
|
+
await q("SELECT JSON_CONTAINS('{\"a\":1,\"b\":2}', '{\"a\":1}')") === 1, null);
|
|
41
|
+
ok('对象值不匹配返回 0',
|
|
42
|
+
await q("SELECT JSON_CONTAINS('{\"a\":1}', '{\"a\":2}')") === 0, null);
|
|
43
|
+
ok('数组子集命中',
|
|
44
|
+
await q("SELECT JSON_CONTAINS('[1,2,3]', '[2,3]')") === 1, null);
|
|
45
|
+
ok('数组不含该元素返回 0',
|
|
46
|
+
await q("SELECT JSON_CONTAINS('[1,2,3]', '9')") === 0, null);
|
|
47
|
+
|
|
48
|
+
// ---------- 类型敏感(差分发现) ----------
|
|
49
|
+
ok('字符串 "2" 不应命中数字 2',
|
|
50
|
+
await q("SELECT JSON_CONTAINS('[1,2,3]', '\"2\"')") === 0, null);
|
|
51
|
+
ok('字符串元素只被字符串候选命中',
|
|
52
|
+
await q("SELECT JSON_CONTAINS('[\"2\"]', '\"2\"')") === 1, null);
|
|
53
|
+
ok('数字 2 不应命中字符串元素',
|
|
54
|
+
await q("SELECT JSON_CONTAINS('[\"2\"]', '2')") === 0, null);
|
|
55
|
+
|
|
56
|
+
// ---------- JSON path 解析器(差分发现) ----------
|
|
57
|
+
ok('JSON_EXTRACT 支持纯数组索引 $[1]',
|
|
58
|
+
await q("SELECT JSON_EXTRACT('[1,2,3]', '$[1]')") === 2, null);
|
|
59
|
+
ok('JSON_CONTAINS 的 path 值是合法 JSON null',
|
|
60
|
+
await q("SELECT JSON_CONTAINS('{\"a\":null}', 'null', '$.a')") === 1, null);
|
|
61
|
+
ok('JSON_CONTAINS 支持数组索引 path',
|
|
62
|
+
await q("SELECT JSON_CONTAINS('{\"a\":[1,2]}', '2', '$.a[1]')") === 1, null);
|
|
63
|
+
ok('JSON_EXTRACT 找不到路径仍返回 NULL',
|
|
64
|
+
await q("SELECT JSON_EXTRACT('{\"a\":1}', '$.b')") === null, null);
|
|
65
|
+
|
|
66
|
+
// ---------- #105 JSON_SEARCH 大小写敏感 ----------
|
|
67
|
+
ok('#105 JSON_SEARCH 大小写不同返回 NULL',
|
|
68
|
+
await q("SELECT JSON_SEARCH('[\"Hello\"]', 'one', 'hello')") === null, null);
|
|
69
|
+
ok('JSON_SEARCH 大小写相同命中',
|
|
70
|
+
await q("SELECT JSON_SEARCH('[\"Hello\"]', 'one', 'Hello')") === '$[0]', null);
|
|
71
|
+
|
|
72
|
+
// ---------- LIKE 通配符(差分发现) ----------
|
|
73
|
+
ok('JSON_SEARCH 支持 % 通配符',
|
|
74
|
+
await q("SELECT JSON_SEARCH('[\"hello world\"]', 'one', 'hello%')") === '$[0]', null);
|
|
75
|
+
ok('JSON_SEARCH 支持 _ 通配符',
|
|
76
|
+
await q("SELECT JSON_SEARCH('[\"Hello\"]', 'one', 'H_llo')") === '$[0]', null);
|
|
77
|
+
ok('JSON_SEARCH 的 % 不是字面量',
|
|
78
|
+
await q("SELECT JSON_SEARCH('[\"hello%world\"]', 'one', 'hello%')") === '$[0]', null);
|
|
79
|
+
const all = await q("SELECT JSON_SEARCH('{\"a\":\"x\",\"b\":\"x\"}', 'all', 'x')");
|
|
80
|
+
ok('all 模式拿到两个路径', Array.isArray(all) && all.length === 2, all);
|
|
81
|
+
|
|
82
|
+
console.log(`\n${pass} passed, ${fail} failed`);
|
|
83
|
+
process.exit(fail === 0 ? 0 : 1);
|
|
84
|
+
})().catch(e => {
|
|
85
|
+
console.log('[FAIL] unexpected exception: ' + e.stack.split('\n').slice(0, 3).join('\n'));
|
|
86
|
+
process.exit(1);
|
|
87
|
+
});
|