jsql-neo 6.8.13 → 6.8.15
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/database.js +215 -36
- package/lib/jsql_format.js +84 -24
- package/lib/sql.js +97 -21
- package/lib/sqlite_worker.js +9 -2
- package/lib/table.js +16 -0
- package/package.json +3 -3
- package/test/issue-248-252.test.js +152 -0
- package/test/issue-259-264.test.js +163 -0
package/lib/jsql_format.js
CHANGED
|
@@ -11,6 +11,45 @@ const SZ = {
|
|
|
11
11
|
DATA: 4096 - 64
|
|
12
12
|
};
|
|
13
13
|
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
// 静态加密(Issue #260)
|
|
16
|
+
//
|
|
17
|
+
// 目录模式(hybrid/disk)的 `.jsql` 数据块此前只做 gzip,明文可直接解压看到。
|
|
18
|
+
// `encryptKey` 只在 legacy 单文件模式生效,目录模式静默忽略密钥 —— 用户以为
|
|
19
|
+
// 落盘已加密,实际裸奔。
|
|
20
|
+
//
|
|
21
|
+
// 现在把目录模式的数据块也加密:
|
|
22
|
+
// 写:原始行字节 → gzip → AES-256-CBC 加密 → 落盘
|
|
23
|
+
// 读:落盘字节 → AES-256-CBC 解密 → gunzip
|
|
24
|
+
//
|
|
25
|
+
// 布局:块头 [49] = 加密标记(0 未加密 / 1 已加密);
|
|
26
|
+
// 密文区 = IV(16 字节) + 密文本体。
|
|
27
|
+
// IV 每次随机生成,随密文一起落盘。
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
|
|
30
|
+
/** 由用户密钥派生 32 字节 AES-256 密钥(scrypt,固定 salt 以便同一密钥可重复解密)。 */
|
|
31
|
+
function deriveAesKey(encryptKey) {
|
|
32
|
+
const raw = Buffer.from(String(encryptKey), 'utf8');
|
|
33
|
+
return crypto.scryptSync(raw, Buffer.from('jsql-neo-static-encryption-v1', 'utf8'), 32);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 加密一段数据,返回 IV(16) + 密文。 */
|
|
37
|
+
function encryptBlock(data, key) {
|
|
38
|
+
const iv = crypto.randomBytes(16);
|
|
39
|
+
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
|
|
40
|
+
const enc = Buffer.concat([cipher.update(data), cipher.final()]);
|
|
41
|
+
return Buffer.concat([iv, enc]);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 解密 IV(16) + 密文。 */
|
|
45
|
+
function decryptBlock(payload, key) {
|
|
46
|
+
if (payload.length < 16) throw new Error('encrypted block too short');
|
|
47
|
+
const iv = payload.subarray(0, 16);
|
|
48
|
+
const body = payload.subarray(16);
|
|
49
|
+
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
|
|
50
|
+
return Buffer.concat([decipher.update(body), decipher.final()]);
|
|
51
|
+
}
|
|
52
|
+
|
|
14
53
|
const BT = { FREE: 0, DATA: 1, IDX: 2 };
|
|
15
54
|
|
|
16
55
|
const TYPE = { NUL:0, BOL:1, I32:2, F64:3, STR:4, BUF:5, ARR:6, OBJ:7, I64:8, DATE:9, OID:10 };
|
|
@@ -177,7 +216,7 @@ function verifyHash(buf) {
|
|
|
177
216
|
}
|
|
178
217
|
|
|
179
218
|
class JSQLFormat {
|
|
180
|
-
constructor(path) {
|
|
219
|
+
constructor(path, encryptKey) {
|
|
181
220
|
this.path = path;
|
|
182
221
|
this.fd = null;
|
|
183
222
|
this.tables = new Map();
|
|
@@ -186,6 +225,37 @@ class JSQLFormat {
|
|
|
186
225
|
this.dirty = false;
|
|
187
226
|
this.open = false;
|
|
188
227
|
this._nextTableId = 1;
|
|
228
|
+
// #260:目录模式的静态加密密钥(未提供则为 null,即不加密)
|
|
229
|
+
this._encryptKey = encryptKey ? deriveAesKey(encryptKey) : null;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** 块头 [49] 加密标记 */
|
|
233
|
+
static get ENC_FLAG_OFF() { return 49; }
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* 把块内载荷编码成落盘字节:gzip → (可选)加密。
|
|
237
|
+
* 返回 { payload, compLen, encFlag }
|
|
238
|
+
*/
|
|
239
|
+
_encodeBlockPayload(raw) {
|
|
240
|
+
const comp = zlib.gzipSync(raw, { level: 1 });
|
|
241
|
+
if (!this._encryptKey) {
|
|
242
|
+
return { payload: comp, compLen: comp.length, encFlag: 0 };
|
|
243
|
+
}
|
|
244
|
+
const payload = encryptBlock(comp, this._encryptKey);
|
|
245
|
+
return { payload, compLen: payload.length, encFlag: 1 };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* 解析块内载荷: (可选)解密 → gunzip。
|
|
250
|
+
*/
|
|
251
|
+
_decodeBlockPayload(buf) {
|
|
252
|
+
const compFlag = buf[48];
|
|
253
|
+
const encFlag = buf[JSQLFormat.ENC_FLAG_OFF];
|
|
254
|
+
const dataLen = compFlag ? buf.readUInt32LE(44) : buf.readUInt32LE(40);
|
|
255
|
+
let payload = buf.slice(SZ.HEADER, SZ.HEADER + dataLen);
|
|
256
|
+
if (encFlag) payload = decryptBlock(payload, this._encryptKey);
|
|
257
|
+
if (!compFlag) return payload;
|
|
258
|
+
return zlib.gunzipSync(payload);
|
|
189
259
|
}
|
|
190
260
|
|
|
191
261
|
_open() {
|
|
@@ -426,13 +496,15 @@ class JSQLFormat {
|
|
|
426
496
|
// Compress and write blocks
|
|
427
497
|
for (let i = 0; i < p.rawBlocks.length; i++) {
|
|
428
498
|
const bid = p.blockIds[i];
|
|
429
|
-
|
|
499
|
+
// #260:gzip 后加密(目录模式静态加密)
|
|
500
|
+
const { payload, compLen, encFlag } = this._encodeBlockPayload(p.rawBlocks[i]);
|
|
430
501
|
const block = Buffer.alloc(SZ.BLOCK);
|
|
431
502
|
mkHeader(BT.DATA, bid, p.tableId).copy(block);
|
|
432
503
|
block.writeUInt32LE(p.rawBlocks[i].length, 40);
|
|
433
504
|
block[48] = 1;
|
|
434
|
-
block.
|
|
435
|
-
|
|
505
|
+
block[JSQLFormat.ENC_FLAG_OFF] = encFlag;
|
|
506
|
+
block.writeUInt32LE(compLen, 44);
|
|
507
|
+
payload.copy(block, SZ.HEADER);
|
|
436
508
|
finalize(block);
|
|
437
509
|
fs.writeSync(this.fd, block, 0, SZ.BLOCK, bid * SZ.BLOCK);
|
|
438
510
|
}
|
|
@@ -519,11 +591,13 @@ class JSQLFormat {
|
|
|
519
591
|
const bid = this._alloc();
|
|
520
592
|
const buf = Buffer.alloc(SZ.BLOCK);
|
|
521
593
|
mkHeader(BT.DATA, bid, t.tableId).copy(buf);
|
|
522
|
-
|
|
594
|
+
// #260:gzip 后加密(目录模式静态加密)
|
|
595
|
+
const { payload, compLen, encFlag } = this._encodeBlockPayload(Buffer.from(scratch.subarray(0, end)));
|
|
523
596
|
buf.writeUInt32LE(end, 40);
|
|
524
597
|
buf[48] = 1;
|
|
525
|
-
buf.
|
|
526
|
-
|
|
598
|
+
buf[JSQLFormat.ENC_FLAG_OFF] = encFlag;
|
|
599
|
+
buf.writeUInt32LE(compLen, 44);
|
|
600
|
+
payload.copy(buf, SZ.HEADER);
|
|
527
601
|
finalize(buf);
|
|
528
602
|
fs.writeSync(this.fd, buf, 0, SZ.BLOCK, bid * SZ.BLOCK);
|
|
529
603
|
t.dataBlock = bid;
|
|
@@ -569,10 +643,7 @@ class JSQLFormat {
|
|
|
569
643
|
if (!verifyHash(buf)) {
|
|
570
644
|
throw new Error(`[JSQLFormat] Table '${name}': data block ${bid} failed integrity check`);
|
|
571
645
|
}
|
|
572
|
-
const
|
|
573
|
-
const raw = compFlag
|
|
574
|
-
? zlib.gunzipSync(buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(44)))
|
|
575
|
-
: buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(40));
|
|
646
|
+
const raw = this._decodeBlockPayload(buf);
|
|
576
647
|
|
|
577
648
|
let off = 0;
|
|
578
649
|
while (off + 4 <= raw.length) {
|
|
@@ -625,10 +696,7 @@ class JSQLFormat {
|
|
|
625
696
|
throw new Error(`[JSQLFormat] Table '${name}': data block ${bid} failed integrity check`);
|
|
626
697
|
}
|
|
627
698
|
|
|
628
|
-
const
|
|
629
|
-
const raw = compFlag
|
|
630
|
-
? zlib.gunzipSync(buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(44)))
|
|
631
|
-
: buf.slice(SZ.HEADER, SZ.HEADER + buf.readUInt32LE(40));
|
|
699
|
+
const raw = this._decodeBlockPayload(buf);
|
|
632
700
|
|
|
633
701
|
let off = 0;
|
|
634
702
|
while (off + 4 <= raw.length) {
|
|
@@ -689,15 +757,7 @@ class JSQLFormat {
|
|
|
689
757
|
_readInBlock(blockId, off) {
|
|
690
758
|
const buf = Buffer.alloc(SZ.BLOCK);
|
|
691
759
|
fs.readSync(this.fd, buf, 0, SZ.BLOCK, blockId * SZ.BLOCK);
|
|
692
|
-
const
|
|
693
|
-
const compSz = buf.readUInt32LE(44);
|
|
694
|
-
const dataSz = buf.readUInt32LE(40);
|
|
695
|
-
let raw;
|
|
696
|
-
if (compFlag) {
|
|
697
|
-
raw = zlib.gunzipSync(buf.slice(SZ.HEADER, SZ.HEADER + compSz));
|
|
698
|
-
} else {
|
|
699
|
-
raw = buf.slice(SZ.HEADER, SZ.HEADER + dataSz);
|
|
700
|
-
}
|
|
760
|
+
const raw = this._decodeBlockPayload(buf);
|
|
701
761
|
const r = decRow(raw, off);
|
|
702
762
|
return r.row;
|
|
703
763
|
}
|
package/lib/sql.js
CHANGED
|
@@ -2016,7 +2016,15 @@ class Parser {
|
|
|
2016
2016
|
while (true) {
|
|
2017
2017
|
const col = this.parseColumnRef();
|
|
2018
2018
|
this.expect('op', '=');
|
|
2019
|
-
|
|
2019
|
+
// #249:SET col = DEFAULT —— 解析层此前把 DEFAULT 当成列名
|
|
2020
|
+
// ({ type:'column', name:'DEFAULT' }),执行时找不到该列 → 写 NULL。
|
|
2021
|
+
// 这里显式识别关键字,产出 { _default: true } 标记。
|
|
2022
|
+
if (this.peek().type === 'keyword' && this.peek().value === 'DEFAULT') {
|
|
2023
|
+
this.next();
|
|
2024
|
+
assignments.push([col, { _default: true }]);
|
|
2025
|
+
} else {
|
|
2026
|
+
assignments.push([col, this.parseScalar()]);
|
|
2027
|
+
}
|
|
2020
2028
|
if (this.peek().type === 'op' && this.peek().value === ',') { this.next(); continue; }
|
|
2021
2029
|
break;
|
|
2022
2030
|
}
|
|
@@ -3826,6 +3834,27 @@ function sqlNumericCoerce(v) {
|
|
|
3826
3834
|
* · 布尔 → 0/1
|
|
3827
3835
|
* · 其余原样
|
|
3828
3836
|
*/
|
|
3837
|
+
/**
|
|
3838
|
+
* 列的隐式默认值(Issue #252)。
|
|
3839
|
+
*
|
|
3840
|
+
* MySQL 8.0 执行 `ALTER TABLE t ADD COLUMN x INT NOT NULL`(非空表、无 DEFAULT)
|
|
3841
|
+
* 时,给存量行填该类型的隐式默认值:数值 → 0,字符串 → '',
|
|
3842
|
+
* 日期 → '0000-00-00'(此处用 '0000-01-01' 作为可存储的近似)。
|
|
3843
|
+
*/
|
|
3844
|
+
function implicitDefaultForType(type) {
|
|
3845
|
+
const t = String(type || '').toLowerCase();
|
|
3846
|
+
if (t === 'integer' || t === 'int' || t === 'bigint' || t === 'smallint'
|
|
3847
|
+
|| t === 'tinyint' || t === 'mediumint' || t === 'number' || t === 'float'
|
|
3848
|
+
|| t === 'double' || t === 'real' || t === 'decimal' || t === 'numeric') {
|
|
3849
|
+
return 0;
|
|
3850
|
+
}
|
|
3851
|
+
if (t === 'boolean' || t === 'bool') return false;
|
|
3852
|
+
if (t === 'date') return '0000-01-01';
|
|
3853
|
+
if (t === 'datetime' || t === 'timestamp') return '0000-01-01 00:00:00';
|
|
3854
|
+
if (t === 'time') return '00:00:00';
|
|
3855
|
+
return '';
|
|
3856
|
+
}
|
|
3857
|
+
|
|
3829
3858
|
function sqlGroupKeyNormalize(v) {
|
|
3830
3859
|
if (v === null || v === undefined) return v;
|
|
3831
3860
|
if (typeof v === 'boolean') return v ? 1 : 0;
|
|
@@ -6583,9 +6612,21 @@ class SQLExecutor {
|
|
|
6583
6612
|
table._schema[op.column] = op.def;
|
|
6584
6613
|
}
|
|
6585
6614
|
const dv = op.def && op.def.default;
|
|
6615
|
+
// #252:NOT NULL 且无 DEFAULT 时,存量行必须填该类型的隐式默认值,
|
|
6616
|
+
// 绝不能写 NULL —— 否则表刚建成就违反自身的 NOT NULL 约束
|
|
6617
|
+
// (新行插入会报 1048,旧行却是 NULL,两种状态并存)。
|
|
6618
|
+
// MySQL 8.0 的 ALTER TABLE ... ADD COLUMN x INT NOT NULL 就是填 0。
|
|
6619
|
+
const required = !!(op.def && op.def.required);
|
|
6620
|
+
const implicit = implicitDefaultForType(op.def && op.def.type);
|
|
6586
6621
|
for (const row of table._rows) {
|
|
6587
6622
|
if (!(op.column in row)) {
|
|
6588
|
-
|
|
6623
|
+
if (dv !== undefined) {
|
|
6624
|
+
row[op.column] = typeof dv === 'function' ? dv() : dv;
|
|
6625
|
+
} else if (required) {
|
|
6626
|
+
row[op.column] = implicit;
|
|
6627
|
+
} else {
|
|
6628
|
+
row[op.column] = null;
|
|
6629
|
+
}
|
|
6589
6630
|
}
|
|
6590
6631
|
}
|
|
6591
6632
|
break;
|
|
@@ -6893,18 +6934,24 @@ class SQLExecutor {
|
|
|
6893
6934
|
});
|
|
6894
6935
|
const conflicts = [];
|
|
6895
6936
|
const fresh = [];
|
|
6937
|
+
// #248:同一批次内同键多行时,每行都必须看到**前一行刚写入的新值**。
|
|
6938
|
+
// 此前 all 是语句开始前的一次性快照:第二行读到的仍是旧值,
|
|
6939
|
+
// 于是 n = n + VALUES(n) 的累加被折叠成一次(1+3=4,正确是 6)。
|
|
6940
|
+
// 这里维护一个可变的「当前行」映射,每行更新后写回。
|
|
6941
|
+
const liveRows = new Map();
|
|
6942
|
+
for (const row of all) liveRows.set(keyOf(row), row);
|
|
6896
6943
|
for (const d of dataRows) {
|
|
6897
|
-
|
|
6898
|
-
|
|
6899
|
-
|
|
6900
|
-
|
|
6901
|
-
|
|
6902
|
-
|
|
6903
|
-
|
|
6944
|
+
let existingId = null;
|
|
6945
|
+
if (hasExplicitPk(d) && pkMap.has(keyOf(d))) existingId = pkMap.get(keyOf(d));
|
|
6946
|
+
if (!existingId) {
|
|
6947
|
+
for (const { pick, key, m } of extraMaps) {
|
|
6948
|
+
if (!pick(d)) continue;
|
|
6949
|
+
const k = key(d);
|
|
6950
|
+
if (m.has(k)) { existingId = m.get(k); break; }
|
|
6951
|
+
}
|
|
6904
6952
|
}
|
|
6905
|
-
|
|
6906
|
-
|
|
6907
|
-
else fresh.push(d);
|
|
6953
|
+
if (existingId) conflicts.push({ d, existingId });
|
|
6954
|
+
else fresh.push(d);
|
|
6908
6955
|
}
|
|
6909
6956
|
const conflictAction = this._conflictAction(statement);
|
|
6910
6957
|
const conflictSets = this._conflictSets(statement);
|
|
@@ -6932,10 +6979,17 @@ class SQLExecutor {
|
|
|
6932
6979
|
const data = {};
|
|
6933
6980
|
// 查找冲突行的「旧版本」—— 用于 ON DUPLICATE KEY UPDATE 表达式
|
|
6934
6981
|
// 如 cnt = cnt + 1,需要用旧行的 cnt 值(0),不是新行的 cnt(10)
|
|
6935
|
-
|
|
6936
|
-
|
|
6937
|
-
|
|
6938
|
-
|
|
6982
|
+
// #248:从 liveRows 取「当前值」(含本批次前序行已写入的新值),
|
|
6983
|
+
// 而不是语句开始前的快照。
|
|
6984
|
+
const liveKey = pkCols.map((c, i) => (
|
|
6985
|
+
existingId[i] !== undefined && existingId[i] !== null ? String(existingId[i]) : ''
|
|
6986
|
+
)).join('|');
|
|
6987
|
+
const existingRow = liveRows.has(liveKey)
|
|
6988
|
+
? liveRows.get(liveKey)
|
|
6989
|
+
: all.find(r => {
|
|
6990
|
+
const keys = pkCols.map(c => r[c]).filter(v => v !== undefined && v !== null);
|
|
6991
|
+
return keys.length === pkCols.length && keys.every((v, i) => String(v) === String(existingId[i]));
|
|
6992
|
+
});
|
|
6939
6993
|
if (conflictSets) {
|
|
6940
6994
|
for (const [col, val] of conflictSets) {
|
|
6941
6995
|
// VALUES(col) 引用本次本应插入的值;EXCLUDED.col 为 PG 同义写法
|
|
@@ -6967,11 +7021,18 @@ class SQLExecutor {
|
|
|
6967
7021
|
for (const k of Object.keys(d)) if (!pkCols.includes(k)) data[k] = d[k];
|
|
6968
7022
|
}
|
|
6969
7023
|
if (this.engine.updateById && existingId.length === 1) {
|
|
6970
|
-
|
|
7024
|
+
await this.engine.updateById(statement.name, existingId[0], data);
|
|
6971
7025
|
} else if (this.engine.update) {
|
|
6972
|
-
|
|
6973
|
-
|
|
6974
|
-
|
|
7026
|
+
const filter = {};
|
|
7027
|
+
pkCols.forEach((c, i) => { filter[c] = existingId[i]; });
|
|
7028
|
+
await this.engine.update(statement.name, filter, data);
|
|
7029
|
+
}
|
|
7030
|
+
// #248:把本行的写入结果并回 liveRows,
|
|
7031
|
+
// 让批次内后续同键行看到更新后的当前值(累加才能正确叠加)。
|
|
7032
|
+
if (existingRow && liveRows.has(liveKey)) {
|
|
7033
|
+
Object.assign(existingRow, data);
|
|
7034
|
+
} else if (existingRow) {
|
|
7035
|
+
liveRows.set(liveKey, Object.assign(existingRow || {}, data));
|
|
6975
7036
|
}
|
|
6976
7037
|
updated++;
|
|
6977
7038
|
}
|
|
@@ -7278,7 +7339,22 @@ class SQLExecutor {
|
|
|
7278
7339
|
const exprRow = this._prefixRow(row, statement.table);
|
|
7279
7340
|
const data = {};
|
|
7280
7341
|
for (const [col, val] of statement.assignments) {
|
|
7281
|
-
if (val && typeof val === 'object' && val.
|
|
7342
|
+
if (val && typeof val === 'object' && val._default) {
|
|
7343
|
+
// #249:SET col = DEFAULT —— 取该列的默认值。
|
|
7344
|
+
// 此前解析层产出 { _default: true },但执行层没有分支处理,
|
|
7345
|
+
// 直接把这个对象写进了列(落库成 NULL / 被类型校验拒掉)。
|
|
7346
|
+
// MySQL 8.0 支持这个写法:UPDATE t SET n = DEFAULT 把 n 重置为默认值。
|
|
7347
|
+
const colDef = schema && schema[col];
|
|
7348
|
+
const dv = colDef && colDef.default;
|
|
7349
|
+
let dvValue;
|
|
7350
|
+
if (dv !== undefined) {
|
|
7351
|
+
dvValue = typeof dv === 'function' ? dv() : dv;
|
|
7352
|
+
} else {
|
|
7353
|
+
// 无显式默认值 → 按列类型的隐式默认值(integer→0、string→'')
|
|
7354
|
+
dvValue = implicitDefaultForType(colDef && colDef.type);
|
|
7355
|
+
}
|
|
7356
|
+
data[col] = dvValue;
|
|
7357
|
+
} else if (val && typeof val === 'object' && val.type) {
|
|
7282
7358
|
// SET col = (SELECT ...) 必须按行真实执行子查询。
|
|
7283
7359
|
// resolveOperand 只读节点上的 _value 缓存,而 UPDATE 路径从不物化 SET 表达式,
|
|
7284
7360
|
// 于是无论子查询返回什么值,写进列里的都是 null(连 MATCHED 行也一样)。
|
package/lib/sqlite_worker.js
CHANGED
|
@@ -106,18 +106,24 @@ function toRows(result) {
|
|
|
106
106
|
|
|
107
107
|
let _lastInsertId = 0;
|
|
108
108
|
|
|
109
|
-
async function executeStatement(sql, params) {
|
|
109
|
+
async function executeStatement(sql, params, extraOpts) {
|
|
110
110
|
if (params && typeof params === 'object' && !Array.isArray(params)) {
|
|
111
111
|
sql = applyParams(sql, params);
|
|
112
112
|
params = null;
|
|
113
113
|
}
|
|
114
114
|
const result = await executeSQL(db, sql, params, {
|
|
115
|
+
// #264:better-sqlite3 的 db.exec() 设计上就是执行一条或多条 SQL
|
|
116
|
+
// (常用于跑建表脚本 / BEGIN;…;COMMIT;)。sqlite 兼容层的 exec 必须
|
|
117
|
+
// 走 allowStacked —— 否则迁移过来的多语句脚本直接被安全策略拦掉。
|
|
118
|
+
// prepare()/run()/get()/all() 等单语句路径保持拦截(allowStacked 为 false)。
|
|
119
|
+
allowStacked: false,
|
|
115
120
|
session: {
|
|
116
121
|
get lastInsertId() { return _lastInsertId; },
|
|
117
122
|
set lastInsertId(v) { _lastInsertId = Number(v); },
|
|
118
123
|
},
|
|
119
124
|
functions: userFunctions,
|
|
120
125
|
aggregates: userAggregates,
|
|
126
|
+
...(extraOpts || {}),
|
|
121
127
|
});
|
|
122
128
|
if (result && result.type === 'insert' && result.insertId !== null && result.insertId !== undefined) {
|
|
123
129
|
_lastInsertId = Number(result.insertId);
|
|
@@ -157,7 +163,8 @@ async function handleOp(op, args) {
|
|
|
157
163
|
break;
|
|
158
164
|
}
|
|
159
165
|
case 'exec': {
|
|
160
|
-
|
|
166
|
+
// #264:exec 固定允许堆叠多语句(better-sqlite3 语义)
|
|
167
|
+
result = await executeStatement(args[0], args[1], { allowStacked: true });
|
|
161
168
|
break;
|
|
162
169
|
}
|
|
163
170
|
case 'run': {
|
package/lib/table.js
CHANGED
|
@@ -449,6 +449,8 @@ class Table {
|
|
|
449
449
|
* 注册一个列的 CHECK 约束(Issue #70)。
|
|
450
450
|
* 支持三种来源:
|
|
451
451
|
* • def.check —— 已编译的判定函数(CREATE TABLE 解析时生成)
|
|
452
|
+
* 也接受**字符串表达式**(Issue #251,如 'a > 0'),
|
|
453
|
+
* 与 index.d.ts 声明的 `check?: string` 一致;
|
|
452
454
|
* • def.checks[] —— 表级 CHECK,元素形如 { sql, fn }
|
|
453
455
|
* • def.checkSql —— JSON 持久化后只剩文本,惰性重新编译
|
|
454
456
|
* 判定函数统一签名为 (值, 整行) => boolean,跨列条件也能拿到整行。
|
|
@@ -457,6 +459,20 @@ class Table {
|
|
|
457
459
|
if (!def) return;
|
|
458
460
|
if (typeof def.check === 'function') {
|
|
459
461
|
this._checkConstraints.push({ field, fn: def.check });
|
|
462
|
+
} else if (typeof def.check === 'string' && def.check.trim()) {
|
|
463
|
+
// #251:JS 建表 API 传字符串 CHECK 表达式(index.d.ts:28 声明为 string)
|
|
464
|
+
// 此前只认 function,字符串落入两个分支之间被静默丢弃 ——
|
|
465
|
+
// getTableSchema() 还把 'a > 0' 显示出来,让人以为约束在保护数据。
|
|
466
|
+
const fn = compileCheckSql(def.check);
|
|
467
|
+
if (fn) {
|
|
468
|
+
this._checkConstraints.push({ field, fn });
|
|
469
|
+
// 同时记录 SQL 文本,保证 JSON 快照重载后能重新编译
|
|
470
|
+
if (!def.checkSql) def.checkSql = def.check;
|
|
471
|
+
} else {
|
|
472
|
+
// 无法编译的表达式必须显式报错,不能静默忽略
|
|
473
|
+
throw createError('ER_CHECK_CONSTRAINT', `${this._name}.${field}`,
|
|
474
|
+
`cannot compile CHECK expression: ${def.check}`);
|
|
475
|
+
}
|
|
460
476
|
} else if (typeof def.checkSql === 'string' && def.checkSql) {
|
|
461
477
|
const fn = compileCheckSql(def.checkSql);
|
|
462
478
|
if (fn) this._checkConstraints.push({ field, fn });
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jsql-neo",
|
|
3
|
-
"version": "6.8.
|
|
3
|
+
"version": "6.8.15",
|
|
4
4
|
"description": "JSQL-NEO — Rust-powered embedded database with WASM, REST API, B-Tree indexes, WAL, crash recovery",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
@@ -52,12 +52,12 @@
|
|
|
52
52
|
"build:native": "node scripts/build-native.js",
|
|
53
53
|
"check:release": "node scripts/check-release-metadata.js",
|
|
54
54
|
"release:prep": "node scripts/release.js",
|
|
55
|
-
"test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js && node test/issue-301-305.test.js",
|
|
55
|
+
"test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js && node test/issue-301-305.test.js && node test/issue-248-252.test.js && node test/issue-259-264.test.js",
|
|
56
56
|
"test:parser": "node test/sql-parser.test.js",
|
|
57
57
|
"test:btree": "node test/btree.test.js",
|
|
58
58
|
"test:native": "node test/native.test.js",
|
|
59
59
|
"test:regress": "node test/regress-5.1.0.js",
|
|
60
|
-
"test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js && node test/issue-301-305.test.js",
|
|
60
|
+
"test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js && node test/issue-314-321.test.js && node test/issue-312-320.test.js && node test/issue-243-289.test.js && node test/issue-284-292.test.js && node test/issue-301-305.test.js && node test/issue-248-252.test.js && node test/issue-259-264.test.js",
|
|
61
61
|
"test:coverage": "c8 --all --include='lib/**' --exclude='lib/web_ui.js' --reporter=text --reporter=lcov node test/coverage.js",
|
|
62
62
|
"test:orms": "node examples/orms/run-all.js",
|
|
63
63
|
"test:dml": "node test/dml-constraints.test.js",
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/* ---- 回归:#248 / #249 / #250 / #251 / #252 ---- */
|
|
2
|
+
/*
|
|
3
|
+
* #248 批量 INSERT ... ON DUPLICATE KEY UPDATE 同一键多行时,每行都按
|
|
4
|
+
* 「语句执行前的旧值」求值,累加结果错误。
|
|
5
|
+
* #249 UPDATE t SET col = DEFAULT 被当成列引用求值,实际写入 NULL。
|
|
6
|
+
* #250 db.updateById() 绕过 NOT NULL 约束,把 NULL 写进 NOT NULL 列。
|
|
7
|
+
* #251 JS 建表 API 的 check: 'a > 0' 字符串约束被静默忽略。
|
|
8
|
+
* #252 ALTER TABLE ADD COLUMN ... NOT NULL(无 DEFAULT)给存量行填 NULL。
|
|
9
|
+
*/
|
|
10
|
+
const path = require('path');
|
|
11
|
+
const ROOT = path.join(__dirname, '..');
|
|
12
|
+
const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
|
|
13
|
+
|
|
14
|
+
let pass = 0, fail = 0;
|
|
15
|
+
function ok(name, cond, got) {
|
|
16
|
+
if (cond) { pass++; console.log('[OK] ' + name); }
|
|
17
|
+
else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
(async () => {
|
|
21
|
+
const db = new Database(':memory:', { autoSave: false });
|
|
22
|
+
const q = async (sql) => (await executeSQL(db, sql, { safety: false })).rows;
|
|
23
|
+
|
|
24
|
+
// ================= #248 ON DUPLICATE 批量累加 =================
|
|
25
|
+
await q('CREATE TABLE up (id INT PRIMARY KEY, n INT)');
|
|
26
|
+
await q('INSERT INTO up VALUES (1,0)');
|
|
27
|
+
await q('INSERT INTO up VALUES (1,1) ON DUPLICATE KEY UPDATE n = n + VALUES(n)');
|
|
28
|
+
ok('单行 upsert:n = 0 + 1 = 1',
|
|
29
|
+
JSON.stringify(await q('SELECT * FROM up')) === '[[1,1]]', await q('SELECT * FROM up'));
|
|
30
|
+
|
|
31
|
+
await q('INSERT INTO up VALUES (1,2),(1,3) ON DUPLICATE KEY UPDATE n = n + VALUES(n)');
|
|
32
|
+
ok('批量 upsert 同键多行按行顺序累加:1 + 2 + 3 = 6',
|
|
33
|
+
JSON.stringify(await q('SELECT * FROM up')) === '[[1,6]]', await q('SELECT * FROM up'));
|
|
34
|
+
|
|
35
|
+
// 三行同键
|
|
36
|
+
await q('CREATE TABLE up3 (id INT PRIMARY KEY, n INT)');
|
|
37
|
+
await q('INSERT INTO up3 VALUES (1,0)');
|
|
38
|
+
await q('INSERT INTO up3 VALUES (1,1),(1,2),(1,3) ON DUPLICATE KEY UPDATE n = n + VALUES(n)');
|
|
39
|
+
ok('三行同键批量 upsert = 6',
|
|
40
|
+
JSON.stringify(await q('SELECT * FROM up3')) === '[[1,6]]', await q('SELECT * FROM up3'));
|
|
41
|
+
|
|
42
|
+
// 不回归:普通多行插入
|
|
43
|
+
await q('CREATE TABLE plain (id INT PRIMARY KEY, n INT)');
|
|
44
|
+
await q('INSERT INTO plain VALUES (1,1),(2,2),(3,3)');
|
|
45
|
+
ok('普通多行 INSERT 不回归',
|
|
46
|
+
JSON.stringify(await q('SELECT * FROM plain')) === '[[1,1],[2,2],[3,3]]', null);
|
|
47
|
+
|
|
48
|
+
// ================= #249 SET col = DEFAULT =================
|
|
49
|
+
await q('CREATE TABLE df (id INT PRIMARY KEY, n INT DEFAULT 7)');
|
|
50
|
+
await q('INSERT INTO df VALUES (1, 1)');
|
|
51
|
+
const r = await executeSQL(db, 'UPDATE df SET n = DEFAULT WHERE id = 1', { safety: false });
|
|
52
|
+
ok('UPDATE SET DEFAULT 影响 1 行', r.affectedRows === 1, r.affectedRows);
|
|
53
|
+
ok('UPDATE SET n = DEFAULT 把 n 重置为列默认值 7',
|
|
54
|
+
JSON.stringify(await q('SELECT * FROM df')) === '[[1,7]]', await q('SELECT * FROM df'));
|
|
55
|
+
|
|
56
|
+
// 无显式默认值 → 按类型的隐式默认值
|
|
57
|
+
await q('CREATE TABLE df2 (id INT PRIMARY KEY, m INT)');
|
|
58
|
+
await q('INSERT INTO df2 VALUES (1, 5)');
|
|
59
|
+
await q('UPDATE df2 SET m = DEFAULT WHERE id = 1');
|
|
60
|
+
ok('无 DEFAULT 时用隐式默认值 0',
|
|
61
|
+
JSON.stringify(await q('SELECT * FROM df2')) === '[[1,0]]', await q('SELECT * FROM df2'));
|
|
62
|
+
|
|
63
|
+
await q('CREATE TABLE df3 (id INT PRIMARY KEY, s VARCHAR(10))');
|
|
64
|
+
await q("INSERT INTO df3 VALUES (1, 'x')");
|
|
65
|
+
await q('UPDATE df3 SET s = DEFAULT WHERE id = 1');
|
|
66
|
+
ok('字符串列的隐式默认值为空串',
|
|
67
|
+
JSON.stringify(await q('SELECT * FROM df3')) === '[[1,""]]', await q('SELECT * FROM df3'));
|
|
68
|
+
|
|
69
|
+
// 不回归:普通 SET
|
|
70
|
+
await q('UPDATE df SET n = 3 WHERE id = 1');
|
|
71
|
+
ok('普通 SET 不回归',
|
|
72
|
+
JSON.stringify(await q('SELECT * FROM df')) === '[[1,3]]', await q('SELECT * FROM df'));
|
|
73
|
+
|
|
74
|
+
// ================= #250 updateById NOT NULL =================
|
|
75
|
+
await q('CREATE TABLE nt (id INT PRIMARY KEY, s VARCHAR(5) NOT NULL)');
|
|
76
|
+
await q("INSERT INTO nt VALUES (1, 'x')");
|
|
77
|
+
let updErr = null;
|
|
78
|
+
try { await db.updateById('nt', 1, { s: null }); } catch (e) { updErr = e; }
|
|
79
|
+
ok('db.updateById 写 NULL 进 NOT NULL 列报错', !!updErr, updErr && updErr.message);
|
|
80
|
+
ok('报错是 Column cannot be null',
|
|
81
|
+
updErr && /cannot be null/i.test(updErr.message), updErr && updErr.message);
|
|
82
|
+
ok('失败后数据未被破坏',
|
|
83
|
+
JSON.stringify(await q('SELECT * FROM nt')) === '[[1,"x"]]', await q('SELECT * FROM nt'));
|
|
84
|
+
|
|
85
|
+
// db.update 同样报错(两条路径口径一致)
|
|
86
|
+
let updErr2 = null;
|
|
87
|
+
try { await db.update('nt', { id: 1 }, { s: null }); } catch (e) { updErr2 = e; }
|
|
88
|
+
ok('db.update 同样报错(两条 API 路径一致)', !!updErr2, updErr2 && updErr2.message);
|
|
89
|
+
|
|
90
|
+
// 合法更新仍成功
|
|
91
|
+
await db.updateById('nt', 1, { s: 'y' });
|
|
92
|
+
ok('合法 updateById 仍成功',
|
|
93
|
+
JSON.stringify(await q('SELECT * FROM nt')) === '[[1,"y"]]', await q('SELECT * FROM nt'));
|
|
94
|
+
|
|
95
|
+
// ================= #251 字符串 CHECK 约束 =================
|
|
96
|
+
await db.createTable('ck', {
|
|
97
|
+
id: { type: 'integer', primaryKey: true },
|
|
98
|
+
a: { type: 'integer', check: 'a > 0' },
|
|
99
|
+
});
|
|
100
|
+
let ckErr = null;
|
|
101
|
+
try { await q('INSERT INTO ck VALUES (1, -5)'); } catch (e) { ckErr = e; }
|
|
102
|
+
ok('SQL INSERT 违反字符串 CHECK 报错', !!ckErr, ckErr && ckErr.message);
|
|
103
|
+
ok('报错是 Check constraint violated',
|
|
104
|
+
ckErr && /Check constraint/i.test(ckErr.message), ckErr && ckErr.message);
|
|
105
|
+
|
|
106
|
+
let ckErr2 = null;
|
|
107
|
+
try { await db.insert('ck', { id: 2, a: -7 }); } catch (e) { ckErr2 = e; }
|
|
108
|
+
ok('API insert 违反字符串 CHECK 同样报错', !!ckErr2, ckErr2 && ckErr2.message);
|
|
109
|
+
|
|
110
|
+
let ckOk = null;
|
|
111
|
+
try { await q('INSERT INTO ck VALUES (3, 5)'); ckOk = true; } catch (e) { ckOk = false; }
|
|
112
|
+
ok('满足 CHECK 的插入成功', ckOk === true, ckOk);
|
|
113
|
+
|
|
114
|
+
// 不回归:函数形态的 CHECK
|
|
115
|
+
await db.createTable('ck2', {
|
|
116
|
+
id: { type: 'integer', primaryKey: true },
|
|
117
|
+
a: { type: 'integer', check: (v) => v > 0 },
|
|
118
|
+
});
|
|
119
|
+
let fnErr = null;
|
|
120
|
+
try { await db.insert('ck2', { id: 1, a: -1 }); } catch (e) { fnErr = e; }
|
|
121
|
+
ok('函数形态 CHECK 不回归', !!fnErr, fnErr && fnErr.message);
|
|
122
|
+
|
|
123
|
+
// ================= #252 ADD COLUMN NOT NULL =================
|
|
124
|
+
await q('CREATE TABLE ac (id INT PRIMARY KEY)');
|
|
125
|
+
await q('INSERT INTO ac VALUES (1),(2)');
|
|
126
|
+
await q('ALTER TABLE ac ADD COLUMN s VARCHAR(5) NOT NULL');
|
|
127
|
+
ok('ADD COLUMN VARCHAR NOT NULL 存量行填空串',
|
|
128
|
+
JSON.stringify(await q('SELECT * FROM ac')) === '[[1,""],[2,""]]', await q('SELECT * FROM ac'));
|
|
129
|
+
await q('ALTER TABLE ac ADD COLUMN n INT NOT NULL');
|
|
130
|
+
ok('ADD COLUMN INT NOT NULL 存量行填 0',
|
|
131
|
+
JSON.stringify(await q('SELECT * FROM ac')) === '[[1,"",0],[2,"",0]]', await q('SELECT * FROM ac'));
|
|
132
|
+
|
|
133
|
+
// 不回归:可空列仍填 NULL
|
|
134
|
+
await q('CREATE TABLE ac2 (id INT PRIMARY KEY)');
|
|
135
|
+
await q('INSERT INTO ac2 VALUES (1)');
|
|
136
|
+
await q('ALTER TABLE ac2 ADD COLUMN x INT');
|
|
137
|
+
ok('可空列仍填 NULL(不回归)',
|
|
138
|
+
JSON.stringify(await q('SELECT * FROM ac2')) === '[[1,null]]', await q('SELECT * FROM ac2'));
|
|
139
|
+
|
|
140
|
+
// 不回归:带 DEFAULT 的列按 DEFAULT 回填
|
|
141
|
+
await q('CREATE TABLE ac3 (id INT PRIMARY KEY)');
|
|
142
|
+
await q('INSERT INTO ac3 VALUES (1)');
|
|
143
|
+
await q('ALTER TABLE ac3 ADD COLUMN d INT DEFAULT 42');
|
|
144
|
+
ok('带 DEFAULT 的列按 DEFAULT 回填',
|
|
145
|
+
JSON.stringify(await q('SELECT * FROM ac3')) === '[[1,42]]', await q('SELECT * FROM ac3'));
|
|
146
|
+
|
|
147
|
+
console.log(`\n${pass} passed, ${fail} failed`);
|
|
148
|
+
process.exit(fail === 0 ? 0 : 1);
|
|
149
|
+
})().catch(e => {
|
|
150
|
+
console.log('[FAIL] unexpected exception: ' + (e.stack || e).split('\n').slice(0, 4).join('\n'));
|
|
151
|
+
process.exit(1);
|
|
152
|
+
});
|