jsql-neo 6.5.31 → 6.6.0
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 +7 -0
- package/lib/date-types.js +113 -55
- package/lib/errors.js +2 -0
- package/lib/sql.js +629 -180
- package/lib/table.js +89 -18
- package/package.json +3 -3
- package/postinstall.js +6 -4
- package/test/issue-50.test.js +35 -22
- package/test/issue-69-70.test.js +152 -0
- package/test/issue-71-72.test.js +137 -0
- package/test/issue-73-76.test.js +254 -0
- package/test/query-opt.test.js +10 -8
- package/test/readme-audit.test.js +8 -8
package/lib/table.js
CHANGED
|
@@ -7,7 +7,35 @@
|
|
|
7
7
|
const Query = require('./query');
|
|
8
8
|
const BTree = require('./btree');
|
|
9
9
|
const { validateDateType, now } = require('./date-types');
|
|
10
|
-
const { createError } = require('./errors');
|
|
10
|
+
const { createError, JSQL_Error } = require('./errors');
|
|
11
|
+
|
|
12
|
+
// ---------------------------------------------------------------------------
|
|
13
|
+
// DEFAULT 表达式求值(Issue #72)
|
|
14
|
+
//
|
|
15
|
+
// 此前只有字符串 'CURRENT_TIMESTAMP' 被特判成 now(),其他函数式默认值
|
|
16
|
+
// ('NOW()'、'NOW(6)'、'LOCALTIMESTAMP' 等)会被原样当成列值塞进数据行,
|
|
17
|
+
// 随后被日期校验当作非法日期,报出误导性的 "Incorrect date value: '<列名>'"。
|
|
18
|
+
// 这里统一按字符串形态识别:
|
|
19
|
+
// • CURRENT_TIMESTAMP / NOW[(n)] / LOCALTIMESTAMP[(n)] / LOCALTIME[(n)]
|
|
20
|
+
// → 当前时间戳(MySQL 语义)
|
|
21
|
+
// • 其他「函数调用形式」的默认值 → 明确报不支持,而不是拿列名当值
|
|
22
|
+
// • 普通字面量('abc'、'0'、'{}' 等)→ 原样返回,保持向后兼容
|
|
23
|
+
// 注意:JS 侧 `default: () => ...` 的函数仍在调用处直接 dv()。
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
const NOW_DEFAULT_RE = /^(?:CURRENT_TIMESTAMP|NOW|LOCALTIMESTAMP|LOCALTIME)\s*(?:\(\s*\d*\s*\))?$/i;
|
|
26
|
+
const FUNC_CALL_DEFAULT_RE = /^[A-Za-z_$][\w$]*\s*\([\s\S]*\)$/;
|
|
27
|
+
|
|
28
|
+
function resolveDefaultValue(dv, fieldName) {
|
|
29
|
+
if (typeof dv === 'function') return dv();
|
|
30
|
+
if (typeof dv !== 'string') return dv;
|
|
31
|
+
const expr = dv.trim();
|
|
32
|
+
if (NOW_DEFAULT_RE.test(expr)) return now();
|
|
33
|
+
if (FUNC_CALL_DEFAULT_RE.test(expr)) {
|
|
34
|
+
throw new JSQL_Error(1235,
|
|
35
|
+
`Unsupported default expression '${expr}' for column '${fieldName}'`);
|
|
36
|
+
}
|
|
37
|
+
return dv;
|
|
38
|
+
}
|
|
11
39
|
|
|
12
40
|
// ---------------------------------------------------------------------------
|
|
13
41
|
// 64 位整数(Issue #38)
|
|
@@ -28,6 +56,16 @@ const INT64_MAX = 9223372036854775807n;
|
|
|
28
56
|
const SAFE_INT_MIN = BigInt(Number.MIN_SAFE_INTEGER);
|
|
29
57
|
const SAFE_INT_MAX = BigInt(Number.MAX_SAFE_INTEGER);
|
|
30
58
|
const DECIMAL_INT_RE = /^[+-]?\d+$/;
|
|
59
|
+
/**
|
|
60
|
+
* 从持久化的 CHECK SQL 文本重新编译判定函数(Issue #70)。
|
|
61
|
+
* 惰性 require 避免 table.js ↔ sql.js 的加载顺序耦合。
|
|
62
|
+
* 编译失败直接抛错:约束无法重建时必须显式失败,不能静默丢弃。
|
|
63
|
+
*/
|
|
64
|
+
function compileCheckSql(sqlText) {
|
|
65
|
+
const { compileCheckExpr } = require('./sql');
|
|
66
|
+
return compileCheckExpr(sqlText);
|
|
67
|
+
}
|
|
68
|
+
|
|
31
69
|
|
|
32
70
|
function integerError(type, v) {
|
|
33
71
|
return createError('ER_TRUNCATED_WRONG_VALUE', type, v);
|
|
@@ -208,9 +246,7 @@ class Table {
|
|
|
208
246
|
if (def.default !== undefined) {
|
|
209
247
|
this._defaults[field] = def.default;
|
|
210
248
|
}
|
|
211
|
-
|
|
212
|
-
this._checkConstraints.push({ field, fn: def.check });
|
|
213
|
-
}
|
|
249
|
+
this._registerChecks(field, def);
|
|
214
250
|
if (def.foreignKey) {
|
|
215
251
|
this._foreignKeys.push({
|
|
216
252
|
field,
|
|
@@ -253,6 +289,46 @@ class Table {
|
|
|
253
289
|
this._cachedComputedFields = this._cachedSchemaFields.filter(f => this._computedFields[f]);
|
|
254
290
|
}
|
|
255
291
|
|
|
292
|
+
/**
|
|
293
|
+
* 注册一个列的 CHECK 约束(Issue #70)。
|
|
294
|
+
* 支持三种来源:
|
|
295
|
+
* • def.check —— 已编译的判定函数(CREATE TABLE 解析时生成)
|
|
296
|
+
* • def.checks[] —— 表级 CHECK,元素形如 { sql, fn }
|
|
297
|
+
* • def.checkSql —— JSON 持久化后只剩文本,惰性重新编译
|
|
298
|
+
* 判定函数统一签名为 (值, 整行) => boolean,跨列条件也能拿到整行。
|
|
299
|
+
*/
|
|
300
|
+
_registerChecks(field, def) {
|
|
301
|
+
if (!def) return;
|
|
302
|
+
if (typeof def.check === 'function') {
|
|
303
|
+
this._checkConstraints.push({ field, fn: def.check });
|
|
304
|
+
} else if (typeof def.checkSql === 'string' && def.checkSql) {
|
|
305
|
+
const fn = compileCheckSql(def.checkSql);
|
|
306
|
+
if (fn) this._checkConstraints.push({ field, fn });
|
|
307
|
+
}
|
|
308
|
+
if (Array.isArray(def.checks)) {
|
|
309
|
+
for (const entry of def.checks) {
|
|
310
|
+
if (!entry) continue;
|
|
311
|
+
let fn = typeof entry === 'function' ? entry : entry.fn;
|
|
312
|
+
if (typeof fn !== 'function' && entry.sql) fn = compileCheckSql(entry.sql);
|
|
313
|
+
if (fn) this._checkConstraints.push({ field, fn });
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** 校验全部 CHECK 约束(整行上下文,列级/表级统一走这里)。 */
|
|
319
|
+
_enforceChecks(data) {
|
|
320
|
+
for (const { field, fn } of this._checkConstraints) {
|
|
321
|
+
if (typeof fn !== 'function') continue;
|
|
322
|
+
let ok;
|
|
323
|
+
try {
|
|
324
|
+
ok = fn(data ? data[field] : undefined, data || {});
|
|
325
|
+
} catch (_) {
|
|
326
|
+
ok = false; // 求值失败视为违反,绝不静默放行
|
|
327
|
+
}
|
|
328
|
+
if (!ok) throw createError('ER_CHECK_CONSTRAINT', this._name + '.' + field);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
256
332
|
_autoCreateBTrees() {
|
|
257
333
|
for (const [field, def] of Object.entries(this._schema)) {
|
|
258
334
|
if (field === '_softDelete') continue;
|
|
@@ -340,7 +416,7 @@ class Table {
|
|
|
340
416
|
// 在副本上做默认值/计算列/类型归一,避免污染调用方传入的原始对象
|
|
341
417
|
let data = { ...items[i] };
|
|
342
418
|
for (const [f, dv] of Object.entries(defaults)) {
|
|
343
|
-
if (data[f] === undefined) data[f] =
|
|
419
|
+
if (data[f] === undefined) data[f] = resolveDefaultValue(dv, f);
|
|
344
420
|
}
|
|
345
421
|
for (const f of Object.keys(computedFields)) data[f] = computedFields[f](data);
|
|
346
422
|
// 与单条 insert 保持一致:归一时间/数值/布尔/字符串类型(此前 insertMany 跳过了这一步)
|
|
@@ -366,8 +442,9 @@ class Table {
|
|
|
366
442
|
if (raw !== undefined && raw !== null && def.min !== undefined && v < min) throw createError('ER_OUT_OF_RANGE', field);
|
|
367
443
|
if (raw !== undefined && raw !== null && def.max !== undefined && v > max) throw createError('ER_OUT_OF_RANGE', field);
|
|
368
444
|
}
|
|
369
|
-
if (def.check && data[field] !== undefined && !def.check(data[field], data)) throw createError('ER_CHECK_CONSTRAINT', this._name + '.' + field);
|
|
370
445
|
}
|
|
446
|
+
// CHECK 约束统一在列循环外整体校验(支持跨列/表级约束)
|
|
447
|
+
this._enforceChecks(data);
|
|
371
448
|
// 主键唯一性检查(主键可能不在 _cachedUniqueFields 中)
|
|
372
449
|
if (this._primaryKey && data[this._primaryKey] !== undefined && data[this._primaryKey] !== null) {
|
|
373
450
|
const pkVal = data[this._primaryKey];
|
|
@@ -774,7 +851,7 @@ class Table {
|
|
|
774
851
|
}
|
|
775
852
|
}
|
|
776
853
|
}
|
|
777
|
-
|
|
854
|
+
this._registerChecks(field, definition);
|
|
778
855
|
if (definition.foreignKey) {
|
|
779
856
|
this._foreignKeys.push({
|
|
780
857
|
field,
|
|
@@ -885,7 +962,7 @@ class Table {
|
|
|
885
962
|
this._schema[field] = { ...this._schema[field], ...definition };
|
|
886
963
|
if (definition.default !== undefined) this._defaults[field] = definition.default;
|
|
887
964
|
this._checkConstraints = this._checkConstraints.filter(c => c.field !== field);
|
|
888
|
-
|
|
965
|
+
this._registerChecks(field, definition);
|
|
889
966
|
if (definition.primaryKey !== undefined || definition.unique !== undefined) {
|
|
890
967
|
if (definition.primaryKey || definition.unique) {
|
|
891
968
|
if (!this._btrees[field]) this._btrees[field] = new BTree(64, true);
|
|
@@ -1499,6 +1576,9 @@ class Table {
|
|
|
1499
1576
|
// ============================================================
|
|
1500
1577
|
|
|
1501
1578
|
_validateConstraints(data, excludeIndex, uniqueTracker, opts = {}) {
|
|
1579
|
+
// CHECK 约束(含跨列/表级):整行校验一次,不能按"当前列"门控 ——
|
|
1580
|
+
// 否则 UPDATE 只改 y 时,挂在 x 上的 CHECK(x > y) 就漏检了。
|
|
1581
|
+
this._enforceChecks(data);
|
|
1502
1582
|
for (const [field, def] of Object.entries(this._schema)) {
|
|
1503
1583
|
if (field === '_softDelete') continue;
|
|
1504
1584
|
|
|
@@ -1561,13 +1641,6 @@ class Table {
|
|
|
1561
1641
|
}
|
|
1562
1642
|
}
|
|
1563
1643
|
|
|
1564
|
-
// CHECK
|
|
1565
|
-
for (const { field: cf, fn } of this._checkConstraints) {
|
|
1566
|
-
if (cf === field && data[field] !== undefined && !fn(data[field], data)) {
|
|
1567
|
-
throw createError('ER_CHECK_CONSTRAINT', this._name + '.' + field);
|
|
1568
|
-
}
|
|
1569
|
-
}
|
|
1570
|
-
|
|
1571
1644
|
// 长度限制
|
|
1572
1645
|
if (def.length && typeof data[field] === 'string' && data[field].length > def.length) {
|
|
1573
1646
|
throw createError('ER_DATA_TOO_LONG', field);
|
|
@@ -1736,9 +1809,7 @@ class Table {
|
|
|
1736
1809
|
const result = { ...data };
|
|
1737
1810
|
for (const [field, defaultValue] of Object.entries(this._defaults)) {
|
|
1738
1811
|
if (result[field] === undefined) {
|
|
1739
|
-
result[field] =
|
|
1740
|
-
? defaultValue()
|
|
1741
|
-
: (defaultValue === 'CURRENT_TIMESTAMP' ? now() : defaultValue);
|
|
1812
|
+
result[field] = resolveDefaultValue(defaultValue, field);
|
|
1742
1813
|
}
|
|
1743
1814
|
}
|
|
1744
1815
|
return result;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jsql-neo",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.6.0",
|
|
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",
|
|
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/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.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",
|
|
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/issue-69-70.test.js && node test/issue-71-72.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",
|
package/postinstall.js
CHANGED
|
@@ -26,10 +26,12 @@ const NATIVE_PATH = process.env.JSQL_NATIVE_PATH
|
|
|
26
26
|
// 前缀必须显式设置 JSQL_GHPROXY(逗号分隔多个,按序回退;'' 表示直连);
|
|
27
27
|
// token 只能从环境变量 JSQL_GHPROXY_TOKEN 读取,代码内不再内置任何 token。
|
|
28
28
|
//
|
|
29
|
-
// 供应链安全(issue #25
|
|
30
|
-
//
|
|
31
|
-
//
|
|
32
|
-
|
|
29
|
+
// 供应链安全(issue #25):已移除内置 de5.net 加速站与硬编码 token。这里只内置
|
|
30
|
+
// 「不需要 token 的公共加速站」,且所有代理下载仍强制通过 SHA256SUMS 校验,
|
|
31
|
+
// 因此第三方端点被投毒也装不进去(校验不通过即回退到下一个候选/直连)。
|
|
32
|
+
// gh-proxy.com 实测:v6.5.32 资产 SHA256 与官方 SHA256SUMS 完全一致,且为合法 ELF。
|
|
33
|
+
// 优先级:JSQL_GHPROXY(用户显式)→ 内置公共加速站 → 直连 github.com。
|
|
34
|
+
const DEFAULT_PROXIES = ['https://gh-proxy.com/'];
|
|
33
35
|
const GHPROXY = process.env.JSQL_GHPROXY !== undefined
|
|
34
36
|
? process.env.JSQL_GHPROXY
|
|
35
37
|
: '';
|
package/test/issue-50.test.js
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
/*
|
|
2
2
|
* Issue #50 — DATETIME 列把 ISO-8601 的 Z / 时区偏移当成本地时间原样存储。
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* 历史:#50 引入了「带时区标记 → 换算到本地时区;无标记 → 本地字面值」的语义。
|
|
5
|
+
* 自 6.6.0 起引擎改为 **UTC 稳定基准**(见 #75):
|
|
6
|
+
* - 带 Z / ±HH:MM → 先换算成绝对时刻,再以 UTC 墙上时间落库;
|
|
7
|
+
* - 不带时区标记 → 字面值即 UTC 墙上时间,原样落库。
|
|
8
|
+
* 这样 '2024-01-15T10:30:00Z' 与 '2024-01-15 10:30:00' 落库一致,
|
|
9
|
+
* 且结果与运行主机时区无关(旧语义在不同 TZ 的机器上落库值不同)。
|
|
6
10
|
*
|
|
7
|
-
*
|
|
11
|
+
* 断言全部用 Date.UTC 计算期望值,故任何 TZ 下都成立。
|
|
8
12
|
*/
|
|
9
13
|
const path = require('path');
|
|
10
14
|
const ROOT = path.join(__dirname, '..');
|
|
@@ -18,36 +22,37 @@ function ok(name, cond, extra) {
|
|
|
18
22
|
}
|
|
19
23
|
|
|
20
24
|
const pad2 = (n) => String(n).padStart(2, '0');
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
+
/** 绝对时刻(毫秒)→ UTC 墙上时间 'YYYY-MM-DD HH:MM:SS' —— 即落库格式 */
|
|
26
|
+
function utcStr(ms) {
|
|
27
|
+
const d = new Date(ms);
|
|
28
|
+
return `${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(d.getUTCDate())} ` +
|
|
29
|
+
`${pad2(d.getUTCHours())}:${pad2(d.getUTCMinutes())}:${pad2(d.getUTCSeconds())}`;
|
|
25
30
|
}
|
|
31
|
+
/** 带时区标记的 ISO 串 → 落库值(UTC 墙上时间) */
|
|
32
|
+
function storedOf(iso) { return utcStr(Date.parse(iso)); }
|
|
26
33
|
|
|
27
34
|
(async () => {
|
|
28
35
|
const db = new Database(':memory:');
|
|
29
36
|
const q = (sql) => executeSQL(db, sql, { safety: false });
|
|
30
37
|
await q('CREATE TABLE t (id INTEGER PRIMARY KEY, dt DATETIME)');
|
|
31
38
|
|
|
32
|
-
// 1) 带 Z
|
|
39
|
+
// 1) 带 Z:绝对时刻不变,按 UTC 墙上时间存储
|
|
33
40
|
await q("INSERT INTO t (id, dt) VALUES (1, '2024-01-15T10:30:00Z')");
|
|
34
41
|
let r = await q('SELECT dt FROM t WHERE id = 1');
|
|
35
|
-
const expectZ =
|
|
36
|
-
ok('#50 ISO Z
|
|
37
|
-
|
|
38
|
-
ok('#50 UTC+8 下 Z 时间 +8 小时', r.rows[0][0] === '2024-01-15 18:30:00', r.rows[0][0]);
|
|
39
|
-
}
|
|
42
|
+
const expectZ = storedOf('2024-01-15T10:30:00Z');
|
|
43
|
+
ok('#50 ISO Z 按绝对时刻存储(UTC 墙上时间)', r.rows[0][0] === expectZ, { got: r.rows[0][0], want: expectZ });
|
|
44
|
+
ok('#50 Z 字面量具体值:2024-01-15 10:30:00', r.rows[0][0] === '2024-01-15 10:30:00', r.rows[0][0]);
|
|
40
45
|
|
|
41
46
|
// 2) 带正偏移 +02:00
|
|
42
47
|
await q("INSERT INTO t (id, dt) VALUES (2, '2024-01-15T10:30:00+02:00')");
|
|
43
48
|
r = await q('SELECT dt FROM t WHERE id = 2');
|
|
44
|
-
const expectPlus2 =
|
|
49
|
+
const expectPlus2 = storedOf('2024-01-15T10:30:00+02:00');
|
|
45
50
|
ok('#50 ISO +02:00 偏移正确换算', r.rows[0][0] === expectPlus2, { got: r.rows[0][0], want: expectPlus2 });
|
|
46
51
|
|
|
47
52
|
// 3) 带负偏移 -05:00
|
|
48
53
|
await q("INSERT INTO t (id, dt) VALUES (3, '2024-01-15T10:30:00-05:00')");
|
|
49
54
|
r = await q('SELECT dt FROM t WHERE id = 3');
|
|
50
|
-
const expectMinus5 =
|
|
55
|
+
const expectMinus5 = storedOf('2024-01-15T10:30:00-05:00');
|
|
51
56
|
ok('#50 ISO -05:00 偏移正确换算', r.rows[0][0] === expectMinus5, { got: r.rows[0][0], want: expectMinus5 });
|
|
52
57
|
|
|
53
58
|
// 4) 带毫秒 + Z
|
|
@@ -55,12 +60,14 @@ function localStr(utcMs) {
|
|
|
55
60
|
r = await q('SELECT dt FROM t WHERE id = 4');
|
|
56
61
|
ok('#50 带毫秒的 Z 同样换算(毫秒截断)', r.rows[0][0] === expectZ, r.rows[0][0]);
|
|
57
62
|
|
|
58
|
-
// 5)
|
|
63
|
+
// 5) 不带时区标记:字面值即 UTC 墙上时间,原样保存(与 Z 等价)
|
|
59
64
|
await q("INSERT INTO t (id, dt) VALUES (5, '2024-01-15T10:30:00')");
|
|
60
65
|
await q("INSERT INTO t (id, dt) VALUES (6, '2024-01-15 10:30:00')");
|
|
61
66
|
r = await q('SELECT dt FROM t WHERE id IN (5,6)');
|
|
62
67
|
ok('#50 无时区的 ISO 串按字面值保存', r.rows[0][0] === '2024-01-15 10:30:00', r.rows[0][0]);
|
|
63
68
|
ok('#50 MySQL 格式原样保留', r.rows[1][0] === '2024-01-15 10:30:00', r.rows[1][0]);
|
|
69
|
+
// 与 1) 同一行值完全相同 → 无时区与 Z 在 UTC 基准下等价(round-trip 闭合的关键)
|
|
70
|
+
ok('#50 无时区与 Z 落库一致', r.rows[0][0] === expectZ && r.rows[1][0] === expectZ, r.rows);
|
|
64
71
|
|
|
65
72
|
// 6) 纯日期列不受影响
|
|
66
73
|
await q('CREATE TABLE d (id INTEGER PRIMARY KEY, dd DATE)');
|
|
@@ -90,7 +97,7 @@ function localStr(utcMs) {
|
|
|
90
97
|
const s = isoCases[i];
|
|
91
98
|
await q(`INSERT INTO tz (id, dt) VALUES (${i + 1}, '${s}')`);
|
|
92
99
|
const got = (await q(`SELECT dt FROM tz WHERE id = ${i + 1}`)).rows[0][0];
|
|
93
|
-
const want =
|
|
100
|
+
const want = storedOf(s);
|
|
94
101
|
ok(`#50 等价写法 ${s} 换算正确`, got === want, { got, want });
|
|
95
102
|
}
|
|
96
103
|
|
|
@@ -98,12 +105,18 @@ function localStr(utcMs) {
|
|
|
98
105
|
await q('CREATE TABLE crossyear (id INTEGER PRIMARY KEY, dt DATETIME)');
|
|
99
106
|
await q("INSERT INTO crossyear VALUES (1, '2024-01-01T00:30:00+09:00')");
|
|
100
107
|
r = await q('SELECT dt FROM crossyear WHERE id = 1');
|
|
101
|
-
//
|
|
102
|
-
const expectCross =
|
|
108
|
+
// +09:00 的 2024-01-01 00:30 == 2023-12-31 15:30Z(跨回上一年)
|
|
109
|
+
const expectCross = storedOf('2024-01-01T00:30:00+09:00');
|
|
103
110
|
ok('#50 时区换算可跨年', r.rows[0][0] === expectCross, { got: r.rows[0][0], want: expectCross });
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
111
|
+
ok('#50 跨年具体值 2023-12-31 15:30:00', r.rows[0][0] === '2023-12-31 15:30:00', r.rows[0][0]);
|
|
112
|
+
|
|
113
|
+
// 10) 主机时区无关性:同一 INSERT 在任何 TZ 下都得到同一落库值
|
|
114
|
+
ok('#50 落库值与主机时区无关(无时区字面量)',
|
|
115
|
+
validateDateType('2024-01-15 10:30:00', 'datetime', 'dt') === '2024-01-15 10:30:00',
|
|
116
|
+
validateDateType('2024-01-15 10:30:00', 'datetime', 'dt'));
|
|
117
|
+
ok('#50 TIMESTAMP 落库值与主机时区无关',
|
|
118
|
+
validateDateType('2020-01-02 03:04:05', 'timestamp', 'ts') === Math.floor(Date.UTC(2020, 0, 2, 3, 4, 5) / 1000),
|
|
119
|
+
validateDateType('2020-01-02 03:04:05', 'timestamp', 'ts'));
|
|
107
120
|
})();
|
|
108
121
|
|
|
109
122
|
setTimeout(() => {
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/* ---- issue #69 / #70 回归 ---- */
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const ROOT = path.join(__dirname, '..');
|
|
6
|
+
const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
|
|
7
|
+
|
|
8
|
+
let pass = 0, fail = 0;
|
|
9
|
+
function ok(name, cond, got) {
|
|
10
|
+
if (cond) { pass++; console.log('[OK] ' + name); }
|
|
11
|
+
else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
|
|
12
|
+
}
|
|
13
|
+
async function run(db, sql) { return executeSQL(db, sql, { safety: false }); }
|
|
14
|
+
async function cell(db, sql) { return (await run(db, sql)).rows[0][0]; }
|
|
15
|
+
async function throwsCode(fn, code) {
|
|
16
|
+
try { await fn(); return false; }
|
|
17
|
+
catch (e) { return code ? (e.code === code || e.code === 3819) : true; }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
(async () => {
|
|
21
|
+
// =========================================================
|
|
22
|
+
// #69 字符串算术:MySQL 宽松转换(数值前缀)
|
|
23
|
+
// =========================================================
|
|
24
|
+
{
|
|
25
|
+
const db = new Database(':memory:', { autoSave: false });
|
|
26
|
+
const cases = [
|
|
27
|
+
["SELECT '5a' + 1", 6],
|
|
28
|
+
["SELECT '5a' + 0", 5],
|
|
29
|
+
["SELECT '12abc' + 0", 12],
|
|
30
|
+
["SELECT '5a' + '3'", 8],
|
|
31
|
+
["SELECT '5a' - 1", 4],
|
|
32
|
+
["SELECT '5a' * 2", 10],
|
|
33
|
+
["SELECT '6a' / 2", 3],
|
|
34
|
+
["SELECT '5a' % 2", 1],
|
|
35
|
+
["SELECT '3.5x' + 1", 4.5],
|
|
36
|
+
["SELECT '-2x' + 1", -1],
|
|
37
|
+
["SELECT 'abc' + 1", 1],
|
|
38
|
+
["SELECT 'a' + 'b'", 0],
|
|
39
|
+
["SELECT '' + 5", 5],
|
|
40
|
+
];
|
|
41
|
+
for (const [sql, want] of cases) {
|
|
42
|
+
const got = await cell(db, sql);
|
|
43
|
+
ok('#69 ' + sql + ' = ' + want, got === want, got);
|
|
44
|
+
}
|
|
45
|
+
ok("#69 '5a' = 5 为真(数值比较)", (await cell(db, "SELECT '5a' = 5")) === 1, null);
|
|
46
|
+
ok("#69 '5a' > 4 为真", (await cell(db, "SELECT '5a' > 4")) === 1, null);
|
|
47
|
+
|
|
48
|
+
// 列数据:TEXT 列里的脏数字同样按数值前缀参与算术
|
|
49
|
+
await run(db, 'CREATE TABLE t69 (id INT PRIMARY KEY, v TEXT)');
|
|
50
|
+
await db.insert('t69', { id: 1, v: '5abc' });
|
|
51
|
+
await db.insert('t69', { id: 2, v: '12x' });
|
|
52
|
+
ok('#69 列值 v + 1', (await cell(db, 'SELECT v + 1 FROM t69 WHERE id = 1')) === 6, null);
|
|
53
|
+
ok('#69 WHERE v + 0 = 12 命中', (await cell(db, 'SELECT COUNT(*) FROM t69 WHERE v + 0 = 12')) === 1, null);
|
|
54
|
+
ok('#69 聚合 SUM(v + 0)', (await cell(db, 'SELECT SUM(v + 0) FROM t69')) === 17, null);
|
|
55
|
+
|
|
56
|
+
// 保持既有语义:NULL 参与运算仍是 NULL
|
|
57
|
+
ok('#69 NULL + 1 = NULL', (await cell(db, 'SELECT NULL + 1')) === null, null);
|
|
58
|
+
// 精确整数 / BigInt 路径不受影响
|
|
59
|
+
ok('#69 BigInt 加法仍精确', (await cell(db, 'SELECT 9007199254740993 + 1')) === 9007199254740994n ||
|
|
60
|
+
String(await cell(db, 'SELECT 9007199254740993 + 1')) === '9007199254740994', null);
|
|
61
|
+
// '!' 逻辑非(解析器此前会抛 Unexpected token '!')
|
|
62
|
+
ok('#69 !1 = 0', (await cell(db, 'SELECT !1')) === 0, null);
|
|
63
|
+
ok('#69 !0 = 1', (await cell(db, 'SELECT !0')) === 1, null);
|
|
64
|
+
ok('#69 != 未被破坏', (await cell(db, 'SELECT 1 != 2')) === 1, null);
|
|
65
|
+
await db.close?.();
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// =========================================================
|
|
69
|
+
// #70 CHECK 约束:列级 / 表级 / 更新 / 批量 / 语法错误
|
|
70
|
+
// =========================================================
|
|
71
|
+
{
|
|
72
|
+
const db = new Database(':memory:', { autoSave: false });
|
|
73
|
+
|
|
74
|
+
// ---- 列级 ----
|
|
75
|
+
await run(db, 'CREATE TABLE ck (id INT PRIMARY KEY, age INT CHECK (age >= 0))');
|
|
76
|
+
ok('#70 列级 CHECK 合法插入', await throwsCode(async () => db.insert('ck', { id: 1, age: 10 }), null) === false, null);
|
|
77
|
+
ok('#70 列级 CHECK 拒绝负值', await throwsCode(() => db.insert('ck', { id: 2, age: -1 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
78
|
+
ok('#70 列级 CHECK 拒绝 SQL 插入', await throwsCode(() => run(db, 'INSERT INTO ck (id, age) VALUES (3, -5)'), 'ER_CHECK_CONSTRAINT'), null);
|
|
79
|
+
ok('#70 列级 CHECK 允许 NULL', await throwsCode(async () => db.insert('ck', { id: 4, age: null }), null) === false, null);
|
|
80
|
+
|
|
81
|
+
// ---- UPDATE 两条路径都要校验 ----
|
|
82
|
+
ok('#70 SQL UPDATE 违反 CHECK 报错', await throwsCode(() => run(db, 'UPDATE ck SET age = -1 WHERE id = 1'), 'ER_CHECK_CONSTRAINT'), null);
|
|
83
|
+
ok('#70 updateById 违反 CHECK 报错', await throwsCode(() => db.updateById('ck', 1, { age: -1 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
84
|
+
ok('#70 合法 UPDATE 生效', (await run(db, 'UPDATE ck SET age = 20 WHERE id = 1')).affectedRows === 1, null);
|
|
85
|
+
ok('#70 UPDATE 后值正确', (await cell(db, 'SELECT age FROM ck WHERE id = 1')) === 20, null);
|
|
86
|
+
|
|
87
|
+
// ---- 批量插入 ----
|
|
88
|
+
const many = await throwsCode(() => db.insert('ck', [{ id: 10, age: 1 }, { id: 11, age: -2 }]), 'ER_CHECK_CONSTRAINT');
|
|
89
|
+
ok('#70 insertMany 违反 CHECK 报错', many, null);
|
|
90
|
+
ok('#70 insertMany 失败行未写入', (await cell(db, 'SELECT COUNT(*) FROM ck WHERE id = 11')) === 0, null);
|
|
91
|
+
|
|
92
|
+
// ---- 表级(跨列) ----
|
|
93
|
+
await run(db, 'CREATE TABLE tk (x INT, y INT, CHECK (x > y))');
|
|
94
|
+
ok('#70 表级跨列满足', await throwsCode(async () => db.insert('tk', { x: 10, y: 1 }), null) === false, null);
|
|
95
|
+
ok('#70 表级跨列违反(插入)', await throwsCode(() => db.insert('tk', { x: 1, y: 10 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
96
|
+
ok('#70 表级跨列违反(只更新一列)', await throwsCode(() => db.updateById('tk', 1, { y: 99 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
97
|
+
ok('#70 表级跨列违反(SQL UPDATE)', await throwsCode(() => run(db, 'UPDATE tk SET y = 50 WHERE x = 10'), 'ER_CHECK_CONSTRAINT'), null);
|
|
98
|
+
|
|
99
|
+
// ---- 具名约束 / 多条约束 / 复杂条件 ----
|
|
100
|
+
await run(db, `CREATE TABLE ck2 (
|
|
101
|
+
id INT PRIMARY KEY,
|
|
102
|
+
a INT,
|
|
103
|
+
b INT,
|
|
104
|
+
CONSTRAINT ck_ab CHECK (a < b),
|
|
105
|
+
CHECK (b < 100),
|
|
106
|
+
CHECK (a >= 0 AND b >= 0)
|
|
107
|
+
)`);
|
|
108
|
+
ok('#70 多约束合法行', await throwsCode(async () => db.insert('ck2', { id: 1, a: 1, b: 2 }), null) === false, null);
|
|
109
|
+
ok('#70 多约束 ck_ab 违反', await throwsCode(() => db.insert('ck2', { id: 2, a: 3, b: 2 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
110
|
+
ok('#70 多约束 b < 100 违反', await throwsCode(() => db.insert('ck2', { id: 3, a: 1, b: 200 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
111
|
+
ok('#70 AND 条件违反', await throwsCode(() => db.insert('ck2', { id: 4, a: -1, b: 2 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
112
|
+
ok('#70 任一列为 NULL 时条件为 UNKNOWN→通过', await throwsCode(async () => db.insert('ck2', { id: 5, a: null, b: 2 }), null) === false, null);
|
|
113
|
+
|
|
114
|
+
// ---- 函数 / IN 条件也能编译执行 ----
|
|
115
|
+
await run(db, "CREATE TABLE ck3 (id INT PRIMARY KEY, s TEXT CHECK (LENGTH(s) > 0 AND s NOT IN ('bad')))");
|
|
116
|
+
ok('#70 函数条件合法', await throwsCode(async () => db.insert('ck3', { id: 1, s: 'ok' }), null) === false, null);
|
|
117
|
+
ok('#70 函数条件违反(空串)', await throwsCode(() => db.insert('ck3', { id: 2, s: '' }), 'ER_CHECK_CONSTRAINT'), null);
|
|
118
|
+
ok('#70 IN 条件违反', await throwsCode(() => db.insert('ck3', { id: 3, s: 'bad' }), 'ER_CHECK_CONSTRAINT'), null);
|
|
119
|
+
|
|
120
|
+
// ---- 语法错误不能被静默吞掉 ----
|
|
121
|
+
ok('#70 CHECK 语法错误在 CREATE 时报错', await throwsCode(() => run(db, 'CREATE TABLE bad1 (a INT CHECK (a >=))')), null);
|
|
122
|
+
ok('#70 CHECK 缺少右括号报错', await throwsCode(() => run(db, 'CREATE TABLE bad2 (a INT CHECK (a > 0)')), null);
|
|
123
|
+
|
|
124
|
+
// ---- 程序化 createTable(JS API)不受影响 ----
|
|
125
|
+
await db.createTable('prog', { id: { type: 'integer', primaryKey: true }, n: { type: 'integer', check: (v) => v > 0 } });
|
|
126
|
+
ok('#70 JS API def.check 仍生效', await throwsCode(() => db.insert('prog', { id: 1, n: -1 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
127
|
+
|
|
128
|
+
await db.close?.();
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// =========================================================
|
|
132
|
+
// #70 持久化:磁盘目录模式重开后 CHECK 仍生效
|
|
133
|
+
// =========================================================
|
|
134
|
+
{
|
|
135
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-ck70-'));
|
|
136
|
+
let db = new Database(dir, { mode: 'disk' });
|
|
137
|
+
await run(db, 'CREATE TABLE p (id INT PRIMARY KEY, age INT CHECK (age >= 0), CHECK (age < 100))');
|
|
138
|
+
await db.insert('p', { id: 1, age: 5 });
|
|
139
|
+
await db.close();
|
|
140
|
+
|
|
141
|
+
db = new Database(dir, { mode: 'disk' });
|
|
142
|
+
ok('#70 重开后数据仍在', (await db.find('p', {}))[0].age === 5, null);
|
|
143
|
+
ok('#70 重开后列级 CHECK 生效', await throwsCode(() => db.insert('p', { id: 2, age: -1 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
144
|
+
ok('#70 重开后表级 CHECK 生效', await throwsCode(() => db.insert('p', { id: 3, age: 200 }), 'ER_CHECK_CONSTRAINT'), null);
|
|
145
|
+
ok('#70 重开后合法数据可插入', await throwsCode(async () => db.insert('p', { id: 4, age: 8 }), null) === false, null);
|
|
146
|
+
await db.close();
|
|
147
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
console.log(`\n${pass} passed, ${fail} failed`);
|
|
151
|
+
process.exit(fail > 0 ? 1 : 0);
|
|
152
|
+
})().catch((e) => { console.error('[FATAL]', e); process.exit(1); });
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Issue #71 / #72 回归测试。
|
|
3
|
+
*
|
|
4
|
+
* #72: `CREATE TABLE t (..., ts TIMESTAMP DEFAULT NOW())` 插入时报
|
|
5
|
+
* "Incorrect date value: 'ts'" —— 根因是 Table 侧只把字符串
|
|
6
|
+
* 'CURRENT_TIMESTAMP' 特判成 now(),'NOW()' 等函数默认值被原样当成
|
|
7
|
+
* 列值,随后日期校验拿列名当值报错。现在 NOW()/NOW(n)/LOCALTIME(STAMP)
|
|
8
|
+
* 都按当前时间戳求值,其他不支持的函数表达式明确报错。
|
|
9
|
+
*
|
|
10
|
+
* #71: `SELECT id FROM a WHERE COUNT(*) > 0` 此前静默返回 0 行(聚合在逐行
|
|
11
|
+
* 上下文中求值为 NULL)。现在在解析阶段就报 1111
|
|
12
|
+
* "Invalid use of group function",与 MySQL 一致;HAVING 不受影响。
|
|
13
|
+
*/
|
|
14
|
+
const path = require('path');
|
|
15
|
+
|
|
16
|
+
const ROOT = path.join(__dirname, '..');
|
|
17
|
+
const { Database } = require(path.join(ROOT, 'index.js'));
|
|
18
|
+
const { executeSQL } = require(path.join(ROOT, 'lib/sql.js'));
|
|
19
|
+
|
|
20
|
+
const OPTS = { safety: false };
|
|
21
|
+
let pass = 0, fail = 0;
|
|
22
|
+
|
|
23
|
+
function ok(name, cond, extra) {
|
|
24
|
+
if (cond) { pass++; console.log('[OK] ', name); }
|
|
25
|
+
else { fail++; console.log('[FAIL]', name, extra !== undefined ? '-> ' + JSON.stringify(extra).slice(0, 160) : ''); }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function t(name, fn) {
|
|
29
|
+
const db = new Database(':memory:');
|
|
30
|
+
const exec = (sql) => executeSQL(db, sql, OPTS);
|
|
31
|
+
const rows = async (sql) => (await exec(sql)).rows;
|
|
32
|
+
const mustFail = async (sql) => {
|
|
33
|
+
try { await exec(sql); return false; } catch (_) { return true; }
|
|
34
|
+
};
|
|
35
|
+
try {
|
|
36
|
+
const r = await fn({ db, exec, rows, mustFail });
|
|
37
|
+
ok(name, r === undefined ? true : !!r);
|
|
38
|
+
} catch (e) {
|
|
39
|
+
ok(name, false, e.message);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
(async () => {
|
|
44
|
+
console.log('\n--- Issue #72: DEFAULT NOW() ---');
|
|
45
|
+
await t('TIMESTAMP DEFAULT NOW() 插入成功且取当前时间', async ({ exec, rows }) => {
|
|
46
|
+
const before = Math.floor(Date.now() / 1000);
|
|
47
|
+
await exec('CREATE TABLE t (id INTEGER PRIMARY KEY, ts TIMESTAMP DEFAULT NOW())');
|
|
48
|
+
await exec('INSERT INTO t (id) VALUES (1)');
|
|
49
|
+
const r = await rows('SELECT ts FROM t');
|
|
50
|
+
const ts = r[0][0];
|
|
51
|
+
return typeof ts === 'number' && ts >= before - 5 && ts <= before + 10;
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
await t('DATETIME DEFAULT NOW() / NOW(6) 同样工作', async ({ exec, rows }) => {
|
|
55
|
+
await exec('CREATE TABLE t (id INTEGER PRIMARY KEY, a DATETIME DEFAULT NOW(), b DATETIME DEFAULT NOW(6))');
|
|
56
|
+
await exec('INSERT INTO t (id) VALUES (1)');
|
|
57
|
+
const r = await rows('SELECT a, b FROM t');
|
|
58
|
+
return typeof r[0][0] === 'string' && r[0][0].length >= 10
|
|
59
|
+
&& typeof r[0][1] === 'string' && r[0][1].length >= 10;
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
await t('DEFAULT CURRENT_TIMESTAMP 不回归', async ({ exec, rows }) => {
|
|
63
|
+
await exec('CREATE TABLE t (id INTEGER PRIMARY KEY, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP)');
|
|
64
|
+
await exec('INSERT INTO t (id) VALUES (1)');
|
|
65
|
+
const r = await rows('SELECT ts FROM t');
|
|
66
|
+
return typeof r[0][0] === 'number' && r[0][0] > 1600000000;
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
await t('显式日期值仍优先于默认值', async ({ exec, rows }) => {
|
|
70
|
+
await exec("CREATE TABLE t (id INTEGER PRIMARY KEY, ts TIMESTAMP DEFAULT NOW())");
|
|
71
|
+
await exec("INSERT INTO t (id, ts) VALUES (1, '2020-01-02 03:04:05')");
|
|
72
|
+
const r = await rows('SELECT ts FROM t');
|
|
73
|
+
// 无时区字面量按 UTC 墙上时间解释(6.6.0 起的稳定基准):
|
|
74
|
+
// 2020-01-02 03:04:05 UTC == 1577934245。这里用 Date.UTC 计算,
|
|
75
|
+
// 断言与运行环境时区无关(此前硬编码 1577905445 是 +08:00 下的值,UTC runner 必红)。
|
|
76
|
+
return r[0][0] === Math.floor(Date.UTC(2020, 0, 2, 3, 4, 5) / 1000);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
await t('不支持的函数默认值明确报错(不再说 Incorrect date value)', async ({ mustFail, exec }) => {
|
|
80
|
+
await exec('CREATE TABLE t (id INTEGER PRIMARY KEY, ts TIMESTAMP DEFAULT UUID())');
|
|
81
|
+
let msg = '';
|
|
82
|
+
try { await exec('INSERT INTO t (id) VALUES (1)'); } catch (e) { msg = e.message; }
|
|
83
|
+
return /Unsupported default expression/i.test(msg) || await mustFail('INSERT INTO t (id) VALUES (1)');
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
await t('普通字面量默认值不回归', async ({ exec, rows }) => {
|
|
87
|
+
await exec("CREATE TABLE t (id INTEGER PRIMARY KEY, s VARCHAR(20) DEFAULT 'abc', n INTEGER DEFAULT 3)");
|
|
88
|
+
await exec('INSERT INTO t (id) VALUES (1)');
|
|
89
|
+
const r = await rows('SELECT s, n FROM t');
|
|
90
|
+
return r[0][0] === 'abc' && r[0][1] === 3;
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
console.log('\n--- Issue #71: WHERE 中的聚合函数 ---');
|
|
94
|
+
const setup = async (exec) => {
|
|
95
|
+
await exec('CREATE TABLE a (id INTEGER PRIMARY KEY, v INTEGER)');
|
|
96
|
+
await exec('INSERT INTO a (id, v) VALUES (1, 5), (2, 7), (3, 9)');
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
await t('WHERE COUNT(*) > 0 报错', async ({ exec, mustFail }) => {
|
|
100
|
+
await setup(exec);
|
|
101
|
+
return await mustFail('SELECT id FROM a WHERE COUNT(*) > 0');
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
await t('WHERE SUM(v) > 10 报错', async ({ exec, mustFail }) => {
|
|
105
|
+
await setup(exec);
|
|
106
|
+
return await mustFail('SELECT id FROM a WHERE SUM(v) > 10');
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
await t('嵌套在 AND / NOT / 算术里的聚合也报错', async ({ exec, mustFail }) => {
|
|
110
|
+
await setup(exec);
|
|
111
|
+
const a = await mustFail('SELECT id FROM a WHERE v > 1 AND AVG(v) > 0');
|
|
112
|
+
const b = await mustFail('SELECT id FROM a WHERE NOT COUNT(*) > 0');
|
|
113
|
+
const c = await mustFail('SELECT id FROM a WHERE COUNT(*) + 1 > 0');
|
|
114
|
+
return a && b && c;
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
await t('普通 WHERE 不回归', async ({ exec, rows }) => {
|
|
118
|
+
await setup(exec);
|
|
119
|
+
const r = await rows('SELECT id FROM a WHERE v > 6');
|
|
120
|
+
return JSON.stringify(r) === JSON.stringify([[2], [3]]);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
await t('HAVING 中的聚合不受影响', async ({ exec, rows }) => {
|
|
124
|
+
await setup(exec);
|
|
125
|
+
const r = await rows('SELECT COUNT(*) AS c FROM a HAVING COUNT(*) > 2');
|
|
126
|
+
return r.length === 1 && r[0][0] === 3;
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
await t('子查询里的聚合合法(WHERE ... IN (SELECT MAX(...)))', async ({ exec, rows }) => {
|
|
130
|
+
await setup(exec);
|
|
131
|
+
const r = await rows('SELECT id FROM a WHERE v IN (SELECT MAX(v) FROM a)');
|
|
132
|
+
return JSON.stringify(r) === JSON.stringify([[3]]);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
console.log(`\n${pass} passed, ${fail} failed`);
|
|
136
|
+
process.exit(fail === 0 ? 0 : 1);
|
|
137
|
+
})().catch(e => { console.error('💥', e); process.exit(1); });
|