jsql-neo 6.8.4 → 6.8.7
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/bin/jsql +5 -2
- package/index.js +1 -1
- package/lib/bigint_json.js +12 -0
- package/lib/cache.js +26 -4
- package/lib/columnar_fast.js +3 -1
- package/lib/database.js +171 -47
- package/lib/date-types.js +27 -19
- package/lib/errors.js +4 -0
- package/lib/migrate.js +20 -8
- package/lib/mongo_server.js +238 -20
- package/lib/mysql_server.js +27 -22
- package/lib/nedb_compat.js +101 -11
- package/lib/pg_server.js +53 -12
- package/lib/redis_server.js +198 -67
- package/lib/sql.js +228 -35
- package/lib/sqlite_compat.js +17 -0
- package/lib/table.js +55 -12
- package/package.json +3 -3
- package/test/extra-coverage.test.js +4 -3
- package/test/issue-162-179.test.js +220 -0
- package/test/issue-181-186.test.js +153 -0
- package/test/issue-187.test.js +36 -0
- package/test/issue-188-237.test.js +481 -0
- package/test/issue-238-241.test.js +65 -0
- package/test/issue-63-68.test.js +2 -2
package/lib/sql.js
CHANGED
|
@@ -402,7 +402,9 @@ function tokenize(sql) {
|
|
|
402
402
|
// 大数 parseInt 也丢失精度。统一用 Number()(bigint 用 BigInt())。
|
|
403
403
|
let numVal;
|
|
404
404
|
if (raw.includes('.') || raw.includes('e') || raw.includes('E')) {
|
|
405
|
-
|
|
405
|
+
// #214:高精度十进制字面量保留原始文本,避免先过 double 丢精度
|
|
406
|
+
const digits = raw.replace(/^[+-]/, '').replace('.', '').replace(/^0+/, '');
|
|
407
|
+
numVal = (raw.includes('.') && digits.length > 15) ? new DecimalLiteral(raw) : parseFloat(raw);
|
|
406
408
|
} else {
|
|
407
409
|
const n = BigInt(raw);
|
|
408
410
|
numVal = n <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(n) : n;
|
|
@@ -832,8 +834,11 @@ class Parser {
|
|
|
832
834
|
uCols.push(this.parseTableName());
|
|
833
835
|
}
|
|
834
836
|
this.expect('op', ')');
|
|
835
|
-
|
|
836
|
-
|
|
837
|
+
// #205:多列表级 UNIQUE 是复合唯一组,不能降级为单列 unique
|
|
838
|
+
if (uCols.length === 1) {
|
|
839
|
+
if (schema[uCols[0]]) schema[uCols[0]].unique = true;
|
|
840
|
+
} else {
|
|
841
|
+
(schema.__uniqueGroups__ = schema.__uniqueGroups__ || []).push(uCols);
|
|
837
842
|
}
|
|
838
843
|
}
|
|
839
844
|
} else if (t.type === 'keyword' && t.value === 'CONSTRAINT') {
|
|
@@ -922,6 +927,9 @@ class Parser {
|
|
|
922
927
|
const mapped = typeMap[type];
|
|
923
928
|
if (!mapped) throw new Error(`Unsupported column type: ${typeTok.value}`);
|
|
924
929
|
def.type = mapped;
|
|
930
|
+
// #209/#214:保留 BIGINT / NUMERIC 的原始类型标记,供 MySQL/PG 线协议通告正确类型
|
|
931
|
+
if (type === 'bigint' || type === 'bigserial') def.intType = 'bigint';
|
|
932
|
+
if (type === 'numeric' || type === 'decimal') def.numericType = 'numeric';
|
|
925
933
|
// JSON / JSONB 列保留原始标记,供数据层校验非法 JSON({bad json 这类字符串会被 JSON.parse 拒绝)
|
|
926
934
|
if (type === 'json' || type === 'jsonb') def.jsonType = true;
|
|
927
935
|
if (/^(BIG)?SERIAL$/i.test(typeRaw)) { def.autoIncrement = true; def.required = true; }
|
|
@@ -1241,6 +1249,10 @@ class Parser {
|
|
|
1241
1249
|
const dataRows = rows.map(vals => {
|
|
1242
1250
|
const row = {};
|
|
1243
1251
|
if (columns) {
|
|
1252
|
+
// #203:值数必须与列清单长度一致
|
|
1253
|
+
if (vals.length !== columns.length) {
|
|
1254
|
+
throw createError('ER_WRONG_VALUE_COUNT_ON_ROW', 1);
|
|
1255
|
+
}
|
|
1244
1256
|
columns.forEach((c, idx) => { row[c] = vals[idx] !== undefined ? vals[idx] : null; });
|
|
1245
1257
|
} else {
|
|
1246
1258
|
vals.forEach((v, idx) => { row['col' + (idx + 1)] = v; });
|
|
@@ -1787,23 +1799,38 @@ class Parser {
|
|
|
1787
1799
|
let limit = null, offset = 0;
|
|
1788
1800
|
if (this.isKeyword('LIMIT')) {
|
|
1789
1801
|
this.next();
|
|
1790
|
-
limit = this.
|
|
1791
|
-
if (
|
|
1792
|
-
if (
|
|
1793
|
-
if (this.isKeyword('OFFSET')) { this.next(); offset = this.parseValue(); if (typeof offset === 'bigint') offset = Number(offset <= BigInt(Number.MAX_SAFE_INTEGER) ? offset : BigInt(Number.MAX_SAFE_INTEGER)); if (typeof offset === 'number' && offset < 0) throw new Error(`OFFSET must be a non-negative integer, got ${offset}`); }
|
|
1794
|
-
else if (this.peek().type === 'op' && this.peek().value === ',') { this.next(); offset = limit; limit = this.parseValue(); if (typeof limit === 'bigint') limit = Number(limit <= BigInt(Number.MAX_SAFE_INTEGER) ? limit : BigInt(Number.MAX_SAFE_INTEGER)); if (typeof limit === 'number' && limit < 0) throw new Error(`LIMIT must be a non-negative integer, got ${limit}`); }
|
|
1802
|
+
limit = this._parseLimitCount('LIMIT');
|
|
1803
|
+
if (this.isKeyword('OFFSET')) { this.next(); offset = this._parseLimitCount('OFFSET'); }
|
|
1804
|
+
else if (this.peek().type === 'op' && this.peek().value === ',') { this.next(); offset = limit; limit = this._parseLimitCount('LIMIT'); }
|
|
1795
1805
|
}
|
|
1796
1806
|
// OFFSET without LIMIT (MySQL compatible)
|
|
1797
1807
|
if (limit === null && this.isKeyword('OFFSET')) {
|
|
1798
1808
|
this.next();
|
|
1799
|
-
offset = this.
|
|
1800
|
-
if (typeof offset === 'bigint') offset = Number(offset <= BigInt(Number.MAX_SAFE_INTEGER) ? offset : BigInt(Number.MAX_SAFE_INTEGER));
|
|
1801
|
-
if (typeof offset === 'number' && offset < 0) throw new Error(`OFFSET must be a non-negative integer, got ${offset}`);
|
|
1809
|
+
offset = this._parseLimitCount('OFFSET');
|
|
1802
1810
|
limit = Number.MAX_SAFE_INTEGER;
|
|
1803
1811
|
}
|
|
1804
1812
|
return { limit, offset };
|
|
1805
1813
|
}
|
|
1806
1814
|
|
|
1815
|
+
/**
|
|
1816
|
+
* #186:LIMIT/OFFSET 只接受非负整数字面量。
|
|
1817
|
+
* 通用 parseValue 会把 `2+1` 解析成表达式、把 1.9 当合法数字,
|
|
1818
|
+
* 执行层对非 number 直接忽略 → 静默 0 行。这里在解析阶段就拒绝。
|
|
1819
|
+
*/
|
|
1820
|
+
_parseLimitCount(kind) {
|
|
1821
|
+
const v = this.parseValue();
|
|
1822
|
+
if (typeof v === 'bigint') {
|
|
1823
|
+
if (v < 0n || v > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
1824
|
+
throw createError('ER_PARSE_ERROR', `${kind} must be a non-negative integer, got ${v}`);
|
|
1825
|
+
}
|
|
1826
|
+
return Number(v);
|
|
1827
|
+
}
|
|
1828
|
+
if (typeof v !== 'number' || !Number.isInteger(v) || v < 0 || !Number.isSafeInteger(v)) {
|
|
1829
|
+
throw createError('ER_PARSE_ERROR', `${kind} must be a non-negative integer`);
|
|
1830
|
+
}
|
|
1831
|
+
return v;
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1807
1834
|
/**
|
|
1808
1835
|
* 集合运算后缀(#60):UNION [ALL|DISTINCT] / INTERSECT / EXCEPT。
|
|
1809
1836
|
* 右侧操作数允许括号化的 SELECT((SELECT ...))。
|
|
@@ -2013,9 +2040,7 @@ class Parser {
|
|
|
2013
2040
|
}
|
|
2014
2041
|
if (this.isKeyword('LIMIT')) {
|
|
2015
2042
|
this.next();
|
|
2016
|
-
limit = this.
|
|
2017
|
-
if (typeof limit === 'bigint') limit = Number(limit <= BigInt(Number.MAX_SAFE_INTEGER) ? limit : BigInt(Number.MAX_SAFE_INTEGER));
|
|
2018
|
-
if (typeof limit === 'number' && limit < 0) throw new Error(`LIMIT must be a non-negative integer, got ${limit}`);
|
|
2043
|
+
limit = this._parseLimitCount('LIMIT');
|
|
2019
2044
|
}
|
|
2020
2045
|
const returning = this.parseOptionalReturning();
|
|
2021
2046
|
this.optionalTailSemicolon();
|
|
@@ -2044,9 +2069,7 @@ class Parser {
|
|
|
2044
2069
|
}
|
|
2045
2070
|
if (this.isKeyword('LIMIT')) {
|
|
2046
2071
|
this.next();
|
|
2047
|
-
limit = this.
|
|
2048
|
-
if (typeof limit === 'bigint') limit = Number(limit <= BigInt(Number.MAX_SAFE_INTEGER) ? limit : BigInt(Number.MAX_SAFE_INTEGER));
|
|
2049
|
-
if (typeof limit === 'number' && limit < 0) throw new Error(`LIMIT must be a non-negative integer, got ${limit}`);
|
|
2072
|
+
limit = this._parseLimitCount('LIMIT');
|
|
2050
2073
|
}
|
|
2051
2074
|
const returning = this.parseOptionalReturning();
|
|
2052
2075
|
this.optionalTailSemicolon();
|
|
@@ -2854,17 +2877,20 @@ class Parser {
|
|
|
2854
2877
|
}
|
|
2855
2878
|
const first = this.parseOperand();
|
|
2856
2879
|
let target = null;
|
|
2880
|
+
let commaForm = false;
|
|
2857
2881
|
if (this.isWord('FROM')) {
|
|
2858
2882
|
this.next();
|
|
2859
2883
|
target = this.parseOperand();
|
|
2860
2884
|
} else if (this.peek().type === 'op' && this.peek().value === ',') {
|
|
2861
2885
|
this.next();
|
|
2862
2886
|
target = this.parseOperand();
|
|
2887
|
+
commaForm = true;
|
|
2863
2888
|
}
|
|
2864
2889
|
this.expect('op', ')');
|
|
2865
2890
|
// 归一成 TRIM(target[, chars[, spec]]),与 applyScalarFunction 的既有签名兼容
|
|
2866
2891
|
if (target === null) return { type: 'func', name: 'TRIM', args: [first] };
|
|
2867
|
-
|
|
2892
|
+
// #232:逗号两参形式是 TRIM(目标串, 字符集);FROM 形式是 TRIM(字符集 FROM 目标串)
|
|
2893
|
+
const args = commaForm ? [first, target] : [target, first];
|
|
2868
2894
|
if (spec) args.push({ type: 'value', value: spec });
|
|
2869
2895
|
return { type: 'func', name: 'TRIM', args };
|
|
2870
2896
|
}
|
|
@@ -3493,6 +3519,13 @@ function mysqlNum(v) {
|
|
|
3493
3519
|
// 结果信封(rows)里仍会降级成普通字符串(见 finalizeResultBigInts),
|
|
3494
3520
|
// 所以对外 API 与旧行为保持兼容。
|
|
3495
3521
|
// ---------------------------------------------------------------------------
|
|
3522
|
+
class DecimalLiteral {
|
|
3523
|
+
constructor(raw) { this.__decimalRaw = String(raw); }
|
|
3524
|
+
toString() { return this.__decimalRaw; }
|
|
3525
|
+
valueOf() { return Number(this.__decimalRaw); }
|
|
3526
|
+
toJSON() { return this.__decimalRaw; }
|
|
3527
|
+
}
|
|
3528
|
+
|
|
3496
3529
|
class BinaryValue {
|
|
3497
3530
|
constructor(buf) {
|
|
3498
3531
|
this.bytes = Buffer.isBuffer(buf) ? Buffer.from(buf) : Buffer.from(String(buf), 'latin1');
|
|
@@ -3990,6 +4023,12 @@ function resolveOperand(operand, row, ctx) {
|
|
|
3990
4023
|
function parseSqlDate(v) {
|
|
3991
4024
|
if (v === null || v === undefined) return null;
|
|
3992
4025
|
if (v instanceof Date) return Number.isNaN(v.getTime()) ? null : v;
|
|
4026
|
+
// #170:数值按 Unix 秒解释(0 = 1970-01-01),与 FROM_UNIXTIME 一致。
|
|
4027
|
+
if (typeof v === 'number') {
|
|
4028
|
+
if (!Number.isFinite(v)) return null;
|
|
4029
|
+
const d = new Date(v * 1000);
|
|
4030
|
+
return Number.isNaN(d.getTime()) ? null : d;
|
|
4031
|
+
}
|
|
3993
4032
|
const ms = parseUtcWallClock(String(v));
|
|
3994
4033
|
return ms === null ? null : new Date(ms);
|
|
3995
4034
|
}
|
|
@@ -4501,6 +4540,27 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4501
4540
|
if (doy < firstSunday) return 0;
|
|
4502
4541
|
return Math.floor((doy - firstSunday) / 7) + 1;
|
|
4503
4542
|
}
|
|
4543
|
+
case 'WEEKOFYEAR': { // ISO 周序(同 WEEK(date,3))
|
|
4544
|
+
const d = parseSqlDate(args[0]);
|
|
4545
|
+
return d ? pgDatePart('week', d) : null;
|
|
4546
|
+
}
|
|
4547
|
+
case 'YEARWEEK': {
|
|
4548
|
+
const d = parseSqlDate(args[0]);
|
|
4549
|
+
if (!d) return null;
|
|
4550
|
+
const mode = args[1] != null ? Number(args[1]) : 3;
|
|
4551
|
+
if (mode === 1 || mode === 3) {
|
|
4552
|
+
const week = pgDatePart('week', d);
|
|
4553
|
+
const thu = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
|
|
4554
|
+
const dow = (thu.getUTCDay() + 6) % 7; // 周一 = 0
|
|
4555
|
+
thu.setUTCDate(thu.getUTCDate() - dow + 3); // 该周星期四决定 ISO 年
|
|
4556
|
+
return thu.getUTCFullYear() * 100 + week;
|
|
4557
|
+
}
|
|
4558
|
+
const week = (() => {
|
|
4559
|
+
const jan1 = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
|
|
4560
|
+
return Math.floor((d - jan1) / 604800000) + 1;
|
|
4561
|
+
})();
|
|
4562
|
+
return d.getUTCFullYear() * 100 + week;
|
|
4563
|
+
}
|
|
4504
4564
|
case 'DAYOFWEEK': { // MySQL:1=周日 … 7=周六
|
|
4505
4565
|
const d = parseSqlDate(args[0]);
|
|
4506
4566
|
return d ? d.getUTCDay() + 1 : null;
|
|
@@ -4651,6 +4711,30 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4651
4711
|
const s = rest - mi * 60;
|
|
4652
4712
|
return sign + String(h).padStart(2, '0') + ':' + pad2(mi) + ':' + pad2(s);
|
|
4653
4713
|
}
|
|
4714
|
+
case 'PERIOD_ADD': {
|
|
4715
|
+
const raw = String(args[0] == null ? '' : args[0]).trim();
|
|
4716
|
+
const n = Number(args[1]);
|
|
4717
|
+
const m = raw.match(/^(\d{2}|\d{4})(\d{2})$/);
|
|
4718
|
+
if (!m || !Number.isFinite(n)) return null;
|
|
4719
|
+
const year = m[1].length === 2 ? 2000 + Number(m[1]) : Number(m[1]);
|
|
4720
|
+
const month = Number(m[2]);
|
|
4721
|
+
if (month < 1 || month > 12) return null;
|
|
4722
|
+
const total = year * 12 + (month - 1) + Math.trunc(n);
|
|
4723
|
+
return Math.floor(total / 12) * 100 + (total % 12) + 1;
|
|
4724
|
+
}
|
|
4725
|
+
case 'TIMESTAMP': {
|
|
4726
|
+
const d = parseSqlDate(args[0]);
|
|
4727
|
+
if (!d) return null;
|
|
4728
|
+
let h = 0, mi = 0, s = 0;
|
|
4729
|
+
if (args[1] != null) {
|
|
4730
|
+
const tm = String(args[1]).trim().match(/^(\d{1,3}):(\d{2})(?::(\d{2}))?$/);
|
|
4731
|
+
if (!tm) return null;
|
|
4732
|
+
h = Number(tm[1]); mi = Number(tm[2]); s = tm[3] === undefined ? 0 : Number(tm[3]);
|
|
4733
|
+
if (h > 23 || mi > 59 || s > 59) return null;
|
|
4734
|
+
}
|
|
4735
|
+
const out = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), h, mi, s));
|
|
4736
|
+
return fmtSqlDate(false, out);
|
|
4737
|
+
}
|
|
4654
4738
|
case 'PERIOD_DIFF': {
|
|
4655
4739
|
const p1 = String(args[0] == null ? '' : args[0]);
|
|
4656
4740
|
const p2 = String(args[1] == null ? '' : args[1]);
|
|
@@ -4946,6 +5030,7 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4946
5030
|
case 'DEGREES': return args[0] == null ? null : finiteOrNull(args[0] * 180 / Math.PI);
|
|
4947
5031
|
case 'RADIANS': return args[0] == null ? null : finiteOrNull(args[0] * Math.PI / 180);
|
|
4948
5032
|
case 'IFNULL': case 'NVL': return args[0] != null ? args[0] : args[1];
|
|
5033
|
+
case 'ISNULL': return args[0] === null || args[0] === undefined ? 1 : 0;
|
|
4949
5034
|
case 'COALESCE': {
|
|
4950
5035
|
// 不能直接 return find(...):全都取不到值时 find 返回 undefined,
|
|
4951
5036
|
// 而 undefined 在结果行里会整个键消失(JSON.stringify 会丢掉它),
|
|
@@ -4954,8 +5039,15 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4954
5039
|
return hit === undefined ? null : hit;
|
|
4955
5040
|
}
|
|
4956
5041
|
case 'NULLIF': return sqlValuesEqual(args[0], args[1]) ? null : args[0];
|
|
4957
|
-
case 'IF': return args[0] ? args[1] : args[2];
|
|
4958
|
-
case 'REPLACE':
|
|
5042
|
+
case 'IF': return sqlTruthy(args[0]) ? args[1] : args[2];
|
|
5043
|
+
case 'REPLACE': {
|
|
5044
|
+
// #231:NULL 全传播;空搜索符原样返回,不能按字符拆分
|
|
5045
|
+
if (args[0] == null || args[1] == null || args[2] == null) return null;
|
|
5046
|
+
const s = String(args[0]);
|
|
5047
|
+
const from = String(args[1]);
|
|
5048
|
+
if (from === '') return s;
|
|
5049
|
+
return s.split(from).join(String(args[2]));
|
|
5050
|
+
}
|
|
4959
5051
|
case 'REPEAT': {
|
|
4960
5052
|
// 此前完全缺失,静默返回 null
|
|
4961
5053
|
if (args[0] == null || args[1] == null) return null;
|
|
@@ -4963,7 +5055,7 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4963
5055
|
if (!Number.isFinite(n) || n <= 0) return '';
|
|
4964
5056
|
return String(args[0]).repeat(n);
|
|
4965
5057
|
}
|
|
4966
|
-
case 'SUBSTRING': case 'SUBSTR': {
|
|
5058
|
+
case 'SUBSTRING': case 'SUBSTR': case 'MID': {
|
|
4967
5059
|
if (args[0] == null) return null;
|
|
4968
5060
|
// Issue #111:按 code point 切分,避免把 emoji/增补平面字符劈成孤立代理项
|
|
4969
5061
|
const cps = Array.from(String(args[0]));
|
|
@@ -5565,7 +5657,8 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
5565
5657
|
return jsonContainsValue(data, candidate) ? 1 : 0;
|
|
5566
5658
|
}
|
|
5567
5659
|
default:
|
|
5568
|
-
|
|
5660
|
+
// #185:未知/拼错的函数不能伪装成 NULL,否则 WHERE 里会静默变成 0 行
|
|
5661
|
+
throw createError('ER_FUNCTION_NOT_EXIST', name);
|
|
5569
5662
|
}
|
|
5570
5663
|
}
|
|
5571
5664
|
|
|
@@ -6003,10 +6096,16 @@ function evaluateExpr(expr, row, ctx) {
|
|
|
6003
6096
|
return !!resolveOperand(expr, row, ctx);
|
|
6004
6097
|
case 'regexp': {
|
|
6005
6098
|
const v = resolveOperand(expr.operand, row, ctx);
|
|
6006
|
-
|
|
6099
|
+
// #230:任一操作数为 NULL → UNKNOWN(null),NOT NULL 仍为 NULL
|
|
6100
|
+
if (v === null || v === undefined) return null;
|
|
6101
|
+
if (expr.pattern === null || expr.pattern === undefined) return null;
|
|
6102
|
+
const p = (expr.pattern && typeof expr.pattern === 'object')
|
|
6103
|
+
? resolveOperand(expr.pattern, row, ctx)
|
|
6104
|
+
: expr.pattern;
|
|
6105
|
+
if (p === null || p === undefined) return null;
|
|
6007
6106
|
// REGEXP / RLIKE 历史上就是大小写不敏感的;`~` 敏感、`~*` 不敏感
|
|
6008
6107
|
const binaryCmp = isBinaryNode(expr.operand) || isBinaryNode(expr.pattern);
|
|
6009
|
-
const re = new RegExp(String(
|
|
6108
|
+
const re = new RegExp(String(p), (expr.ci === false || binaryCmp) ? '' : 'i');
|
|
6010
6109
|
const r = re.test(String(v));
|
|
6011
6110
|
return expr.not ? !r : r;
|
|
6012
6111
|
}
|
|
@@ -6300,8 +6399,18 @@ class SQLExecutor {
|
|
|
6300
6399
|
for (const op of statement.ops) {
|
|
6301
6400
|
switch (op.op) {
|
|
6302
6401
|
case 'addColumn': {
|
|
6303
|
-
|
|
6304
|
-
|
|
6402
|
+
// #197:走表层 addColumn,统一注册默认值/约束并回填存量行
|
|
6403
|
+
if (typeof table.addColumn === 'function') {
|
|
6404
|
+
table.addColumn(op.column, op.def);
|
|
6405
|
+
} else {
|
|
6406
|
+
table._schema[op.column] = op.def;
|
|
6407
|
+
}
|
|
6408
|
+
const dv = op.def && op.def.default;
|
|
6409
|
+
for (const row of table._rows) {
|
|
6410
|
+
if (!(op.column in row)) {
|
|
6411
|
+
row[op.column] = dv !== undefined ? (typeof dv === 'function' ? dv() : dv) : null;
|
|
6412
|
+
}
|
|
6413
|
+
}
|
|
6305
6414
|
break;
|
|
6306
6415
|
}
|
|
6307
6416
|
case 'dropColumn': {
|
|
@@ -6475,6 +6584,13 @@ class SQLExecutor {
|
|
|
6475
6584
|
// INSERT ... SELECT:先跑 SELECT,再把结果行映射成待插入行
|
|
6476
6585
|
if (statement.select) {
|
|
6477
6586
|
const res = await this.executeSelect(statement.select);
|
|
6587
|
+
// #202:目标列数与 SELECT 输出列数必须一致,多余的源列不能静默丢弃
|
|
6588
|
+
const targetCols = (statement.columns && statement.columns.length)
|
|
6589
|
+
? statement.columns
|
|
6590
|
+
: Object.keys(schema).filter(c => !(schema[c] && schema[c].autoIncrement));
|
|
6591
|
+
if (res.columns.length !== targetCols.length) {
|
|
6592
|
+
throw createError('ER_WRONG_VALUE_COUNT_ON_ROW', 1);
|
|
6593
|
+
}
|
|
6478
6594
|
const cols = statement.columns && statement.columns.length ? statement.columns : res.columns;
|
|
6479
6595
|
dataRows = res.rows.map(arr => {
|
|
6480
6596
|
const row = {};
|
|
@@ -6487,10 +6603,22 @@ class SQLExecutor {
|
|
|
6487
6603
|
// P2: INSERT 未知列静默接受 → 应报 Unknown column
|
|
6488
6604
|
// 检查 VALUES 数量是否超过列数(无列清单时)
|
|
6489
6605
|
if (!statement.columns || statement.columns.length === 0) {
|
|
6606
|
+
const autoCols = colNames.filter(c => schema[c].autoIncrement);
|
|
6490
6607
|
for (const vals of statement.values) {
|
|
6491
6608
|
if (vals.length > colNames.length) {
|
|
6492
6609
|
throw new Error(`Unknown column in '${statement.name}': VALUES has ${vals.length} values but table has ${colNames.length} columns`);
|
|
6493
6610
|
}
|
|
6611
|
+
// #203:值少于列数同样报 1136;唯一例外是 legacy 的「恰好跳过全部自增列」。
|
|
6612
|
+
if (vals.length < colNames.length && (colNames.length - vals.length) !== autoCols.length) {
|
|
6613
|
+
throw createError('ER_WRONG_VALUE_COUNT_ON_ROW', 1);
|
|
6614
|
+
}
|
|
6615
|
+
}
|
|
6616
|
+
} else {
|
|
6617
|
+
// #203:带列清单时值数必须等于清单列数
|
|
6618
|
+
for (const vals of statement.values) {
|
|
6619
|
+
if (vals.length !== statement.columns.length) {
|
|
6620
|
+
throw createError('ER_WRONG_VALUE_COUNT_ON_ROW', 1);
|
|
6621
|
+
}
|
|
6494
6622
|
}
|
|
6495
6623
|
}
|
|
6496
6624
|
const skipAuto = statement.values[0].length < colNames.length;
|
|
@@ -6696,6 +6824,18 @@ class SQLExecutor {
|
|
|
6696
6824
|
ids = await this.engine.insert(statement.name, toInsert);
|
|
6697
6825
|
await this.engine.flush();
|
|
6698
6826
|
}
|
|
6827
|
+
// #164:自增主键在存储层生成,插入前构造的行快照没有该值;
|
|
6828
|
+
// RETURNING 之前把最终 id 回填,避免返回 null。
|
|
6829
|
+
if (Array.isArray(ids) && ids.length === toInsert.length && schema) {
|
|
6830
|
+
const autoField = Object.keys(schema).find((k) => schema[k] && schema[k].autoIncrement);
|
|
6831
|
+
if (autoField) {
|
|
6832
|
+
for (let i = 0; i < toInsert.length; i++) {
|
|
6833
|
+
if (toInsert[i] && (toInsert[i][autoField] === undefined || toInsert[i][autoField] === null)) {
|
|
6834
|
+
toInsert[i][autoField] = ids[i];
|
|
6835
|
+
}
|
|
6836
|
+
}
|
|
6837
|
+
}
|
|
6838
|
+
}
|
|
6699
6839
|
const out = {
|
|
6700
6840
|
ok: true, type: 'insert', table: statement.name,
|
|
6701
6841
|
affectedRows: toInsert.length + updated,
|
|
@@ -6930,7 +7070,7 @@ class SQLExecutor {
|
|
|
6930
7070
|
}
|
|
6931
7071
|
const all = (await this.engine.find(statement.table, {}, { limit: 1e9, offset: 0 })).map(r => normalizeRow(r, schema));
|
|
6932
7072
|
// UPDATE ... ORDER BY ... LIMIT n:先过滤、排序、截取,再逐行更新
|
|
6933
|
-
let candidates =
|
|
7073
|
+
let candidates = await this._filterMutationRows(statement, all);
|
|
6934
7074
|
if (statement.orderBy) {
|
|
6935
7075
|
const cmp = (a, b) => {
|
|
6936
7076
|
for (const o of statement.orderBy) {
|
|
@@ -6949,7 +7089,8 @@ class SQLExecutor {
|
|
|
6949
7089
|
if (typeof statement.limit === 'number') candidates = candidates.slice(0, statement.limit);
|
|
6950
7090
|
let count = 0;
|
|
6951
7091
|
for (const row of candidates) {
|
|
6952
|
-
|
|
7092
|
+
// #198:复合主键没有单一 id 值,按行对象定位(表层做深相等匹配)
|
|
7093
|
+
const id = pkCols.length > 1 ? row : this._rowPkId(row, pkCols);
|
|
6953
7094
|
if (id !== undefined) {
|
|
6954
7095
|
// 表达式求值用的行要带「表.列」前缀:相关子查询里的 x.id 依赖前缀键解析,
|
|
6955
7096
|
// find() 返回的是无前缀行,直接用会让 x.id → undefined,SET 结果全变 NULL。
|
|
@@ -6967,6 +7108,9 @@ class SQLExecutor {
|
|
|
6967
7108
|
} else {
|
|
6968
7109
|
data[col] = val;
|
|
6969
7110
|
}
|
|
7111
|
+
// #208:MySQL 赋值从左到右求值,后续赋值要看到前面的新值
|
|
7112
|
+
exprRow[col] = data[col];
|
|
7113
|
+
exprRow[statement.table + '.' + col] = data[col];
|
|
6970
7114
|
// H5:UPDATE 也不能把主键改成 NULL,否则这一行丢失身份:
|
|
6971
7115
|
// 主键索引里查不到,后续 updateById/remove 全部失效。
|
|
6972
7116
|
// 与 INSERT 不同,自增列在 UPDATE 里也不开绿灯(MySQL 同样报 1048)。
|
|
@@ -7002,7 +7146,7 @@ class SQLExecutor {
|
|
|
7002
7146
|
const all = (await this.engine.find(statement.table, {}, { limit: 1e9, offset: 0 })).map(r => normalizeRow(r, schema));
|
|
7003
7147
|
const ids = [];
|
|
7004
7148
|
const removedRows = [];
|
|
7005
|
-
let candidates =
|
|
7149
|
+
let candidates = await this._filterMutationRows(statement, all);
|
|
7006
7150
|
// DELETE ... ORDER BY ... LIMIT n
|
|
7007
7151
|
if (statement.orderBy) {
|
|
7008
7152
|
const cmp = (a, b) => {
|
|
@@ -7024,7 +7168,7 @@ class SQLExecutor {
|
|
|
7024
7168
|
// 无主键表没有稳定行标识:_rowPkId 会回退到 row.id(业务列名),
|
|
7025
7169
|
// 而存储层的 _resolveId 把 id 当 1-based 行号 —— 两者语义不一致,
|
|
7026
7170
|
// DELETE ... WHERE id IN (3,5) 会删错行。此时直接传行对象,存储层按引用删。
|
|
7027
|
-
const id = pkCols.length
|
|
7171
|
+
const id = pkCols.length === 1 ? this._rowPkId(row, pkCols) : row;
|
|
7028
7172
|
if (id !== undefined) { ids.push(id); removedRows.push(row); }
|
|
7029
7173
|
}
|
|
7030
7174
|
if (ids.length > 0) {
|
|
@@ -7775,6 +7919,26 @@ class SQLExecutor {
|
|
|
7775
7919
|
}
|
|
7776
7920
|
}
|
|
7777
7921
|
|
|
7922
|
+
/**
|
|
7923
|
+
* #182:UPDATE / DELETE 的 WHERE 过滤。
|
|
7924
|
+
* SELECT 路径会先物化 IN/EXISTS 子查询,再对相关子查询逐行求值;
|
|
7925
|
+
* 写路径此前直接用同步 evaluateExpr,子查询列表为空 → 静默 0 行。
|
|
7926
|
+
*/
|
|
7927
|
+
async _filterMutationRows(statement, rows) {
|
|
7928
|
+
if (!statement.where) return rows;
|
|
7929
|
+
await this._materialize(statement.where);
|
|
7930
|
+
const aliases = new Set([String(statement.table || '').toLowerCase()]);
|
|
7931
|
+
const subs = this._collectSubqueries(statement.where).filter(n => this._isCorrelated(n, aliases));
|
|
7932
|
+
if (subs.length === 0) return rows.filter(row => evaluateExpr(statement.where, row, this.ctx));
|
|
7933
|
+
const kept = [];
|
|
7934
|
+
for (const row of rows) {
|
|
7935
|
+
const exprRow = this._prefixRow(row, statement.table);
|
|
7936
|
+
for (const node of subs) await this._evalCorrelated(node, exprRow);
|
|
7937
|
+
if (evaluateExpr(statement.where, exprRow, this.ctx)) kept.push(row);
|
|
7938
|
+
}
|
|
7939
|
+
return kept;
|
|
7940
|
+
}
|
|
7941
|
+
|
|
7778
7942
|
// 物化 FROM 子查询(把子查询替换为行数组),返回 { rows, alias }
|
|
7779
7943
|
async _materializeFrom(item) {
|
|
7780
7944
|
if (item.subquery) {
|
|
@@ -9513,7 +9677,8 @@ class SQLExecutor {
|
|
|
9513
9677
|
// 返回的仍是分组出现顺序)。这里补上排序,规则与非分组路径一致。
|
|
9514
9678
|
let outRows = mapped;
|
|
9515
9679
|
if (statement.orderBy && mapped.length > 1) {
|
|
9516
|
-
const ordVal = (
|
|
9680
|
+
const ordVal = (entry, o) => {
|
|
9681
|
+
const row = entry.row, src = entry.src;
|
|
9517
9682
|
// row 是投影后的 [v1, v2, ...],按列名下标取
|
|
9518
9683
|
const name = typeof o.column === 'string' ? o.column
|
|
9519
9684
|
: (o.column && o.column.type === 'column' ? o.column.name : null);
|
|
@@ -9523,13 +9688,25 @@ class SQLExecutor {
|
|
|
9523
9688
|
if (name === null && pos !== null && pos >= 1 && pos <= cols.length) {
|
|
9524
9689
|
return row[pos - 1];
|
|
9525
9690
|
}
|
|
9526
|
-
if (name
|
|
9527
|
-
|
|
9528
|
-
|
|
9691
|
+
if (name !== null) {
|
|
9692
|
+
// #183:GROUP BY 路径的投影列名不带限定符,ORDER BY t1.b 要按 b 命中
|
|
9693
|
+
const bare = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1) : name;
|
|
9694
|
+
const idx = cols.indexOf(name) !== -1 ? cols.indexOf(name) : cols.indexOf(bare);
|
|
9695
|
+
if (idx !== -1) return row[idx];
|
|
9696
|
+
}
|
|
9697
|
+
// #163:ORDER BY <聚合表达式> / <表达式> 必须按分组求值并遵守 dir,
|
|
9698
|
+
// 此前直接返回 null,DESC/ASC 都无法影响顺序。
|
|
9699
|
+
if (o.column && typeof o.column === 'object') {
|
|
9700
|
+
const group = (src && src._group) || [src];
|
|
9701
|
+
const copy = JSON.parse(JSON.stringify(o.column));
|
|
9702
|
+
this._replaceAggregates(copy, group);
|
|
9703
|
+
return resolveOperand(copy, src, this.ctx);
|
|
9704
|
+
}
|
|
9705
|
+
return null;
|
|
9529
9706
|
};
|
|
9530
9707
|
const cmp = (a, b) => {
|
|
9531
9708
|
for (const o of statement.orderBy) {
|
|
9532
|
-
const r = compareSqlValues(ordVal(a
|
|
9709
|
+
const r = compareSqlValues(ordVal(a, o), ordVal(b, o), o.dir);
|
|
9533
9710
|
if (r !== 0) return r;
|
|
9534
9711
|
}
|
|
9535
9712
|
return 0;
|
|
@@ -10132,7 +10309,23 @@ async function inferColumnTypes(engine, stmt, r) {
|
|
|
10132
10309
|
? stmt.from.tables[0].table : null;
|
|
10133
10310
|
if (t && engine && typeof engine.getTableSchema === 'function') schema = await engine.getTableSchema(t);
|
|
10134
10311
|
} catch (e) { schema = null; }
|
|
10312
|
+
const defs = (stmt && Array.isArray(stmt.columns)) ? stmt.columns : [];
|
|
10313
|
+
const aggType = (fn) => String(fn).toUpperCase() === 'COUNT' ? 'INT' : 'FLOAT';
|
|
10135
10314
|
return r.columns.map((name) => {
|
|
10315
|
+
// #240:先按输出列找到对应表达式;聚合列按聚合函数类型,不能拿别名回查表列
|
|
10316
|
+
const c = defs.find((d) => scalarColumnName(d) === name);
|
|
10317
|
+
if (c) {
|
|
10318
|
+
if (c.aggregate) return aggType(c.aggregate);
|
|
10319
|
+
if (c.scalar && containsAggregateNode(c.scalar)) return 'FLOAT';
|
|
10320
|
+
if (c.scalar && c.scalar.type === 'column' && schema && schema[c.scalar.name]) {
|
|
10321
|
+
return sqlTypeName(schema[c.scalar.name].type).toUpperCase();
|
|
10322
|
+
}
|
|
10323
|
+
if (typeof c.expr === 'string' && c.expr !== '*' && (!c.alias || c.alias === c.expr)) {
|
|
10324
|
+
const def = schema && schema[c.expr];
|
|
10325
|
+
if (def && def.type) return sqlTypeName(def.type).toUpperCase();
|
|
10326
|
+
}
|
|
10327
|
+
return null;
|
|
10328
|
+
}
|
|
10136
10329
|
const def = schema && schema[name];
|
|
10137
10330
|
return def && def.type ? sqlTypeName(def.type).toUpperCase() : null;
|
|
10138
10331
|
});
|
package/lib/sqlite_compat.js
CHANGED
|
@@ -25,6 +25,12 @@ class SqliteError extends Error {
|
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
+
// #196:readonly 连接必须拒绝写语句
|
|
29
|
+
function isWriteSql(sql) {
|
|
30
|
+
const s = String(sql || '').replace(/^\s*(?:--[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*/, '').trim();
|
|
31
|
+
return /^(CREATE|DROP|ALTER|INSERT|UPDATE|DELETE|REPLACE|TRUNCATE|VACUUM|REINDEX|ATTACH|DETACH)\b/i.test(s);
|
|
32
|
+
}
|
|
33
|
+
|
|
28
34
|
class Database {
|
|
29
35
|
constructor(filename = ':memory:', options = {}) {
|
|
30
36
|
if (filename !== null && filename !== undefined && typeof filename !== 'string') {
|
|
@@ -96,6 +102,9 @@ class Database {
|
|
|
96
102
|
|
|
97
103
|
exec(sql) {
|
|
98
104
|
if (typeof sql !== 'string') throw new TypeError('The "sql" argument must be a string');
|
|
105
|
+
if (this.readonly && isWriteSql(sql)) {
|
|
106
|
+
throw new SqliteError('attempt to write a readonly database', 'SQLITE_READONLY');
|
|
107
|
+
}
|
|
99
108
|
this._sync('exec', [sql, null]);
|
|
100
109
|
return this;
|
|
101
110
|
}
|
|
@@ -277,10 +286,18 @@ class Statement {
|
|
|
277
286
|
if (p === undefined || p === null) p = this._params;
|
|
278
287
|
if (Array.isArray(p) && p.length === 1 && typeof p[0] === 'object' && p[0] !== null && !Array.isArray(p[0]) && !(p[0] instanceof Date) && !Buffer.isBuffer(p[0])) {
|
|
279
288
|
const hasNamed = /[@:$][A-Za-z_][A-Za-z0-9_]*/.test(this.source);
|
|
289
|
+
// #195:匿名 ? 不接受对象实参(对象只用于命名占位符),否则会静默绑 NULL
|
|
290
|
+
if (!hasNamed && /\?/.test(this.source)) {
|
|
291
|
+
throw new SqliteError('Too many parameter values were provided', 'SQLITE_RANGE');
|
|
292
|
+
}
|
|
280
293
|
p = hasNamed ? p[0] : p;
|
|
281
294
|
} else if (!Array.isArray(p) && (typeof p !== 'object' || p === null)) {
|
|
282
295
|
p = [p];
|
|
283
296
|
}
|
|
297
|
+
// #196:readonly 连接上的写语句在绑定阶段直接拒绝
|
|
298
|
+
if (mode === 'run' && this.database.readonly && isWriteSql(this.source)) {
|
|
299
|
+
throw new SqliteError('attempt to write a readonly database', 'SQLITE_READONLY');
|
|
300
|
+
}
|
|
284
301
|
return this.database._sync(mode, [this.source, p]);
|
|
285
302
|
}
|
|
286
303
|
|