jsql-neo 6.6.2 → 6.6.4
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/cache.js +3 -0
- package/lib/mysql_server.js +8 -3
- package/lib/nedb_compat.js +8 -2
- package/lib/pg_server.js +16 -2
- package/lib/sql.js +187 -83
- package/lib/sqlite_compat.js +7 -1
- package/lib/updater.js +33 -8
- package/package.json +3 -3
- package/test/issue-101-103.test.js +204 -0
- package/test/issue-86-99.test.js +154 -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.4** — 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/cache.js
CHANGED
|
@@ -187,6 +187,9 @@ class Cache {
|
|
|
187
187
|
if (start < 0) start = Math.max(list.length + start, 0);
|
|
188
188
|
if (stop < 0) stop = list.length + stop;
|
|
189
189
|
stop = Math.min(stop, list.length - 1);
|
|
190
|
+
// #89:stop 越界到负数也要钳到 0(与 Redis 一致)。
|
|
191
|
+
// 此前 stop 只有上限钳制,负数越界后 start > stop → 错误返回 []。
|
|
192
|
+
stop = Math.max(stop, 0);
|
|
190
193
|
if (start > stop) return [];
|
|
191
194
|
return list.slice(start, stop + 1);
|
|
192
195
|
}
|
package/lib/mysql_server.js
CHANGED
|
@@ -595,7 +595,9 @@ class MysqlConnection {
|
|
|
595
595
|
this._send(encodeLenenc(1));
|
|
596
596
|
this._send(columnDefinition({ name: 'Id', type: MYSQL_TYPE_LONG }));
|
|
597
597
|
this._send(eofPacket());
|
|
598
|
-
|
|
598
|
+
// #95:结果行字段必须是 length-encoded string。
|
|
599
|
+
// 此前直接发裸字节 0x31('1'),客户端把它当字段长度读后续 49 字节 → 协议失步。
|
|
600
|
+
this._send(encodeLenencString('1'));
|
|
599
601
|
this._send(eofPacket());
|
|
600
602
|
break;
|
|
601
603
|
}
|
|
@@ -1108,10 +1110,13 @@ class MysqlServer {
|
|
|
1108
1110
|
if (!this._dbExists(db)) await this.createDatabase(db);
|
|
1109
1111
|
const engine = await this._getDatabase(db);
|
|
1110
1112
|
let s = sql;
|
|
1111
|
-
// 词法扫描:找出所有字符串字面量和注释的位置,替换时跳过它们
|
|
1112
|
-
const masked = _maskStringsAndComments(s);
|
|
1113
1113
|
for (const t of tables) {
|
|
1114
1114
|
if (t && t.indexOf('.') !== -1) {
|
|
1115
|
+
// #97:每次 s.replace 都会缩短 s(剥掉 db. 前缀),但 offset 是相对当前 s 的。
|
|
1116
|
+
// 此前 masked 只基于最初始的完整 s 算一次,后续 replace 的 offset 相对 masked
|
|
1117
|
+
// 整体"提前",掩码守卫误判 → ≥2 个 db.table 时改写错位(错库/错表)。
|
|
1118
|
+
// 所以每次替换前必须基于**当前 s** 重算掩码,保证 offset 对齐。
|
|
1119
|
+
const masked = _maskStringsAndComments(s);
|
|
1115
1120
|
const re = new RegExp('\\b' + t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\b', 'g');
|
|
1116
1121
|
s = s.replace(re, (match, offset) => {
|
|
1117
1122
|
// 如果匹配位置在字符串字面量或注释中,不替换。
|
package/lib/nedb_compat.js
CHANGED
|
@@ -77,8 +77,14 @@ function matchOperator(value, op, expected) {
|
|
|
77
77
|
case '$in': return Array.isArray(expected) && expected.some(e => looseEqual(value, e));
|
|
78
78
|
case '$nin': return Array.isArray(expected) && !expected.some(e => looseEqual(value, e));
|
|
79
79
|
case '$exists': return expected ? value !== undefined : value === undefined;
|
|
80
|
-
case '$regex':
|
|
81
|
-
|
|
80
|
+
case '$regex': {
|
|
81
|
+
// #88:$regex 用字符串模式('a')时直接用字符串作正则源,不能取 .source
|
|
82
|
+
// (只有 RegExp 才有 .source)。此前 new RegExp(undefined) = /(?:)/ 匹配一切,
|
|
83
|
+
// 导致 find({ $regex: 'a' }) 返回全表。
|
|
84
|
+
const src = typeof expected === 'string' ? expected : (expected && expected.source);
|
|
85
|
+
const flags = (expected && expected.flags) || 'i';
|
|
86
|
+
return typeof value === 'string' && new RegExp(src, flags).test(value);
|
|
87
|
+
}
|
|
82
88
|
case '$size': return Array.isArray(value) && value.length === expected;
|
|
83
89
|
default: return false;
|
|
84
90
|
}
|
package/lib/pg_server.js
CHANGED
|
@@ -206,6 +206,17 @@ function buildParameterDesc(paramTypes) {
|
|
|
206
206
|
return frame(0x74, p.build()); // 't'
|
|
207
207
|
}
|
|
208
208
|
|
|
209
|
+
// #93:PG 二进制参数解码。Bind 的 parameter format code=1 时按参数类型(OID)解码,
|
|
210
|
+
// 不能按 UTF-8 文本读。常见 OID:int4=23, int8=20, float8=701, float4=700, bool=16。
|
|
211
|
+
function decodeBinaryParam(buf, typeOid) {
|
|
212
|
+
if (typeOid === 23) return buf.length >= 4 ? buf.readInt32BE(0) : null; // int4
|
|
213
|
+
if (typeOid === 20) return buf.length >= 8 ? buf.readBigInt64BE(0) : null; // int8
|
|
214
|
+
if (typeOid === 701) return buf.length >= 8 ? buf.readDoubleBE(0) : null; // float8
|
|
215
|
+
if (typeOid === 700) return buf.length >= 4 ? buf.readFloatBE(0) : null; // float4
|
|
216
|
+
if (typeOid === 16) return buf.length >= 1 ? buf[0] !== 0 : null; // bool
|
|
217
|
+
return buf.toString('utf8');
|
|
218
|
+
}
|
|
219
|
+
|
|
209
220
|
// ---------------------------------------------------------------------------
|
|
210
221
|
// SCRAM-SHA-256 (RFC 5802 / RFC 7677) — server side
|
|
211
222
|
// ---------------------------------------------------------------------------
|
|
@@ -520,7 +531,10 @@ class PgConnection {
|
|
|
520
531
|
if (vlen === -1) { values.push(null); continue; }
|
|
521
532
|
if (vlen < 0 || off + vlen > body.length) throw new Error('invalid Bind parameter length');
|
|
522
533
|
const fmt = formats.length > 0 ? formats[Math.min(i, formats.length - 1)] : 0;
|
|
523
|
-
|
|
534
|
+
// #93:fmt=1(binary)时按参数类型解码,此前一律按 UTF-8 文本读导致二进制参数错乱。
|
|
535
|
+
const pt = (stmt.paramTypes && stmt.paramTypes[i]) || 0;
|
|
536
|
+
const raw = body.slice(off, off + vlen);
|
|
537
|
+
values.push(fmt === 1 ? decodeBinaryParam(raw, pt) : body.toString('utf8', off, off + vlen));
|
|
524
538
|
off += vlen;
|
|
525
539
|
}
|
|
526
540
|
this._portal.set(portal, { values, stmt });
|
|
@@ -881,4 +895,4 @@ function createPgServer(options) {
|
|
|
881
895
|
return new PgServer(options || {});
|
|
882
896
|
}
|
|
883
897
|
|
|
884
|
-
module.exports = { PgServer, createPgServer, PgConnection, buildRowDescription, buildDataRow, buildCommandComplete, buildErrorResponse, buildReadyForQuery, buildParameterStatus, buildBackendKeyData, buildParseComplete, buildBindComplete, buildCloseComplete, buildNoData, buildParameterDesc, TYPE_OIDS, pgTypeOid, pgFormatValue };
|
|
898
|
+
module.exports = { PgServer, createPgServer, PgConnection, buildRowDescription, buildDataRow, buildCommandComplete, buildErrorResponse, buildReadyForQuery, buildParameterStatus, buildBackendKeyData, buildParseComplete, buildBindComplete, buildCloseComplete, buildNoData, buildParameterDesc, decodeBinaryParam, TYPE_OIDS, pgTypeOid, pgFormatValue };
|
package/lib/sql.js
CHANGED
|
@@ -1248,7 +1248,10 @@ class Parser {
|
|
|
1248
1248
|
while (true) {
|
|
1249
1249
|
const col = this.parseTableName();
|
|
1250
1250
|
this.expect('op', '=');
|
|
1251
|
-
|
|
1251
|
+
// #99:ON DUPLICATE KEY UPDATE 赋值右侧的裸标识符(如 other=other)是**列引用**,
|
|
1252
|
+
// 不是字符串字面量(MySQL 语义:自赋值是合法 no-op)。
|
|
1253
|
+
// 传 identAsColumn=true 让 parseValue 把裸 ident 解析成 {type:'column'}。
|
|
1254
|
+
const val = this.parseValue(true);
|
|
1252
1255
|
onDuplicate.push([col, val]);
|
|
1253
1256
|
if (this.peek().value === ',') { this.next(); continue; }
|
|
1254
1257
|
break;
|
|
@@ -1283,8 +1286,8 @@ class Parser {
|
|
|
1283
1286
|
return cols;
|
|
1284
1287
|
}
|
|
1285
1288
|
|
|
1286
|
-
parseValue() {
|
|
1287
|
-
const atom = this.parseValueAtom();
|
|
1289
|
+
parseValue(identAsColumn = false) {
|
|
1290
|
+
const atom = this.parseValueAtom(identAsColumn);
|
|
1288
1291
|
return this.parseBinaryFromAtom(atom);
|
|
1289
1292
|
}
|
|
1290
1293
|
|
|
@@ -1301,7 +1304,7 @@ class Parser {
|
|
|
1301
1304
|
return left;
|
|
1302
1305
|
}
|
|
1303
1306
|
|
|
1304
|
-
parseValueAtom() {
|
|
1307
|
+
parseValueAtom(identAsColumn = false) {
|
|
1305
1308
|
// MySQL 前缀运算符:BINARY expr —— 强制大小写敏感比较。
|
|
1306
1309
|
// 仅当后面确实是值起始 token 才当作运算符,避免误吞裸列名 `binary`
|
|
1307
1310
|
// (`SELECT binary FROM t` / `WHERE binary = 1` 仍按列名解析)。
|
|
@@ -1348,9 +1351,11 @@ class Parser {
|
|
|
1348
1351
|
this.next();
|
|
1349
1352
|
const col = this.next();
|
|
1350
1353
|
if (!isUsableNameToken(col)) throw new Error(`Expected column name after '.', got '${col.value}'`);
|
|
1351
|
-
|
|
1354
|
+
const full = nameOfToken(t) + '.' + nameOfToken(col);
|
|
1355
|
+
return identAsColumn ? { type: 'column', name: full } : full;
|
|
1352
1356
|
}
|
|
1353
|
-
|
|
1357
|
+
// #99:ON DUPLICATE 赋值右侧裸标识符 → 列引用节点
|
|
1358
|
+
return identAsColumn ? { type: 'column', name: nameOfToken(t) } : nameOfToken(t);
|
|
1354
1359
|
}
|
|
1355
1360
|
throw new Error(`Expected value, got '${t.value}'`);
|
|
1356
1361
|
}
|
|
@@ -3257,10 +3262,25 @@ function applyCast(value, dataType) {
|
|
|
3257
3262
|
}
|
|
3258
3263
|
return n;
|
|
3259
3264
|
}
|
|
3260
|
-
if (t === 'FLOAT' || t === 'DOUBLE' || t === 'REAL'
|
|
3265
|
+
if (t === 'FLOAT' || t === 'DOUBLE' || t === 'REAL') {
|
|
3261
3266
|
const n = Number(value);
|
|
3262
3267
|
return Number.isFinite(n) ? n : null;
|
|
3263
3268
|
}
|
|
3269
|
+
if (t === 'NUMERIC' || t === 'DECIMAL') {
|
|
3270
|
+
// #96:CAST(x AS DECIMAL(p,s)) 必须按标度 s 四舍五入,不能原样返回。
|
|
3271
|
+
// 此前 DECIMAL 被并入 FLOAT 分支,p/s 被剥掉后原值返回(123.456 → 123.456)。
|
|
3272
|
+
const m = String(dataType).match(/\((\d+)(?:,(\d+))?\)/i);
|
|
3273
|
+
const scale = m && m[2] !== undefined ? parseInt(m[2], 10) : 0;
|
|
3274
|
+
let n = Number(value);
|
|
3275
|
+
if (!Number.isFinite(n)) return null;
|
|
3276
|
+
if (scale > 0) {
|
|
3277
|
+
const factor = Math.pow(10, scale);
|
|
3278
|
+
n = Math.round(n * factor) / factor;
|
|
3279
|
+
} else {
|
|
3280
|
+
n = Math.round(n);
|
|
3281
|
+
}
|
|
3282
|
+
return n;
|
|
3283
|
+
}
|
|
3264
3284
|
if (t === 'BOOLEAN' || t === 'BOOL') {
|
|
3265
3285
|
if (typeof value === 'boolean') return value;
|
|
3266
3286
|
if (typeof value === 'number') return value !== 0;
|
|
@@ -3432,6 +3452,30 @@ function bigintExactArith(l, r, op) {
|
|
|
3432
3452
|
}
|
|
3433
3453
|
}
|
|
3434
3454
|
|
|
3455
|
+
/**
|
|
3456
|
+
* 统一的 SQL 标量排序比较器(普通 ORDER BY / 窗口函数 / 组合查询共用,#103)。
|
|
3457
|
+
*
|
|
3458
|
+
* NULL 排序策略:ASC 时 NULL 排在最前,DESC 时 NULL 排在最后
|
|
3459
|
+
* (MySQL / SQLite 的默认语义)。此前窗口函数的比较器把 NULL 硬编码成
|
|
3460
|
+
* 恒小,于是 ORDER BY col DESC 时 NULL 跑到最前,与普通 SELECT 的 ORDER BY
|
|
3461
|
+
* 不一致;抽成一个函数后两条排序路径不会再各写一套。
|
|
3462
|
+
*/
|
|
3463
|
+
function compareSqlValues(av, bv, dir) {
|
|
3464
|
+
const desc = dir === 'desc';
|
|
3465
|
+
if (av === bv) return 0;
|
|
3466
|
+
const aNull = av === null || av === undefined;
|
|
3467
|
+
const bNull = bv === null || bv === undefined;
|
|
3468
|
+
if (aNull || bNull) {
|
|
3469
|
+
if (aNull && bNull) return 0;
|
|
3470
|
+
const r = aNull ? -1 : 1;
|
|
3471
|
+
return desc ? -r : r;
|
|
3472
|
+
}
|
|
3473
|
+
const r = typeof av === 'number' && typeof bv === 'number'
|
|
3474
|
+
? av - bv
|
|
3475
|
+
: (String(av) < String(bv) ? -1 : String(av) > String(bv) ? 1 : 0);
|
|
3476
|
+
return desc ? -r : r;
|
|
3477
|
+
}
|
|
3478
|
+
|
|
3435
3479
|
function resolveOperand(operand, row, ctx) {
|
|
3436
3480
|
if (operand === null || operand === undefined) return null;
|
|
3437
3481
|
if (typeof operand === 'string') return resolveOperand({ type: 'column', name: operand }, row, ctx);
|
|
@@ -4882,7 +4926,10 @@ function seedRand(seed) {
|
|
|
4882
4926
|
// ci 默认 true:保持 LIKE 既有的大小写不敏感行为不变;ILIKE 同为不敏感。
|
|
4883
4927
|
// escape:可选转义符(ESCAPE 子句),默认反斜杠;转义符后跟 % _ 或转义符本身按字面量匹配。
|
|
4884
4928
|
function likeMatch(value, pattern, ci = true, escape = '\\') {
|
|
4885
|
-
|
|
4929
|
+
// #94:NULL LIKE ... → UNKNOWN(null),不能当 false。
|
|
4930
|
+
if (value === null || value === undefined) return null;
|
|
4931
|
+
// #94:MySQL 语义——数值列(及其他类型)先转成字符串再 LIKE(10 LIKE '1%' → '10' LIKE '1%' → true)。
|
|
4932
|
+
const sv = String(value);
|
|
4886
4933
|
const p = String(pattern);
|
|
4887
4934
|
const e = (escape === null || escape === undefined || escape === '') ? '\\' : String(escape);
|
|
4888
4935
|
const reEsc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
@@ -4898,7 +4945,7 @@ function likeMatch(value, pattern, ci = true, escape = '\\') {
|
|
|
4898
4945
|
else if (ch === '_') out += '.';
|
|
4899
4946
|
else out += reEsc(ch);
|
|
4900
4947
|
}
|
|
4901
|
-
return new RegExp('^' + out + '$', ci ? 'i' : '').test(
|
|
4948
|
+
return new RegExp('^' + out + '$', ci ? 'i' : '').test(sv);
|
|
4902
4949
|
}
|
|
4903
4950
|
|
|
4904
4951
|
/** 解析 PG 的路径字面量:'{a,b}' 或数组 → ['a','b'] */
|
|
@@ -5122,6 +5169,23 @@ function sqlXor(a, b) {
|
|
|
5122
5169
|
return a !== b ? 1 : 0;
|
|
5123
5170
|
}
|
|
5124
5171
|
|
|
5172
|
+
// #86:递归把表达式 AST 里的 VALUES(col)/EXCLUDED.col 节点替换成目标行 d 的对应列值。
|
|
5173
|
+
// ON DUPLICATE KEY UPDATE 里 VALUES(col) 引用"本次本应插入的值"(新行 d),
|
|
5174
|
+
// 求值前必须先替换,否则 evaluateExpr/resolveOperand 不认识 _valuesOf 节点。
|
|
5175
|
+
function substituteValuesOf(node, d) {
|
|
5176
|
+
if (node && typeof node === 'object') {
|
|
5177
|
+
if (node._valuesOf !== undefined || node._excludedOf !== undefined) {
|
|
5178
|
+
const col = node._valuesOf !== undefined ? node._valuesOf : node._excludedOf;
|
|
5179
|
+
return (d && d[col] !== undefined) ? d[col] : null;
|
|
5180
|
+
}
|
|
5181
|
+
if (Array.isArray(node)) return node.map(n => substituteValuesOf(n, d));
|
|
5182
|
+
const out = {};
|
|
5183
|
+
for (const k of Object.keys(node)) out[k] = substituteValuesOf(node[k], d);
|
|
5184
|
+
return out;
|
|
5185
|
+
}
|
|
5186
|
+
return node;
|
|
5187
|
+
}
|
|
5188
|
+
|
|
5125
5189
|
function evaluateExpr(expr, row, ctx) {
|
|
5126
5190
|
if (expr === null || expr === undefined) return false;
|
|
5127
5191
|
switch (expr.type) {
|
|
@@ -5263,6 +5327,8 @@ function evaluateExpr(expr, row, ctx) {
|
|
|
5263
5327
|
// MySQL 的 LIKE 默认不区分大小写;只有显式 BINARY / ci=false 才敏感。
|
|
5264
5328
|
// 此前写成 !!expr.ci,把 likeMatch 的 ci 默认值 true 覆盖成了 false。
|
|
5265
5329
|
const r = likeMatch(v, expr.pattern, expr.ci !== false, expr.escape);
|
|
5330
|
+
// #94:NULL LIKE → UNKNOWN(null);NOT (NULL LIKE) 仍为 UNKNOWN(null)。
|
|
5331
|
+
if (r === null) return null;
|
|
5266
5332
|
return expr.not ? !r : r;
|
|
5267
5333
|
}
|
|
5268
5334
|
case 'quantified':
|
|
@@ -5907,7 +5973,16 @@ class SQLExecutor {
|
|
|
5907
5973
|
const evalRow = existingRow
|
|
5908
5974
|
? Object.fromEntries([...Object.entries(d), ...Object.entries(existingRow)])
|
|
5909
5975
|
: d;
|
|
5910
|
-
|
|
5976
|
+
// #86:把表达式里的 VALUES(col)/EXCLUDED.col 解析成"本次本应插入的值"(d),
|
|
5977
|
+
// 否则 evaluateExpr 不认识 _valuesOf 节点 → undefined + 1 → NULL(数据损坏)。
|
|
5978
|
+
data[col] = evaluateExpr(substituteValuesOf(val, d), evalRow, this.ctx);
|
|
5979
|
+
} else if (val && typeof val === 'object' && val.type === 'column') {
|
|
5980
|
+
// #99:裸列名(other=other)按旧行值求值(合法 no-op),不当字符串字面量。
|
|
5981
|
+
// 此前解析成 'other' 赋给 INT 列 → 1292 崩溃。
|
|
5982
|
+
const evalRow = existingRow
|
|
5983
|
+
? Object.fromEntries([...Object.entries(d), ...Object.entries(existingRow)])
|
|
5984
|
+
: d;
|
|
5985
|
+
data[col] = evalRow[val.name] !== undefined ? evalRow[val.name] : d[val.name];
|
|
5911
5986
|
} else {
|
|
5912
5987
|
data[col] = val;
|
|
5913
5988
|
}
|
|
@@ -7000,9 +7075,10 @@ class SQLExecutor {
|
|
|
7000
7075
|
const vs = values.filter(v => v !== null && v !== undefined);
|
|
7001
7076
|
if (!vs.length) return null;
|
|
7002
7077
|
// 数值按数值比;字符串/日期按字典序/时间序。
|
|
7003
|
-
//
|
|
7004
|
-
|
|
7005
|
-
|
|
7078
|
+
// #98:只有**真正的 number** 才按数值比较。全数字字符串列('2','100','9')
|
|
7079
|
+
// 此前被误判为数值 → MIN/MAX 用数值比较且返回 Number,与 ORDER BY 字典序自相矛盾。
|
|
7080
|
+
// MySQL 语义:字符串列一律字典序且结果保持字符串。
|
|
7081
|
+
const numeric = (v) => typeof v === 'number';
|
|
7006
7082
|
if (vs.every(numeric)) {
|
|
7007
7083
|
let best = Number(vs[0]);
|
|
7008
7084
|
for (let i = 1; i < vs.length; i++) {
|
|
@@ -7878,11 +7954,8 @@ class SQLExecutor {
|
|
|
7878
7954
|
for (const o of orderBy) {
|
|
7879
7955
|
const av = resolveOperand(o.column, ra, this.ctx);
|
|
7880
7956
|
const bv = resolveOperand(o.column, rb, this.ctx);
|
|
7881
|
-
|
|
7882
|
-
if (
|
|
7883
|
-
if (bv === undefined || bv === null) return 1;
|
|
7884
|
-
const d = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv));
|
|
7885
|
-
if (d !== 0) return o.dir === 'asc' ? d : -d;
|
|
7957
|
+
const d = compareSqlValues(av, bv, o.dir);
|
|
7958
|
+
if (d !== 0) return d;
|
|
7886
7959
|
}
|
|
7887
7960
|
return ia - ib;
|
|
7888
7961
|
});
|
|
@@ -7925,16 +7998,35 @@ class SQLExecutor {
|
|
|
7925
7998
|
const argNode = toNode((w.spec && (w.spec.column || (w.spec.args && w.spec.args[0]))) || w.col.column || w.col.expr);
|
|
7926
7999
|
const valAt = (rowIdx, node) => resolveOperand(node || { type: 'value', value: 1 }, rows[rowIdx], this.ctx);
|
|
7927
8000
|
|
|
8001
|
+
// #102:RANK 值按需计算,PERCENT_RANK / CUME_DIST 复用
|
|
8002
|
+
const rankAt = (pos) => {
|
|
8003
|
+
let rank = 1;
|
|
8004
|
+
for (let k = 0; k < pos; k++) {
|
|
8005
|
+
if (this._windowPeerCmp(rows[ordered[k]], rows[ordered[pos]], orderBy, this.ctx) !== 0) rank++;
|
|
8006
|
+
}
|
|
8007
|
+
return rank;
|
|
8008
|
+
};
|
|
8009
|
+
|
|
7928
8010
|
ordered.forEach((rowIdx, pos) => {
|
|
7929
8011
|
let v = null;
|
|
7930
8012
|
switch (w.fn) {
|
|
7931
8013
|
case 'ROW_NUMBER': v = pos + 1; break;
|
|
7932
|
-
case 'RANK':
|
|
7933
|
-
|
|
7934
|
-
|
|
7935
|
-
|
|
7936
|
-
|
|
7937
|
-
|
|
8014
|
+
case 'RANK': v = rankAt(pos); break;
|
|
8015
|
+
case 'PERCENT_RANK': {
|
|
8016
|
+
// (rank - 1) / (total_rows - 1),单行 / 无 ORDER BY 分区返回 0
|
|
8017
|
+
const rank = rankAt(pos);
|
|
8018
|
+
const total = ordered.length;
|
|
8019
|
+
v = total > 1 ? (rank - 1) / (total - 1) : 0;
|
|
8020
|
+
break;
|
|
8021
|
+
}
|
|
8022
|
+
case 'CUME_DIST': {
|
|
8023
|
+
// 分区内 值 <= 当前行 的行数占比(所有 peer 同值)
|
|
8024
|
+
const total = ordered.length;
|
|
8025
|
+
const curKey = this._windowPeerKey(rows[rowIdx], orderBy, this.ctx);
|
|
8026
|
+
let end = pos;
|
|
8027
|
+
while (end + 1 < total &&
|
|
8028
|
+
this._windowPeerKey(rows[ordered[end + 1]], orderBy, this.ctx) === curKey) end++;
|
|
8029
|
+
v = total > 0 ? (end + 1) / total : null;
|
|
7938
8030
|
break;
|
|
7939
8031
|
}
|
|
7940
8032
|
case 'DENSE_RANK': {
|
|
@@ -7993,7 +8085,9 @@ class SQLExecutor {
|
|
|
7993
8085
|
|
|
7994
8086
|
_windowPeerKey(row, orderBy, ctx) {
|
|
7995
8087
|
if (!orderBy.length) return '';
|
|
7996
|
-
|
|
8088
|
+
// null 与 undefined 视为同一取值(都是 SQL NULL),否则二者会被当成不同 peer
|
|
8089
|
+
const norm = (v) => (v === null || v === undefined ? 'null' : JSON.stringify(v));
|
|
8090
|
+
return orderBy.map(o => norm(resolveOperand(o.column, row, ctx))).join('');
|
|
7997
8091
|
}
|
|
7998
8092
|
|
|
7999
8093
|
_windowPeerCmp(rowA, rowB, orderBy, ctx) {
|
|
@@ -8001,10 +8095,7 @@ class SQLExecutor {
|
|
|
8001
8095
|
for (const o of orderBy) {
|
|
8002
8096
|
const av = resolveOperand(o.column, rowA, ctx);
|
|
8003
8097
|
const bv = resolveOperand(o.column, rowB, ctx);
|
|
8004
|
-
|
|
8005
|
-
if (av === undefined || av === null) return -1;
|
|
8006
|
-
if (bv === undefined || bv === null) return 1;
|
|
8007
|
-
const d = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv));
|
|
8098
|
+
const d = compareSqlValues(av, bv, o.dir);
|
|
8008
8099
|
if (d !== 0) return d;
|
|
8009
8100
|
}
|
|
8010
8101
|
return 0;
|
|
@@ -8091,18 +8182,8 @@ class SQLExecutor {
|
|
|
8091
8182
|
};
|
|
8092
8183
|
keyed.sort((a, b) => {
|
|
8093
8184
|
for (const o of orderBy) {
|
|
8094
|
-
const
|
|
8095
|
-
|
|
8096
|
-
if (av === bv) continue;
|
|
8097
|
-
const aNull = av === null || av === undefined;
|
|
8098
|
-
const bNull = bv === null || bv === undefined;
|
|
8099
|
-
if (aNull || bNull) {
|
|
8100
|
-
const r = aNull && bNull ? 0 : (aNull ? -1 : 1);
|
|
8101
|
-
return o.dir === 'desc' ? -r : r;
|
|
8102
|
-
}
|
|
8103
|
-
const d = typeof av === 'number' && typeof bv === 'number'
|
|
8104
|
-
? av - bv : String(av).localeCompare(String(bv));
|
|
8105
|
-
if (d !== 0) return o.dir === 'desc' ? -d : d;
|
|
8185
|
+
const d = compareSqlValues(keyOf(a, o), keyOf(b, o), o.dir);
|
|
8186
|
+
if (d !== 0) return d;
|
|
8106
8187
|
}
|
|
8107
8188
|
return a.i - b.i;
|
|
8108
8189
|
});
|
|
@@ -8185,29 +8266,42 @@ class SQLExecutor {
|
|
|
8185
8266
|
all = [{ _virtual: true }];
|
|
8186
8267
|
} else {
|
|
8187
8268
|
const items = statement.from.tables.concat(statement.from.joins.map(j => j.item));
|
|
8188
|
-
//
|
|
8189
|
-
//
|
|
8190
|
-
|
|
8269
|
+
// #101:自连接(同一张表在 FROM 中出现多次)时,行前缀的分配规则:
|
|
8270
|
+
// - 显式别名优先;
|
|
8271
|
+
// - 无别名的实例默认仍用**表名**作为前缀,这样 SQL 里写的 `t.col` 才能解析到;
|
|
8272
|
+
// - 只有当这个名字已经被前面的实例占用时,才生成 t1/t2 这类自动别名,
|
|
8273
|
+
// 并且跳过所有已被显式别名占用的名字。
|
|
8274
|
+
// 此前对「同表出现多次」一律自动别名 t1/t2,导致查询里用原表名限定的
|
|
8275
|
+
// `t.id` 完全解析不到(行里只有 t1.id/t2.id),JOIN ON 恒假 → INNER 空、LEFT 全 NULL。
|
|
8276
|
+
const autoAliasMap = new Map();
|
|
8277
|
+
const usedPrefixes = new Set();
|
|
8278
|
+
// 先把显式别名登记为保留名,自动别名不能撞上
|
|
8279
|
+
const reservedPrefixes = new Set();
|
|
8191
8280
|
for (const item of items) {
|
|
8192
|
-
if (item
|
|
8193
|
-
|
|
8194
|
-
|
|
8195
|
-
}
|
|
8281
|
+
if (!item) continue;
|
|
8282
|
+
if (item.alias) reservedPrefixes.add(String(item.alias).toLowerCase());
|
|
8283
|
+
else if (item.subquery && item.subquery.alias) reservedPrefixes.add(String(item.subquery.alias).toLowerCase());
|
|
8196
8284
|
}
|
|
8197
|
-
const autoAliasMap = new Map();
|
|
8198
8285
|
let autoIdx = 0;
|
|
8286
|
+
const nextAutoAlias = () => {
|
|
8287
|
+
let name;
|
|
8288
|
+
do { autoIdx++; name = `t${autoIdx}`; }
|
|
8289
|
+
while (reservedPrefixes.has(name.toLowerCase()) || usedPrefixes.has(name.toLowerCase()));
|
|
8290
|
+
return name;
|
|
8291
|
+
};
|
|
8199
8292
|
const prefix = item => {
|
|
8200
|
-
if (item
|
|
8201
|
-
if (item
|
|
8202
|
-
|
|
8203
|
-
if (item.
|
|
8204
|
-
|
|
8205
|
-
|
|
8206
|
-
|
|
8207
|
-
|
|
8208
|
-
|
|
8209
|
-
|
|
8210
|
-
|
|
8293
|
+
if (!item) return null;
|
|
8294
|
+
if (autoAliasMap.has(item)) return autoAliasMap.get(item);
|
|
8295
|
+
let p;
|
|
8296
|
+
if (item.alias) p = item.alias;
|
|
8297
|
+
else if (item.subquery) p = item.subquery.alias || item.alias || nextAutoAlias();
|
|
8298
|
+
else if (item.table) {
|
|
8299
|
+
p = item.table;
|
|
8300
|
+
if (usedPrefixes.has(String(p).toLowerCase())) p = nextAutoAlias();
|
|
8301
|
+
} else p = nextAutoAlias();
|
|
8302
|
+
usedPrefixes.add(String(p).toLowerCase());
|
|
8303
|
+
autoAliasMap.set(item, p);
|
|
8304
|
+
return p;
|
|
8211
8305
|
};
|
|
8212
8306
|
|
|
8213
8307
|
// 读第一表
|
|
@@ -8574,13 +8668,8 @@ class SQLExecutor {
|
|
|
8574
8668
|
};
|
|
8575
8669
|
const cmp = (a, b) => {
|
|
8576
8670
|
for (const o of statement.orderBy) {
|
|
8577
|
-
const
|
|
8578
|
-
|
|
8579
|
-
if (av === bv || (av === undefined && bv === undefined)) continue;
|
|
8580
|
-
if (av === undefined || av === null) return o.dir === 'asc' ? -1 : 1;
|
|
8581
|
-
if (bv === undefined || bv === null) return o.dir === 'asc' ? 1 : -1;
|
|
8582
|
-
const r = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv));
|
|
8583
|
-
if (r !== 0) return o.dir === 'asc' ? r : -r;
|
|
8671
|
+
const r = compareSqlValues(ordVal(a.row, o), ordVal(b.row, o), o.dir);
|
|
8672
|
+
if (r !== 0) return r;
|
|
8584
8673
|
}
|
|
8585
8674
|
return 0;
|
|
8586
8675
|
};
|
|
@@ -8657,14 +8746,9 @@ class SQLExecutor {
|
|
|
8657
8746
|
const cmp = (a, b) => {
|
|
8658
8747
|
for (let i = 0; i < ordKeys.length; i++) {
|
|
8659
8748
|
const k = ordKeys[i];
|
|
8660
|
-
|
|
8661
|
-
const
|
|
8662
|
-
if (
|
|
8663
|
-
if (av === undefined || av === null) return -1 * k.dir;
|
|
8664
|
-
if (bv === undefined || bv === null) return 1 * k.dir;
|
|
8665
|
-
// P2-1: localeCompare 对字符串排序受 locale 影响,应使用简单字符串比较
|
|
8666
|
-
const r = typeof av === 'number' && typeof bv === 'number' ? av - bv : (String(av) < String(bv) ? -1 : String(av) > String(bv) ? 1 : 0);
|
|
8667
|
-
if (r !== 0) return r * k.dir;
|
|
8749
|
+
// P2-1: 字符串排序不走 localeCompare(受 locale 影响),统一在 compareSqlValues 里处理
|
|
8750
|
+
const r = compareSqlValues(k.at(a), k.at(b), k.dir === 1 ? 'asc' : 'desc');
|
|
8751
|
+
if (r !== 0) return r;
|
|
8668
8752
|
}
|
|
8669
8753
|
return 0;
|
|
8670
8754
|
};
|
|
@@ -8970,7 +9054,9 @@ function applyParams(sql, values) {
|
|
|
8970
9054
|
const args = values || [];
|
|
8971
9055
|
let count = 0;
|
|
8972
9056
|
let out = '';
|
|
8973
|
-
let idx = 0;
|
|
9057
|
+
let idx = 0; // 匿名 ? 的"下一个未占用槽"游标
|
|
9058
|
+
const used = new Set(); // 已被编号占位符 ?N/$N 占用的参数槽
|
|
9059
|
+
let hasIndexed = false; // 是否出现过编号占位符(混用时 Too many 检查会误判)
|
|
8974
9060
|
let inStr = null;
|
|
8975
9061
|
let i = 0;
|
|
8976
9062
|
const named = {};
|
|
@@ -8979,6 +9065,8 @@ function applyParams(sql, values) {
|
|
|
8979
9065
|
hasNamed = true;
|
|
8980
9066
|
}
|
|
8981
9067
|
const n = sql.length;
|
|
9068
|
+
// #92:匿名 ? 按顺序消费"尚未被编号占位符占用"的最小槽,避免编号 ?N 劫持游标。
|
|
9069
|
+
const nextFree = () => { while (used.has(idx)) idx++; return idx; };
|
|
8982
9070
|
while (i < n) {
|
|
8983
9071
|
const c = sql[i];
|
|
8984
9072
|
if (inStr) {
|
|
@@ -9007,8 +9095,14 @@ function applyParams(sql, values) {
|
|
|
9007
9095
|
continue;
|
|
9008
9096
|
}
|
|
9009
9097
|
if (c === '?' && sql[i + 1] === '?') {
|
|
9010
|
-
if (
|
|
9011
|
-
|
|
9098
|
+
if (hasNamed) { out += escapeId(args['@@']); }
|
|
9099
|
+
else {
|
|
9100
|
+
const k = nextFree();
|
|
9101
|
+
if (k >= args.length) throw new Error('Not enough parameters for SQL: expected ' + (count + 1));
|
|
9102
|
+
out += escapeId(args[k]);
|
|
9103
|
+
used.add(k);
|
|
9104
|
+
idx++;
|
|
9105
|
+
}
|
|
9012
9106
|
count++;
|
|
9013
9107
|
i += 2;
|
|
9014
9108
|
continue;
|
|
@@ -9026,14 +9120,21 @@ function applyParams(sql, values) {
|
|
|
9026
9120
|
} else {
|
|
9027
9121
|
if (n - 1 >= args.length) throw new Error(`Not enough parameters for SQL: expected ?${n}`);
|
|
9028
9122
|
out += escapeValue(args[n - 1]);
|
|
9029
|
-
|
|
9123
|
+
used.add(n - 1);
|
|
9124
|
+
hasIndexed = true;
|
|
9030
9125
|
}
|
|
9031
9126
|
count++;
|
|
9032
9127
|
i = j;
|
|
9033
9128
|
continue;
|
|
9034
9129
|
}
|
|
9035
|
-
if (
|
|
9036
|
-
|
|
9130
|
+
if (hasNamed) { out += escapeValue(args['?']); }
|
|
9131
|
+
else {
|
|
9132
|
+
const k = nextFree();
|
|
9133
|
+
if (k >= args.length) throw new Error('Not enough parameters for SQL: expected ' + (count + 1));
|
|
9134
|
+
out += escapeValue(args[k]);
|
|
9135
|
+
used.add(k);
|
|
9136
|
+
idx++;
|
|
9137
|
+
}
|
|
9037
9138
|
count++;
|
|
9038
9139
|
i++;
|
|
9039
9140
|
continue;
|
|
@@ -9065,7 +9166,8 @@ function applyParams(sql, values) {
|
|
|
9065
9166
|
} else {
|
|
9066
9167
|
if (n - 1 >= args.length) throw new Error(`Not enough parameters for SQL: expected $${n}`);
|
|
9067
9168
|
out += escapeValue(args[n - 1]);
|
|
9068
|
-
|
|
9169
|
+
used.add(n - 1);
|
|
9170
|
+
hasIndexed = true;
|
|
9069
9171
|
}
|
|
9070
9172
|
count++;
|
|
9071
9173
|
i = j;
|
|
@@ -9086,7 +9188,9 @@ function applyParams(sql, values) {
|
|
|
9086
9188
|
out += c;
|
|
9087
9189
|
i++;
|
|
9088
9190
|
}
|
|
9089
|
-
|
|
9191
|
+
// #92:混用编号占位符 ?N/$N 时,idx(匿名游标)与 args.length 的"恰好相等"判断
|
|
9192
|
+
// 不可靠(编号占位符会占用任意槽),会误报 Too many。纯匿名场景保留严格检查。
|
|
9193
|
+
if (!hasNamed && !hasIndexed && idx !== args.length) {
|
|
9090
9194
|
throw new Error(`Too many parameters for SQL: got ${args.length}, expected ${count}`);
|
|
9091
9195
|
}
|
|
9092
9196
|
return out;
|
package/lib/sqlite_compat.js
CHANGED
|
@@ -296,7 +296,13 @@ class Statement {
|
|
|
296
296
|
|
|
297
297
|
all(...params) {
|
|
298
298
|
const r = this._call('all', params.length > 0 ? params : undefined);
|
|
299
|
-
|
|
299
|
+
// #87:raw() 只是输出格式开关(对象行 → 值数组),不能重新执行 SQL。
|
|
300
|
+
// 此前 .raw(true).all() 再调 _call('raw') 导致 INSERT/DELETE 重复执行(数据损坏)。
|
|
301
|
+
if (this._rawMode) {
|
|
302
|
+
return Array.isArray(r)
|
|
303
|
+
? r.map(row => (row && typeof row === 'object' && !Array.isArray(row)) ? Object.values(row) : row)
|
|
304
|
+
: r;
|
|
305
|
+
}
|
|
300
306
|
if (this._pluck) {
|
|
301
307
|
const cols = r && r.length > 0 ? Object.keys(r[0]) : [];
|
|
302
308
|
return cols.length > 0 ? r.map(row => row[cols[0]]) : [];
|
package/lib/updater.js
CHANGED
|
@@ -45,21 +45,46 @@ function parseVersion(v) {
|
|
|
45
45
|
const x = parseInt(n, 10);
|
|
46
46
|
return Number.isFinite(x) ? x : 0;
|
|
47
47
|
});
|
|
48
|
-
while (nums.length < 3) nums.push(0);
|
|
49
48
|
return { nums, pre };
|
|
50
49
|
}
|
|
51
50
|
|
|
52
|
-
|
|
51
|
+
// #90:prerelease 标识符按 semver 规则比较:数字标识符按数值、字母按字典序、
|
|
52
|
+
// 数字 > 字母、长度长者大。此前用 A.pre > B.pre 字符串比较,'alpha.10' < 'alpha.9' 误判。
|
|
53
|
+
function comparePre(a, b) {
|
|
54
|
+
if (a === b) return 0;
|
|
55
|
+
if (!a) return 1; // 无 prerelease > 有 prerelease
|
|
56
|
+
if (!b) return -1;
|
|
57
|
+
const A = a.split('.');
|
|
58
|
+
const B = b.split('.');
|
|
59
|
+
const len = Math.max(A.length, B.length);
|
|
60
|
+
for (let i = 0; i < len; i++) {
|
|
61
|
+
const x = A[i], y = B[i];
|
|
62
|
+
if (x === undefined) return -1;
|
|
63
|
+
if (y === undefined) return 1;
|
|
64
|
+
const xn = /^\d+$/.test(x), yn = /^\d+$/.test(y);
|
|
65
|
+
if (xn && yn) {
|
|
66
|
+
const xi = parseInt(x, 10), yi = parseInt(y, 10);
|
|
67
|
+
if (xi !== yi) return xi > yi ? 1 : -1;
|
|
68
|
+
} else if (xn !== yn) {
|
|
69
|
+
return xn ? 1 : -1; // 数字标识符 > 字母标识符
|
|
70
|
+
} else if (x !== y) {
|
|
71
|
+
return x > y ? 1 : -1;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return 0;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** semver-ish 比较:a < b → -1,相等 → 0,a > b → 1(prerelease 视为更低)。
|
|
78
|
+
* #90:支持 4+ 段版本号(此前截断为 3 段,1.2.3.4 与 1.2.3 被误判相等)。 */
|
|
53
79
|
function compareVersions(a, b) {
|
|
54
80
|
const A = parseVersion(a);
|
|
55
81
|
const B = parseVersion(b);
|
|
56
|
-
|
|
57
|
-
|
|
82
|
+
const len = Math.max(A.nums.length, B.nums.length);
|
|
83
|
+
for (let i = 0; i < len; i++) {
|
|
84
|
+
const x = A.nums[i] || 0, y = B.nums[i] || 0;
|
|
85
|
+
if (x !== y) return x > y ? 1 : -1;
|
|
58
86
|
}
|
|
59
|
-
|
|
60
|
-
if (!A.pre) return 1;
|
|
61
|
-
if (!B.pre) return -1;
|
|
62
|
-
return A.pre > B.pre ? 1 : -1;
|
|
87
|
+
return comparePre(A.pre, B.pre);
|
|
63
88
|
}
|
|
64
89
|
|
|
65
90
|
function isNewer(latest, current) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jsql-neo",
|
|
3
|
-
"version": "6.6.
|
|
3
|
+
"version": "6.6.4",
|
|
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",
|
|
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",
|
|
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",
|
|
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",
|
|
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,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,154 @@
|
|
|
1
|
+
// 回归测试:Issue #86-#99
|
|
2
|
+
const Database = require('../lib/database');
|
|
3
|
+
const { executeSQL, applyParams, splitStatements, parseSQL } = require('../lib/sql');
|
|
4
|
+
const { Datastore } = require('../lib/nedb_compat');
|
|
5
|
+
const Cache = require('../lib/cache');
|
|
6
|
+
const updater = require('../lib/updater');
|
|
7
|
+
const { decodeBinaryParam } = require('../lib/pg_server');
|
|
8
|
+
const { createMysqlServer, MysqlConnection } = require('../lib/mysql_server');
|
|
9
|
+
const sqliteCompat = require('../lib/sqlite_compat');
|
|
10
|
+
|
|
11
|
+
let pass = 0, fail = 0;
|
|
12
|
+
function ok(name, cond, extra) {
|
|
13
|
+
if (cond) { pass++; console.log('[OK] ', name); }
|
|
14
|
+
else { fail++; console.log('[FAIL]', name, extra !== undefined ? ' -> ' + JSON.stringify(extra).slice(0, 240) : ''); }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
(async () => {
|
|
18
|
+
// #86 ON DUPLICATE VALUES(a)+1 表达式
|
|
19
|
+
{
|
|
20
|
+
const db = new Database(':memory:');
|
|
21
|
+
await executeSQL(db, "CREATE TABLE t (id INT PRIMARY KEY, a INT, b INT)");
|
|
22
|
+
await executeSQL(db, "INSERT INTO t VALUES (1,10,3)");
|
|
23
|
+
await executeSQL(db, "INSERT INTO t (id,a,b) VALUES (1,100,200) ON DUPLICATE KEY UPDATE a=VALUES(a)+1, b=VALUES(b)");
|
|
24
|
+
const r = await executeSQL(db, "SELECT * FROM t");
|
|
25
|
+
ok('#86 VALUES(a)+1 → a=101', r.rows[0][1] === 101, r.rows[0]);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// #87 sqlite raw(true).all() 不重复执行
|
|
29
|
+
{
|
|
30
|
+
const db = new sqliteCompat.Database(':memory:');
|
|
31
|
+
db.exec('CREATE TABLE t (a INT)');
|
|
32
|
+
db.prepare('INSERT INTO t(a) VALUES (1)').raw(true).all();
|
|
33
|
+
const n = db.prepare('SELECT COUNT(*) c FROM t').get();
|
|
34
|
+
ok('#87 raw(true).all() 只执行一次', n.c === 1, n);
|
|
35
|
+
const rows = db.prepare('SELECT a FROM t').raw(true).all();
|
|
36
|
+
ok('#87 raw 输出数组格式', JSON.stringify(rows) === '[[1]]', rows);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// #88 $regex 字符串模式
|
|
40
|
+
{
|
|
41
|
+
const ds = new Datastore({ inMemoryOnly: true });
|
|
42
|
+
await ds.loadDatabase();
|
|
43
|
+
await ds.insert({ name: 'alice' }); await ds.insert({ name: 'bob' }); await ds.insert({ name: 'charlie' });
|
|
44
|
+
const r = await ds.find({ name: { $regex: '^al' } });
|
|
45
|
+
ok('#88 $regex ^al 只返回 alice', r.length === 1, r.length);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// #89 lrange 负索引越界
|
|
49
|
+
{
|
|
50
|
+
const c = new Cache();
|
|
51
|
+
c.rpush('k', 'a', 'b', 'c');
|
|
52
|
+
const out = c.lrange('k', 0, -5);
|
|
53
|
+
ok('#89 lrange(0,-5) → ["a"]', out.join(',') === 'a', out);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// #90 updater 版本比较
|
|
57
|
+
{
|
|
58
|
+
ok('#90 alpha.10 > alpha.9', updater.isNewer('1.0.0-alpha.10', '1.0.0-alpha.9') === true, updater.isNewer('1.0.0-alpha.10', '1.0.0-alpha.9'));
|
|
59
|
+
ok('#90 1.2.3.4 > 1.2.3', updater.compareVersions('1.2.3.4', '1.2.3') > 0, updater.compareVersions('1.2.3.4', '1.2.3'));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// #91 多语句协议(fake connection 应产生 2 个结果集)
|
|
63
|
+
{
|
|
64
|
+
const server = createMysqlServer({ safety: false });
|
|
65
|
+
await server._getEngine();
|
|
66
|
+
const socket = { write: () => {}, destroy: () => {}, remoteAddress: 'x', on: () => {} };
|
|
67
|
+
const conn = new MysqlConnection(socket, server);
|
|
68
|
+
conn.authenticated = true; conn.multiStatements = true;
|
|
69
|
+
await new Promise((res) => { conn._handleQuery('SELECT 1; SELECT 2;'); setTimeout(res, 800); });
|
|
70
|
+
ok('#91 多语句无异常', true);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// #92 applyParams 混用 ?N 与 ?
|
|
74
|
+
{
|
|
75
|
+
const a = applyParams("SELECT * FROM t WHERE a=? AND b=?2", [10, 20, 30]);
|
|
76
|
+
ok('#92 a=? AND b=?2 → a=10 b=20', a.includes('a=10') && a.includes('b=20'), a);
|
|
77
|
+
const b = applyParams("SELECT * FROM t WHERE b=?2 AND a=?", [10, 20, 30]);
|
|
78
|
+
ok('#92 b=?2 AND a=? → b=20 a=10', b.includes('b=20') && b.includes('a=10'), b);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// #93 pg 二进制参数解码
|
|
82
|
+
{
|
|
83
|
+
const i4 = Buffer.from([0, 0, 0, 42]);
|
|
84
|
+
ok('#93 int4 binary=42', decodeBinaryParam(i4, 23) === 42, decodeBinaryParam(i4, 23));
|
|
85
|
+
const i8 = Buffer.alloc(8); i8.writeBigInt64BE(1234567890123n);
|
|
86
|
+
ok('#93 int8 binary', decodeBinaryParam(i8, 20) === 1234567890123n, decodeBinaryParam(i8, 20));
|
|
87
|
+
const f8 = Buffer.alloc(8); f8.writeDoubleBE(3.14);
|
|
88
|
+
ok('#93 float8 binary', decodeBinaryParam(f8, 701) === 3.14, decodeBinaryParam(f8, 701));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// #94 数值 LIKE
|
|
92
|
+
{
|
|
93
|
+
const db = new Database(':memory:');
|
|
94
|
+
await executeSQL(db, "CREATE TABLE t (id INT PRIMARY KEY, a INT)");
|
|
95
|
+
await executeSQL(db, "INSERT INTO t VALUES (1,10),(2,20)");
|
|
96
|
+
const r = await executeSQL(db, "SELECT id FROM t WHERE a LIKE '1%'");
|
|
97
|
+
ok('#94 a LIKE \'1%\' → id=1', r.rows.map(x => x[0]).join(',') === '1', r.rows);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// #95 COM_PROCESS_INFO 用 lenenc string
|
|
101
|
+
{
|
|
102
|
+
const server = createMysqlServer({ safety: false });
|
|
103
|
+
await server._getEngine();
|
|
104
|
+
const socket = { write: () => {}, destroy: () => {}, remoteAddress: 'x', on: () => {} };
|
|
105
|
+
const conn = new MysqlConnection(socket, server);
|
|
106
|
+
conn.authenticated = true;
|
|
107
|
+
const sent = [];
|
|
108
|
+
conn._send = (b) => { sent.push(Buffer.from(b)); };
|
|
109
|
+
conn._handlePacket(Buffer.from([0x0a]), 0);
|
|
110
|
+
let found = false;
|
|
111
|
+
for (const p of sent) for (let i = 0; i < p.length - 1; i++) if (p[i] === 0x01 && p[i + 1] === 0x31) found = true;
|
|
112
|
+
ok('#95 数据行含 lenenc 0x01 0x31', found);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// #96 CAST DECIMAL 精度
|
|
116
|
+
{
|
|
117
|
+
const db = new Database(':memory:');
|
|
118
|
+
const r = await executeSQL(db, "SELECT CAST(123.456 AS DECIMAL(10,2))");
|
|
119
|
+
ok('#96 CAST DECIMAL(10,2) → 123.46', r.rows[0][0] === 123.46, r.rows[0][0]);
|
|
120
|
+
const r2 = await executeSQL(db, "SELECT CAST(123.456 AS DECIMAL(10,0))");
|
|
121
|
+
ok('#96 CAST DECIMAL(10,0) → 123', r2.rows[0][0] === 123, r2.rows[0][0]);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// #97 _route 多限定表
|
|
125
|
+
{
|
|
126
|
+
const server = createMysqlServer({ safety: false });
|
|
127
|
+
await server._getEngine();
|
|
128
|
+
const sql = "SELECT * FROM db1.t JOIN db1.u ON t.id=u.id WHERE name='db1.t'";
|
|
129
|
+
const routed = await server._route(parseSQL(sql), sql, null, null);
|
|
130
|
+
ok('#97 多表改写 + 字符串保留', routed.sql === "SELECT * FROM t JOIN u ON t.id=u.id WHERE name='db1.t'", routed.sql);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// #98 字符串列 MIN/MAX 字典序
|
|
134
|
+
{
|
|
135
|
+
const db = new Database(':memory:');
|
|
136
|
+
await executeSQL(db, "CREATE TABLE s (x STRING)");
|
|
137
|
+
await executeSQL(db, "INSERT INTO s VALUES ('2'),('100'),('9')");
|
|
138
|
+
const r = await executeSQL(db, "SELECT MIN(x), MAX(x) FROM s");
|
|
139
|
+
ok('#98 MIN=100 MAX=9 字典序', r.rows[0][0] === '100' && r.rows[0][1] === '9', r.rows[0]);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// #99 ON DUPLICATE 裸列名
|
|
143
|
+
{
|
|
144
|
+
const db = new Database(':memory:');
|
|
145
|
+
await executeSQL(db, "CREATE TABLE t (id INT PRIMARY KEY, cnt INT, other INT)");
|
|
146
|
+
await executeSQL(db, "INSERT INTO t VALUES (1,5,7)");
|
|
147
|
+
await executeSQL(db, "INSERT INTO t (id,cnt,other) VALUES (1,5,7) ON DUPLICATE KEY UPDATE cnt=cnt+1, other=other");
|
|
148
|
+
const r = await executeSQL(db, "SELECT * FROM t");
|
|
149
|
+
ok('#99 other=other 不崩溃且 cnt=6', r.rows[0][1] === 6 && r.rows[0][2] === 7, r.rows[0]);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
console.log(`\n${pass} passed, ${fail} failed`);
|
|
153
|
+
process.exit(fail === 0 ? 0 : 1);
|
|
154
|
+
})().catch(e => { console.error('FATAL', e); process.exit(1); });
|