jsql-neo 6.8.23 → 6.8.25
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 +11 -9
- package/lib/native_client.js +103 -6
- package/lib/pg_server.js +55 -19
- package/lib/sql.js +26 -20
- package/package.json +3 -3
- package/test/issue-181-186.test.js +1 -1
- package/test/issue-188-237.test.js +1 -1
- package/test/issue-247-295-277.test.js +66 -0
- package/test/issue-322-325.test.js +59 -0
- package/test/issue-38.test.js +3 -0
- package/test/wal-recovery.test.js +9 -9
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
> **One engine to rule them all** — a Rust-powered embedded database that speaks your language:
|
|
4
4
|
> MySQL, PostgreSQL, MongoDB, Redis, SQL, TypeScript, **and the browser**.
|
|
5
5
|
|
|
6
|
-
> **v6.8.
|
|
6
|
+
> **v6.8.25** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
|
|
7
7
|
|
|
8
8
|

|
|
9
9
|

|
package/index.js
CHANGED
package/lib/database.js
CHANGED
|
@@ -213,7 +213,8 @@ class Database {
|
|
|
213
213
|
this._jsqlFormat = this._jsqlMode ? new JSQLFormat(this._filePath, this._encryptKey) : null;
|
|
214
214
|
|
|
215
215
|
// 文件锁
|
|
216
|
-
|
|
216
|
+
// #295:默认开启文件锁,避免两个实例静默互相覆盖
|
|
217
|
+
this._fileLockEnabled = options.fileLock !== false && !this._memoryMode;
|
|
217
218
|
this._lockFd = null;
|
|
218
219
|
this._lockPath = this._filePath ? this._filePath + '.lock' : null;
|
|
219
220
|
|
|
@@ -228,14 +229,13 @@ class Database {
|
|
|
228
229
|
if (!this._memoryMode && !this._dirMode) {
|
|
229
230
|
const hasDataFile = this._filePath ? fs.existsSync(this._filePath) : false;
|
|
230
231
|
const hasWal = this._walEnabled && this._walPath && fs.existsSync(this._walPath);
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
}
|
|
232
|
+
// #295:即使数据文件尚不存在也要先拿锁,否则两个新实例会同时写同一路径
|
|
233
|
+
this._loading = true;
|
|
234
|
+
this._acquireLock();
|
|
235
|
+
try {
|
|
236
|
+
if (hasDataFile || hasWal) this._load();
|
|
237
|
+
} finally {
|
|
238
|
+
this._loading = false;
|
|
239
239
|
}
|
|
240
240
|
}
|
|
241
241
|
|
|
@@ -2776,6 +2776,8 @@ class Database {
|
|
|
2776
2776
|
this._sigInstalled = false;
|
|
2777
2777
|
Database._uninstallSignalHandler(this);
|
|
2778
2778
|
}
|
|
2779
|
+
// #295:stop() 表示本实例停止写入,必须释放文件锁,否则同路径再打开会误报占用
|
|
2780
|
+
this._releaseLock();
|
|
2779
2781
|
return this;
|
|
2780
2782
|
}
|
|
2781
2783
|
|
package/lib/native_client.js
CHANGED
|
@@ -1156,13 +1156,110 @@ class JSQL {
|
|
|
1156
1156
|
// 没有原生模块时不要构造一个「所有属性都是函数」的假 native:
|
|
1157
1157
|
// 直接回退到 WASM/JS 引擎,保持 API 可用(性能较低但功能完整)。
|
|
1158
1158
|
let ExportedJSQL = JSQL;
|
|
1159
|
+
let DiskFallbackJSQL = null;
|
|
1160
|
+
let WasmJSQL = null;
|
|
1161
|
+
try {
|
|
1162
|
+
WasmJSQL = require('./wasm_client').JSQL;
|
|
1163
|
+
} catch (e) {
|
|
1164
|
+
console.warn('[jsql-neo] WASM fallback unavailable:', e.message);
|
|
1165
|
+
}
|
|
1166
|
+
if (WasmJSQL) {
|
|
1167
|
+
// #247:WASM/JS 引擎本身是纯内存实现。带 path 且非 memory 模式时,
|
|
1168
|
+
// 改由纯 JS 的 Database 承载,保证 stop()/重启后数据真正落盘。
|
|
1169
|
+
DiskFallbackJSQL = class DiskFallbackJSQL extends WasmJSQL {
|
|
1170
|
+
constructor(opts = {}) {
|
|
1171
|
+
const wantDisk = !!opts.path && opts.path !== ':memory:'
|
|
1172
|
+
&& (opts.mode || 'disk') !== 'memory';
|
|
1173
|
+
const superOpts = wantDisk ? Object.assign({}, opts, { modules: false }) : opts;
|
|
1174
|
+
super(superOpts);
|
|
1175
|
+
if (wantDisk) {
|
|
1176
|
+
const Database = require('./database');
|
|
1177
|
+
this._disk = new Database(opts.path, opts);
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
async start() {
|
|
1181
|
+
if (!this._disk) return super.start();
|
|
1182
|
+
await this._disk.start();
|
|
1183
|
+
this._runHooks('onStart', []);
|
|
1184
|
+
this._emit('start', {});
|
|
1185
|
+
}
|
|
1186
|
+
async stop() {
|
|
1187
|
+
if (!this._disk) return super.stop();
|
|
1188
|
+
await this._disk.stop();
|
|
1189
|
+
this._runHooks('onStop', []);
|
|
1190
|
+
this._emit('stop', {});
|
|
1191
|
+
}
|
|
1192
|
+
async createTable(name, schema) {
|
|
1193
|
+
return this._disk ? this._disk.createTable(name, schema) : super.createTable(name, schema);
|
|
1194
|
+
}
|
|
1195
|
+
async addColumn(table, name, def) {
|
|
1196
|
+
return this._disk ? this._disk.addColumn(table, name, def) : super.addColumn(table, name, def);
|
|
1197
|
+
}
|
|
1198
|
+
async dropTable(name) {
|
|
1199
|
+
return this._disk ? this._disk.dropTable(name) : super.dropTable(name);
|
|
1200
|
+
}
|
|
1201
|
+
async insert(table, data) {
|
|
1202
|
+
return this._disk ? this._disk.insert(table, data) : super.insert(table, data);
|
|
1203
|
+
}
|
|
1204
|
+
async insertMany(table, data) {
|
|
1205
|
+
return this._disk ? this._disk.insertMany(table, data) : super.insertMany(table, data);
|
|
1206
|
+
}
|
|
1207
|
+
async find(table, filter, opts) {
|
|
1208
|
+
return this._disk ? this._disk.find(table, filter, opts) : super.find(table, filter, opts);
|
|
1209
|
+
}
|
|
1210
|
+
async findById(table, id) {
|
|
1211
|
+
return this._disk ? this._disk.findById(table, id) : super.findById(table, id);
|
|
1212
|
+
}
|
|
1213
|
+
async findByIds(table, ids) {
|
|
1214
|
+
return this._disk ? this._disk.findByIds(table, ids) : super.findByIds(table, ids);
|
|
1215
|
+
}
|
|
1216
|
+
async updateById(table, id, data) {
|
|
1217
|
+
return this._disk ? this._disk.updateById(table, id, data) : super.updateById(table, id, data);
|
|
1218
|
+
}
|
|
1219
|
+
async updateByIds(table, entries) {
|
|
1220
|
+
return this._disk ? this._disk.updateByIds(table, entries) : super.updateByIds(table, entries);
|
|
1221
|
+
}
|
|
1222
|
+
async removeById(table, id) {
|
|
1223
|
+
return this._disk ? this._disk.removeById(table, id) : super.removeById(table, id);
|
|
1224
|
+
}
|
|
1225
|
+
async removeByIds(table, ids) {
|
|
1226
|
+
return this._disk ? this._disk.removeByIds(table, ids) : super.removeByIds(table, ids);
|
|
1227
|
+
}
|
|
1228
|
+
async count(table) {
|
|
1229
|
+
return this._disk ? this._disk.count(table) : super.count(table);
|
|
1230
|
+
}
|
|
1231
|
+
getTables() {
|
|
1232
|
+
return this._disk ? this._disk.getTables() : super.getTables();
|
|
1233
|
+
}
|
|
1234
|
+
hasTable(name) {
|
|
1235
|
+
return this._disk ? this._disk.hasTable(name) : super.hasTable(name);
|
|
1236
|
+
}
|
|
1237
|
+
async getTableSchema(name) {
|
|
1238
|
+
return this._disk ? this._disk.getTableSchema(name) : super.getTableSchema(name);
|
|
1239
|
+
}
|
|
1240
|
+
async query(sql, paramsOrOpts, opts) {
|
|
1241
|
+
return this._disk ? this._disk.query(sql, paramsOrOpts, opts) : super.query(sql, paramsOrOpts, opts);
|
|
1242
|
+
}
|
|
1243
|
+
async exists(table, filter) {
|
|
1244
|
+
return this._disk ? this._disk.exists(table, filter) : super.exists(table, filter);
|
|
1245
|
+
}
|
|
1246
|
+
async flush() {
|
|
1247
|
+
return this._disk ? this._disk.flush() : super.flush();
|
|
1248
|
+
}
|
|
1249
|
+
async beginTx() {
|
|
1250
|
+
return this._disk ? this._disk.beginTx() : super.beginTx();
|
|
1251
|
+
}
|
|
1252
|
+
async commitTx(id) {
|
|
1253
|
+
return this._disk ? this._disk.commitTx(id) : super.commitTx(id);
|
|
1254
|
+
}
|
|
1255
|
+
async rollbackTx(id) {
|
|
1256
|
+
return this._disk ? this._disk.rollbackTx(id) : super.rollbackTx(id);
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1159
1260
|
if (!NATIVE_AVAILABLE) {
|
|
1160
1261
|
console.warn('[jsql-neo] NativeJSQL unavailable; falling back to the WASM/JS engine.');
|
|
1161
|
-
|
|
1162
|
-
ExportedJSQL = require('./wasm_client').JSQL;
|
|
1163
|
-
} catch (e) {
|
|
1164
|
-
console.warn('[jsql-neo] WASM fallback also unavailable:', e.message);
|
|
1165
|
-
}
|
|
1262
|
+
ExportedJSQL = DiskFallbackJSQL || WasmJSQL || JSQL;
|
|
1166
1263
|
}
|
|
1167
1264
|
|
|
1168
|
-
module.exports = { JSQL: ExportedJSQL, _nativeAvailable: NATIVE_AVAILABLE };
|
|
1265
|
+
module.exports = { JSQL: ExportedJSQL, _nativeAvailable: NATIVE_AVAILABLE, _DiskFallbackJSQL: DiskFallbackJSQL };
|
package/lib/pg_server.js
CHANGED
|
@@ -134,27 +134,46 @@ function frame(type, payload) {
|
|
|
134
134
|
return Buffer.concat([head, payload]);
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
-
|
|
137
|
+
// #277:按列的结果格式码编码二进制 DataRow
|
|
138
|
+
function pgEncodeBinary(value, type) {
|
|
139
|
+
const t = String(type || '').toLowerCase();
|
|
140
|
+
if (t === 'boolean' || t === 'bool') return Buffer.from([value ? 1 : 0]);
|
|
141
|
+
if (t === 'integer' || t === 'int' || t === 'int4' || t === 'serial') {
|
|
142
|
+
const b = Buffer.alloc(4); b.writeInt32BE(Number(value) | 0, 0); return b;
|
|
143
|
+
}
|
|
144
|
+
if (t === 'bigint' || t === 'int8' || t === 'bigserial') {
|
|
145
|
+
const b = Buffer.alloc(8); b.writeBigInt64BE(BigInt(value), 0); return b;
|
|
146
|
+
}
|
|
147
|
+
if (t === 'numeric' || t === 'decimal' || t === 'number' || t === 'float' || t === 'float8') {
|
|
148
|
+
const b = Buffer.alloc(8); b.writeDoubleBE(Number(value), 0); return b;
|
|
149
|
+
}
|
|
150
|
+
return Buffer.from(pgFormatValue(value, type) === null ? '' : String(pgFormatValue(value, type)), 'utf8');
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function buildDataRow(values, types, formats) {
|
|
138
154
|
const p = new PgBuffer();
|
|
139
155
|
p.i16(values.length);
|
|
140
156
|
for (let i = 0; i < values.length; i++) {
|
|
141
|
-
const
|
|
142
|
-
if (
|
|
157
|
+
const fmt = formats && formats.length ? (formats.length === 1 ? formats[0] : formats[i]) : 0;
|
|
158
|
+
if (values[i] === null || values[i] === undefined) {
|
|
143
159
|
p.i32(-1);
|
|
144
|
-
|
|
145
|
-
const b = Buffer.from(s, 'utf8');
|
|
146
|
-
p.i32(b.length);
|
|
147
|
-
p.raw(b);
|
|
160
|
+
continue;
|
|
148
161
|
}
|
|
162
|
+
const b = fmt === 1
|
|
163
|
+
? pgEncodeBinary(values[i], types[i])
|
|
164
|
+
: Buffer.from(pgFormatValue(values[i], types[i]) === null ? '' : String(pgFormatValue(values[i], types[i])), 'utf8');
|
|
165
|
+
p.i32(b.length);
|
|
166
|
+
p.raw(b);
|
|
149
167
|
}
|
|
150
168
|
return frame(0x44, p.build()); // 'D'
|
|
151
169
|
}
|
|
152
170
|
|
|
153
|
-
function buildRowDescription(columns, types) {
|
|
171
|
+
function buildRowDescription(columns, types, formats) {
|
|
154
172
|
const p = new PgBuffer();
|
|
155
173
|
p.i16(columns.length);
|
|
156
174
|
for (let i = 0; i < columns.length; i++) {
|
|
157
175
|
const c = columns[i];
|
|
176
|
+
const fmt = formats && formats.length ? (formats.length === 1 ? formats[0] : formats[i]) : 0;
|
|
158
177
|
p.str(c);
|
|
159
178
|
p.nul();
|
|
160
179
|
p.i32(0); // table oid
|
|
@@ -162,7 +181,7 @@ function buildRowDescription(columns, types) {
|
|
|
162
181
|
p.i32(pgTypeOid(types[i]));
|
|
163
182
|
p.i16(types[i] === 'integer' ? 4 : (types[i] === 'bigint' ? 8 : (types[i] === 'boolean' ? 1 : -1))); // typlen
|
|
164
183
|
p.i32(-1); // typmod
|
|
165
|
-
p.i16(0);
|
|
184
|
+
p.i16(fmt === 1 ? 1 : 0); // format code
|
|
166
185
|
}
|
|
167
186
|
return frame(0x54, p.build()); // 'T'
|
|
168
187
|
}
|
|
@@ -568,7 +587,15 @@ class PgConnection {
|
|
|
568
587
|
err.sqlState = '08P01';
|
|
569
588
|
throw err;
|
|
570
589
|
}
|
|
571
|
-
|
|
590
|
+
// #277:Bind 末尾还有结果格式码列表(0=text,1=binary)
|
|
591
|
+
const resultFormats = [];
|
|
592
|
+
if (off + 2 <= body.length) {
|
|
593
|
+
const nResultFormats = body.readInt16BE(off); off += 2;
|
|
594
|
+
for (let i = 0; i < nResultFormats && off + 2 <= body.length; i++) {
|
|
595
|
+
resultFormats.push(body.readInt16BE(off)); off += 2;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
this._portal.set(portal, { values, stmt, resultFormats });
|
|
572
599
|
this._send(buildBindComplete()); break;
|
|
573
600
|
}
|
|
574
601
|
case 0x44: // 'D' describe
|
|
@@ -638,8 +665,9 @@ class PgConnection {
|
|
|
638
665
|
const portal = this._portal.get(name);
|
|
639
666
|
if (!portal) throw new Error(`portal "${name}" does not exist`);
|
|
640
667
|
const cols = this._describeCols(portal.stmt.sql);
|
|
641
|
-
if (cols && cols.length > 0) {
|
|
642
|
-
this.
|
|
668
|
+
if (cols && cols.columns && cols.columns.length > 0) {
|
|
669
|
+
const fmts = this._columnFormats(cols.columns.length, portal.resultFormats);
|
|
670
|
+
this._send(buildRowDescription(cols.columns, cols.types, fmts));
|
|
643
671
|
} else {
|
|
644
672
|
this._send(buildNoData());
|
|
645
673
|
}
|
|
@@ -719,7 +747,7 @@ class PgConnection {
|
|
|
719
747
|
return;
|
|
720
748
|
}
|
|
721
749
|
try {
|
|
722
|
-
await this._executeSql(sql, null);
|
|
750
|
+
await this._executeSql(sql, null, null);
|
|
723
751
|
} catch (e) {
|
|
724
752
|
if (this._inTransaction) this._txAborted = true;
|
|
725
753
|
this._send(buildErrorResponse(this._pgErrorCode(e), e && e.message ? e.message : String(e)));
|
|
@@ -736,14 +764,14 @@ class PgConnection {
|
|
|
736
764
|
}
|
|
737
765
|
try {
|
|
738
766
|
const { sql } = portal.stmt;
|
|
739
|
-
await this._executeSql(sql, portal.values || []);
|
|
767
|
+
await this._executeSql(sql, portal.values || [], portal.resultFormats);
|
|
740
768
|
} catch (e) {
|
|
741
769
|
if (this._inTransaction) this._txAborted = true;
|
|
742
770
|
this._send(buildErrorResponse(this._pgErrorCode(e), e && e.message ? e.message : String(e)));
|
|
743
771
|
}
|
|
744
772
|
}
|
|
745
773
|
|
|
746
|
-
async _executeSql(sql, values) {
|
|
774
|
+
async _executeSql(sql, values, resultFormats) {
|
|
747
775
|
const engine = await this._getEngine();
|
|
748
776
|
const ctx = {
|
|
749
777
|
session: { currentDb: this.database, connectionId: this._pid },
|
|
@@ -759,19 +787,27 @@ class PgConnection {
|
|
|
759
787
|
}
|
|
760
788
|
const list = Array.isArray(results) ? results : [results];
|
|
761
789
|
for (const res of list) {
|
|
762
|
-
this._emitResult(res);
|
|
790
|
+
this._emitResult(res, resultFormats);
|
|
763
791
|
}
|
|
764
792
|
}
|
|
765
793
|
|
|
766
|
-
|
|
794
|
+
_columnFormats(count, resultFormats) {
|
|
795
|
+
if (!resultFormats || resultFormats.length === 0) return null;
|
|
796
|
+
const out = new Array(count).fill(0);
|
|
797
|
+
for (let i = 0; i < count; i++) out[i] = resultFormats.length === 1 ? resultFormats[0] : (resultFormats[i] || 0);
|
|
798
|
+
return out;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
_emitResult(res, resultFormats) {
|
|
767
802
|
if (!res) return;
|
|
768
803
|
if (res.type === 'select') {
|
|
769
804
|
const types = this._resultTypes(res);
|
|
805
|
+
const fmts = this._columnFormats((res.columns || []).length, resultFormats);
|
|
770
806
|
if (res.columns && res.columns.length > 0) {
|
|
771
|
-
this._send(buildRowDescription(res.columns, types));
|
|
807
|
+
this._send(buildRowDescription(res.columns, types, fmts));
|
|
772
808
|
}
|
|
773
809
|
for (const row of res.rows || []) {
|
|
774
|
-
this._send(buildDataRow(row, types));
|
|
810
|
+
this._send(buildDataRow(row, types, fmts));
|
|
775
811
|
}
|
|
776
812
|
const tag = `SELECT ${(res.rows || []).length}`;
|
|
777
813
|
this._send(buildCommandComplete(tag));
|
package/lib/sql.js
CHANGED
|
@@ -1509,7 +1509,8 @@ class Parser {
|
|
|
1509
1509
|
this.next();
|
|
1510
1510
|
spec.partitionBy = [];
|
|
1511
1511
|
for (;;) {
|
|
1512
|
-
|
|
1512
|
+
// #323:PARTITION BY 允许二元表达式
|
|
1513
|
+
spec.partitionBy.push(this.parseArgExpr());
|
|
1513
1514
|
if (this.peek().type === 'op' && this.peek().value === ',') { this.next(); continue; }
|
|
1514
1515
|
break;
|
|
1515
1516
|
}
|
|
@@ -1520,7 +1521,8 @@ class Parser {
|
|
|
1520
1521
|
this.next();
|
|
1521
1522
|
spec.orderBy = [];
|
|
1522
1523
|
for (;;) {
|
|
1523
|
-
|
|
1524
|
+
// #323:ORDER BY 允许二元表达式
|
|
1525
|
+
const col = this.parseArgExpr();
|
|
1524
1526
|
let dir = 'asc';
|
|
1525
1527
|
if (this.isWord('ASC')) { this.next(); }
|
|
1526
1528
|
else if (this.isWord('DESC')) { this.next(); dir = 'desc'; }
|
|
@@ -3210,7 +3212,8 @@ class Parser {
|
|
|
3210
3212
|
parseCase() {
|
|
3211
3213
|
let base = null;
|
|
3212
3214
|
if (!this.isKeyword('WHEN')) {
|
|
3213
|
-
|
|
3215
|
+
// #322:基表达式允许完整的二元表达式(CASE 1 + 1 WHEN ...)
|
|
3216
|
+
base = this.parseArgExpr();
|
|
3214
3217
|
}
|
|
3215
3218
|
const branches = [];
|
|
3216
3219
|
while (this.isKeyword('WHEN')) {
|
|
@@ -3218,7 +3221,7 @@ class Parser {
|
|
|
3218
3221
|
// 简单 CASE: CASE x WHEN v THEN ... ; 搜索 CASE: CASE WHEN cond THEN ...
|
|
3219
3222
|
let cond;
|
|
3220
3223
|
if (base) {
|
|
3221
|
-
const v = this.
|
|
3224
|
+
const v = this.parseArgExpr();
|
|
3222
3225
|
cond = { type: 'compare', op: '=', left: base, right: v };
|
|
3223
3226
|
} else {
|
|
3224
3227
|
// 条件可能是完整比较(WHEN a > 1),也可能是裸值/裸列(WHEN 1、WHEN flag)。
|
|
@@ -3232,11 +3235,11 @@ class Parser {
|
|
|
3232
3235
|
: { type: 'isTruth', operand: this.parseArgExpr(), not: false, truth: true };
|
|
3233
3236
|
}
|
|
3234
3237
|
this.expectKeyword('THEN');
|
|
3235
|
-
const val = this.
|
|
3238
|
+
const val = this.parseArgExpr();
|
|
3236
3239
|
branches.push({ cond, val });
|
|
3237
3240
|
}
|
|
3238
3241
|
let elseVal = null;
|
|
3239
|
-
if (this.isKeyword('ELSE')) { this.next(); elseVal = this.
|
|
3242
|
+
if (this.isKeyword('ELSE')) { this.next(); elseVal = this.parseArgExpr(); }
|
|
3240
3243
|
this.expectKeyword('END');
|
|
3241
3244
|
return { type: 'case', branches, elseVal };
|
|
3242
3245
|
}
|
|
@@ -3507,11 +3510,13 @@ function applyCast(value, dataType) {
|
|
|
3507
3510
|
const scale = m && m[2] !== undefined ? parseInt(m[2], 10) : 0;
|
|
3508
3511
|
let n = Number(value);
|
|
3509
3512
|
if (!Number.isFinite(n)) return null;
|
|
3513
|
+
// #325:MySQL 的 DECIMAL 舍入是「半远离零」,Math.round 对负半值朝 +∞
|
|
3514
|
+
const roundHalfAway = (x) => (x < 0 ? -Math.round(-x) : Math.round(x));
|
|
3510
3515
|
if (scale > 0) {
|
|
3511
3516
|
const factor = Math.pow(10, scale);
|
|
3512
|
-
n =
|
|
3517
|
+
n = roundHalfAway(n * factor) / factor;
|
|
3513
3518
|
} else {
|
|
3514
|
-
n =
|
|
3519
|
+
n = roundHalfAway(n);
|
|
3515
3520
|
}
|
|
3516
3521
|
return n;
|
|
3517
3522
|
}
|
|
@@ -3916,6 +3921,15 @@ function compareSqlValues(av, bv, dir) {
|
|
|
3916
3921
|
return desc ? -r : r;
|
|
3917
3922
|
}
|
|
3918
3923
|
|
|
3924
|
+
function mysqlWeekMode0(d) {
|
|
3925
|
+
// #324:周日为一周之始,第 1 周是本年第一个含周日的周(之前为第 0 周)
|
|
3926
|
+
const jan1Dow = new Date(Date.UTC(d.getUTCFullYear(), 0, 1)).getUTCDay(); // 0=周日
|
|
3927
|
+
const firstSunday = jan1Dow === 0 ? 1 : 8 - jan1Dow;
|
|
3928
|
+
const doy = Math.round((d - Date.UTC(d.getUTCFullYear(), 0, 0)) / 86400000);
|
|
3929
|
+
if (doy < firstSunday) return 0;
|
|
3930
|
+
return Math.floor((doy - firstSunday) / 7) + 1;
|
|
3931
|
+
}
|
|
3932
|
+
|
|
3919
3933
|
function resolveOperand(operand, row, ctx) {
|
|
3920
3934
|
if (operand === null || operand === undefined) return null;
|
|
3921
3935
|
if (typeof operand === 'string') return resolveOperand({ type: 'column', name: operand }, row, ctx);
|
|
@@ -4731,12 +4745,7 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4731
4745
|
const mode = args[1] != null ? Number(args[1]) : 0;
|
|
4732
4746
|
// mode 1/3(周一为一周之始且首周需 ≥4 天)走 ISO 周序;其余按 MySQL 默认 mode 0
|
|
4733
4747
|
if (mode === 1 || mode === 3) return pgDatePart('week', d);
|
|
4734
|
-
|
|
4735
|
-
const jan1Dow = new Date(Date.UTC(d.getUTCFullYear(), 0, 1)).getUTCDay(); // 0=周日
|
|
4736
|
-
const firstSunday = jan1Dow === 0 ? 1 : 8 - jan1Dow;
|
|
4737
|
-
const doy = Math.round((d - Date.UTC(d.getUTCFullYear(), 0, 0)) / 86400000);
|
|
4738
|
-
if (doy < firstSunday) return 0;
|
|
4739
|
-
return Math.floor((doy - firstSunday) / 7) + 1;
|
|
4748
|
+
return mysqlWeekMode0(d);
|
|
4740
4749
|
}
|
|
4741
4750
|
case 'WEEKOFYEAR': { // ISO 周序(同 WEEK(date,3))
|
|
4742
4751
|
const d = parseSqlDate(args[0]);
|
|
@@ -4745,7 +4754,8 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4745
4754
|
case 'YEARWEEK': {
|
|
4746
4755
|
const d = parseSqlDate(args[0]);
|
|
4747
4756
|
if (!d) return null;
|
|
4748
|
-
|
|
4757
|
+
// #324:MySQL 单参默认 mode=0(周日为周首日),与 WEEK(date,0) 同源
|
|
4758
|
+
const mode = args[1] != null ? Number(args[1]) : 0;
|
|
4749
4759
|
if (mode === 1 || mode === 3) {
|
|
4750
4760
|
const week = pgDatePart('week', d);
|
|
4751
4761
|
const thu = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
|
|
@@ -4753,11 +4763,7 @@ function applyScalarFunction(fnNode, row, ctx) {
|
|
|
4753
4763
|
thu.setUTCDate(thu.getUTCDate() - dow + 3); // 该周星期四决定 ISO 年
|
|
4754
4764
|
return thu.getUTCFullYear() * 100 + week;
|
|
4755
4765
|
}
|
|
4756
|
-
|
|
4757
|
-
const jan1 = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
|
|
4758
|
-
return Math.floor((d - jan1) / 604800000) + 1;
|
|
4759
|
-
})();
|
|
4760
|
-
return d.getUTCFullYear() * 100 + week;
|
|
4766
|
+
return d.getUTCFullYear() * 100 + mysqlWeekMode0(d);
|
|
4761
4767
|
}
|
|
4762
4768
|
case 'DAYOFWEEK': { // MySQL:1=周日 … 7=周六
|
|
4763
4769
|
const d = parseSqlDate(args[0]);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jsql-neo",
|
|
3
|
-
"version": "6.8.
|
|
3
|
+
"version": "6.8.25",
|
|
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 && node test/issue-248-252.test.js && node test/issue-259-264.test.js && node test/issue-255-270.test.js && node test/issue-253-269.test.js && node test/issue-280-310.test.js && node test/issue-272-311.test.js && node test/issue-279-306.test.js && node test/issue-271-283.test.js && node test/issue-265-307.test.js && node test/issue-258-300.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 && node test/issue-255-270.test.js && node test/issue-253-269.test.js && node test/issue-280-310.test.js && node test/issue-272-311.test.js && node test/issue-279-306.test.js && node test/issue-271-283.test.js && node test/issue-265-307.test.js && node test/issue-258-300.test.js && node test/issue-247-295-277.test.js && node test/issue-322-325.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 && node test/issue-248-252.test.js && node test/issue-259-264.test.js && node test/issue-255-270.test.js && node test/issue-253-269.test.js && node test/issue-280-310.test.js && node test/issue-272-311.test.js && node test/issue-279-306.test.js && node test/issue-271-283.test.js && node test/issue-265-307.test.js && node test/issue-258-300.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 && node test/issue-255-270.test.js && node test/issue-253-269.test.js && node test/issue-280-310.test.js && node test/issue-272-311.test.js && node test/issue-279-306.test.js && node test/issue-271-283.test.js && node test/issue-265-307.test.js && node test/issue-258-300.test.js && node test/issue-247-295-277.test.js && node test/issue-322-325.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",
|
|
@@ -101,7 +101,7 @@ async function csvRoundTrip() {
|
|
|
101
101
|
async function scalarFunctions() {
|
|
102
102
|
const db = new Database(':memory:');
|
|
103
103
|
const val = async (sql) => (await q(db, sql)).rows[0][0];
|
|
104
|
-
ok('#185 YEARWEEK', await val("SELECT YEARWEEK('2026-11-21')") ===
|
|
104
|
+
ok('#185 YEARWEEK', await val("SELECT YEARWEEK('2026-11-21')") === 202646);
|
|
105
105
|
ok('#185 WEEKOFYEAR', await val("SELECT WEEKOFYEAR('2026-11-21')") === 47);
|
|
106
106
|
ok('#185 MID alias', await val("SELECT MID('abcdef',2,3)") === 'bcd');
|
|
107
107
|
ok('#185 PERIOD_ADD', await val('SELECT PERIOD_ADD(202601,3)') === 202604);
|
|
@@ -235,7 +235,7 @@ async function sqlCases() {
|
|
|
235
235
|
fs.writeFileSync(file, snap.slice(0, Math.floor(snap.length / 2)));
|
|
236
236
|
const orig = console.error; console.error = () => {};
|
|
237
237
|
let err = null, r = null;
|
|
238
|
-
try { const db2 = new Database(file); r = await rows(db2, 'SELECT id,v FROM t ORDER BY id'); db2.stop(); } catch (e) { err = e.message; }
|
|
238
|
+
try { const db2 = new Database(file, { fileLock: false }); r = await rows(db2, 'SELECT id,v FROM t ORDER BY id'); db2.stop(); } catch (e) { err = e.message; }
|
|
239
239
|
console.error = orig;
|
|
240
240
|
ok('#237 torn snapshot falls back to WAL', err === null && r.some(x => x[0] === 3), { err, r });
|
|
241
241
|
db.stop();
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Regression tests for #247 #295 #277.
|
|
3
|
+
*/
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const os = require('os');
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const ROOT = path.join(__dirname, '..');
|
|
8
|
+
const { Database } = require(path.join(ROOT, 'index.js'));
|
|
9
|
+
const pg = require(path.join(ROOT, 'lib', 'pg_server.js'));
|
|
10
|
+
let passed = 0, failed = 0;
|
|
11
|
+
function ok(name, cond, extra) {
|
|
12
|
+
if (cond) { passed++; console.log('[OK]', name); }
|
|
13
|
+
else { failed++; console.log('[FAIL]', name, extra !== undefined ? '→ ' + JSON.stringify(extra) : ''); }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
(async () => {
|
|
17
|
+
// #247 WASM/JS 回退在 disk 模式下必须真正落盘
|
|
18
|
+
{
|
|
19
|
+
const native = require(path.join(ROOT, 'lib', 'native_client.js'));
|
|
20
|
+
if (native._DiskFallbackJSQL) {
|
|
21
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-247-'));
|
|
22
|
+
const file = path.join(dir, 'db.jsql');
|
|
23
|
+
const db1 = new native._DiskFallbackJSQL({ path: file, mode: 'disk' });
|
|
24
|
+
await db1.start();
|
|
25
|
+
await db1.createTable('users', { id: 'INTEGER PRIMARY KEY', name: 'TEXT' });
|
|
26
|
+
await db1.insert('users', { id: 1, name: 'alice' });
|
|
27
|
+
await db1.stop();
|
|
28
|
+
const db2 = new native._DiskFallbackJSQL({ path: file, mode: 'disk' });
|
|
29
|
+
await db2.start();
|
|
30
|
+
const rows = await db2.find('users', {});
|
|
31
|
+
ok('#247 disk fallback persists across restart', rows.length === 1 && rows[0].name === 'alice', rows);
|
|
32
|
+
await db2.stop();
|
|
33
|
+
} else {
|
|
34
|
+
console.log('[SKIP] #247 native module present');
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
// #295 默认文件锁阻止同路径双实例
|
|
38
|
+
{
|
|
39
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-295-'));
|
|
40
|
+
const file = path.join(dir, 'lock.jsql');
|
|
41
|
+
const db1 = new Database(file);
|
|
42
|
+
let code = null;
|
|
43
|
+
try { const db2 = new Database(file); db2.stop(); } catch (e) { code = e.code; }
|
|
44
|
+
ok('#295 second instance on same path is rejected', code === 1205 || code === 'ER_LOCK_WAIT_TIMEOUT', code);
|
|
45
|
+
await db1.stop();
|
|
46
|
+
const db3 = new Database(file);
|
|
47
|
+
ok('#295 lock released after stop', !!db3);
|
|
48
|
+
await db3.stop();
|
|
49
|
+
}
|
|
50
|
+
// #277 Bind 结果格式码 → RowDescription/DataRow 使用二进制
|
|
51
|
+
{
|
|
52
|
+
const desc = pg.buildRowDescription(['n'], ['integer'], [1]);
|
|
53
|
+
ok('#277 RowDescription format code = 1', desc.readInt16BE(desc.length - 2) === 1, desc.toString('hex'));
|
|
54
|
+
const row = pg.buildDataRow([5], ['integer'], [1]);
|
|
55
|
+
const payload = row.slice(5);
|
|
56
|
+
ok('#277 binary int4 DataRow', payload.readInt16BE(0) === 1 && payload.readInt32BE(2) === 4 && payload.readInt32BE(6) === 5, payload.toString('hex'));
|
|
57
|
+
const textRow = pg.buildDataRow([5], ['integer'], [0]);
|
|
58
|
+
ok('#277 text DataRow unchanged', textRow.slice(11).toString() === '5', textRow.toString('hex'));
|
|
59
|
+
const fmts = pg.PgConnection.prototype._columnFormats.call({}, 3, [1]);
|
|
60
|
+
ok('#277 single format applies to all columns', JSON.stringify(fmts) === '[1,1,1]', fmts);
|
|
61
|
+
const perCol = pg.PgConnection.prototype._columnFormats.call({}, 3, [0, 1]);
|
|
62
|
+
ok('#277 per-column format codes', JSON.stringify(perCol) === '[0,1,0]', perCol);
|
|
63
|
+
}
|
|
64
|
+
console.log(`\n${passed} passed, ${failed} failed`);
|
|
65
|
+
process.exit(failed === 0 ? 0 : 1);
|
|
66
|
+
})().catch((e) => { console.error('FATAL', e); process.exit(1); });
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Regression tests for #322 #323 #324 #325.
|
|
3
|
+
*/
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const ROOT = path.join(__dirname, '..');
|
|
6
|
+
const { Database, executeSQL } = require(path.join(ROOT, 'index.js'));
|
|
7
|
+
let passed = 0, failed = 0;
|
|
8
|
+
function ok(name, cond, extra) {
|
|
9
|
+
if (cond) { passed++; console.log('[OK]', name); }
|
|
10
|
+
else { failed++; console.log('[FAIL]', name, extra !== undefined ? '→ ' + JSON.stringify(extra) : ''); }
|
|
11
|
+
}
|
|
12
|
+
const q = (db, sql) => executeSQL(db, sql, { safety: false });
|
|
13
|
+
|
|
14
|
+
(async () => {
|
|
15
|
+
const db = new Database(':memory:');
|
|
16
|
+
await q(db, 'SELECT 1');
|
|
17
|
+
// #322 CASE 各子表达式支持二元表达式
|
|
18
|
+
const cases = [
|
|
19
|
+
[["SELECT CASE WHEN 1 THEN 1 + 2 END"], 3],
|
|
20
|
+
[["SELECT CASE WHEN 1 THEN 1 / 2 END"], 0.5],
|
|
21
|
+
[["SELECT CASE WHEN 0 THEN 'y' ELSE 1 + 0 END"], 1],
|
|
22
|
+
[["SELECT CASE 1 + 1 WHEN 2 THEN 'two' END"], 'two'],
|
|
23
|
+
[["SELECT CASE WHEN 1 THEN 1 = 1 END"], 1],
|
|
24
|
+
[["SELECT CASE WHEN 1 THEN 1 AND 0 END"], 0],
|
|
25
|
+
];
|
|
26
|
+
for (const [sql, expected] of cases) {
|
|
27
|
+
let got, err;
|
|
28
|
+
try { got = (await q(db, sql[0])).rows[0][0]; } catch (e) { err = e.message; }
|
|
29
|
+
ok('#322 ' + sql[0], !err && String(got) === String(expected), err || got);
|
|
30
|
+
}
|
|
31
|
+
// #323 窗口 PARTITION BY / ORDER BY 二元表达式
|
|
32
|
+
{
|
|
33
|
+
await q(db, 'CREATE TABLE w (id INT, g INT, v INT)');
|
|
34
|
+
await q(db, 'INSERT INTO w VALUES (1,1,10),(2,1,20),(3,2,30)');
|
|
35
|
+
let rows, err;
|
|
36
|
+
try {
|
|
37
|
+
rows = (await q(db, 'SELECT id, SUM(v) OVER (PARTITION BY g % 2 ORDER BY v + 0) AS s FROM w')).rows;
|
|
38
|
+
} catch (e) { err = e.message; }
|
|
39
|
+
ok('#323 window expression parses and computes', !err && rows.length === 3, err || rows);
|
|
40
|
+
}
|
|
41
|
+
// #324 YEARWEEK 默认 mode 0
|
|
42
|
+
{
|
|
43
|
+
const one = async (sql) => (await q(db, sql)).rows[0][0];
|
|
44
|
+
ok('#324 YEARWEEK default 2023-01-01', Number(await one("SELECT YEARWEEK('2023-01-01')")) === 202301, await one("SELECT YEARWEEK('2023-01-01')"));
|
|
45
|
+
ok('#324 YEARWEEK default 2026-01-01', Number(await one("SELECT YEARWEEK('2026-01-01')")) === 202600, await one("SELECT YEARWEEK('2026-01-01')"));
|
|
46
|
+
ok('#324 YEARWEEK mode 0 matches WEEK', Number(await one("SELECT YEARWEEK('2026-01-01', 0)")) === 202600, await one("SELECT YEARWEEK('2026-01-01', 0)"));
|
|
47
|
+
}
|
|
48
|
+
// #325 DECIMAL 负数半值远离零
|
|
49
|
+
{
|
|
50
|
+
const one = async (sql) => (await q(db, sql)).rows[0][0];
|
|
51
|
+
ok('#325 CAST -1.5 DECIMAL(10,0)', Number(await one('SELECT CAST(-1.5 AS DECIMAL(10,0))')) === -2, await one('SELECT CAST(-1.5 AS DECIMAL(10,0))'));
|
|
52
|
+
ok('#325 CAST -1.25 DECIMAL(10,1)', Number(await one('SELECT CAST(-1.25 AS DECIMAL(10,1))')) === -1.3, await one('SELECT CAST(-1.25 AS DECIMAL(10,1))'));
|
|
53
|
+
ok('#325 CAST -1.5 string DECIMAL(10,0)', Number(await one("SELECT CAST('-1.5' AS DECIMAL(10,0))")) === -2, await one("SELECT CAST('-1.5' AS DECIMAL(10,0))"));
|
|
54
|
+
ok('#325 positive half unchanged', Number(await one('SELECT CAST(1.25 AS DECIMAL(10,1))')) === 1.3, await one('SELECT CAST(1.25 AS DECIMAL(10,1))'));
|
|
55
|
+
}
|
|
56
|
+
db.stop();
|
|
57
|
+
console.log(`\n${passed} passed, ${failed} failed`);
|
|
58
|
+
process.exit(failed === 0 ? 0 : 1);
|
|
59
|
+
})().catch((e) => { console.error('FATAL', e); process.exit(1); });
|
package/test/issue-38.test.js
CHANGED
|
@@ -170,6 +170,7 @@ async function testPersistence() {
|
|
|
170
170
|
db.big.insert({ v: 9223372036854775807n });
|
|
171
171
|
db.big.insert({ v: -9223372036854775808n });
|
|
172
172
|
db.save();
|
|
173
|
+
await db.stop();
|
|
173
174
|
|
|
174
175
|
db = new Database(p);
|
|
175
176
|
const rows = db.big.find({}).sort((a, b) => (a.v < b.v ? -1 : 1));
|
|
@@ -187,6 +188,7 @@ async function testPersistence() {
|
|
|
187
188
|
});
|
|
188
189
|
db.big.insert({ v: '9007199254740993' });
|
|
189
190
|
db.save();
|
|
191
|
+
await db.stop();
|
|
190
192
|
|
|
191
193
|
db = new Database(p);
|
|
192
194
|
ok('#38 JSON persistence keeps >2^53 exactly', db.big.find({})[0].v === 9007199254740993n, db.big.find({}));
|
|
@@ -203,6 +205,7 @@ async function testPersistence() {
|
|
|
203
205
|
});
|
|
204
206
|
db.big.insert({ v: 9007199254740993n });
|
|
205
207
|
db.save();
|
|
208
|
+
await db.stop();
|
|
206
209
|
|
|
207
210
|
db = new Database(dir, { mode: 'disk' });
|
|
208
211
|
ok('#38 dir-mode persistence keeps >2^53 exactly', db.big.find({})[0].v === 9007199254740993n, db.big.find({}));
|
|
@@ -44,7 +44,7 @@ const SCHEMA = { id: { type: 'integer', primaryKey: true }, v: { type: 'string'
|
|
|
44
44
|
await db.insert('t', { id: 3, v: 'third' });
|
|
45
45
|
await db.removeById('t', 3);
|
|
46
46
|
// 模拟 kill -9:直接丢弃,不 save 不 stop
|
|
47
|
-
const db2 = new Database(file, { wal: true });
|
|
47
|
+
const db2 = new Database(file, { wal: true, fileLock: false });
|
|
48
48
|
const rows = await db2.find('t', {});
|
|
49
49
|
ok('崩溃后表仍存在', Object.keys(db2._tables).includes('t'));
|
|
50
50
|
ok('崩溃后行数正确 (2)', rows.length === 2, rows.length);
|
|
@@ -65,7 +65,7 @@ const SCHEMA = { id: { type: 'integer', primaryKey: true }, v: { type: 'string'
|
|
|
65
65
|
db.save(); // 快照:2 行,WAL 应清空
|
|
66
66
|
ok('save 后 WAL 被清空', !fs.existsSync(file + '.wal'));
|
|
67
67
|
await db.insert('t', { id: 3, v: 'c-after-save' }); // 只进 WAL
|
|
68
|
-
const db2 = new Database(file, { wal: true });
|
|
68
|
+
const db2 = new Database(file, { wal: true, fileLock: false });
|
|
69
69
|
const rows = await db2.find('t', {});
|
|
70
70
|
ok('快照 2 行 + WAL 1 行 = 3 行', rows.length === 3, rows.length);
|
|
71
71
|
ok('WAL 中的新行已恢复', rows.find(r => r.id === 3)?.v === 'c-after-save');
|
|
@@ -79,9 +79,9 @@ const SCHEMA = { id: { type: 'integer', primaryKey: true }, v: { type: 'string'
|
|
|
79
79
|
await db.createTable('t', SCHEMA);
|
|
80
80
|
await db.insert('t', { id: 1, v: 'x' });
|
|
81
81
|
await db.insert('t', { id: 2, v: 'y' });
|
|
82
|
-
const db2 = new Database(file, { wal: true });
|
|
82
|
+
const db2 = new Database(file, { wal: true, fileLock: false });
|
|
83
83
|
const r2 = await db2.find('t', {});
|
|
84
|
-
const db3 = new Database(file, { wal: true });
|
|
84
|
+
const db3 = new Database(file, { wal: true, fileLock: false });
|
|
85
85
|
const r3 = await db3.find('t', {});
|
|
86
86
|
ok('首次恢复 2 行', r2.length === 2, r2.length);
|
|
87
87
|
ok('二次重开仍 2 行(不重复回放)', r3.length === 2, r3.length);
|
|
@@ -96,7 +96,7 @@ const SCHEMA = { id: { type: 'integer', primaryKey: true }, v: { type: 'string'
|
|
|
96
96
|
await db.insert('t', { id: 1, v: 'ok' });
|
|
97
97
|
// 模拟崩溃时最后一行只写了一半
|
|
98
98
|
fs.appendFileSync(file + '.wal', '{"op":"insert","table":"t","ro');
|
|
99
|
-
const db2 = new Database(file, { wal: true });
|
|
99
|
+
const db2 = new Database(file, { wal: true, fileLock: false });
|
|
100
100
|
const rows = await db2.find('t', {});
|
|
101
101
|
ok('半截尾行被丢弃,完整记录仍恢复', rows.length === 1, rows.length);
|
|
102
102
|
ok('数据内容正确', rows[0] && rows[0].v === 'ok', rows);
|
|
@@ -112,7 +112,7 @@ const SCHEMA = { id: { type: 'integer', primaryKey: true }, v: { type: 'string'
|
|
|
112
112
|
await db.insert('t', { id: 1, v: 'a' });
|
|
113
113
|
await db.insert('u', { id: 1, v: 'b' });
|
|
114
114
|
await db.dropTable('u');
|
|
115
|
-
const db2 = new Database(file, { wal: true });
|
|
115
|
+
const db2 = new Database(file, { wal: true, fileLock: false });
|
|
116
116
|
ok('被 drop 的表未复活', !db2._tables.u, Object.keys(db2._tables));
|
|
117
117
|
ok('保留的表数据完整', (await db2.find('t', {})).length === 1);
|
|
118
118
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
@@ -135,7 +135,7 @@ const SCHEMA = { id: { type: 'integer', primaryKey: true }, v: { type: 'string'
|
|
|
135
135
|
fs.writeFileSync(file + '.wal', JSON.stringify([
|
|
136
136
|
{ op: 'createTable', table: 'legacy', schema: SCHEMA },
|
|
137
137
|
]));
|
|
138
|
-
const db = new Database(file, { wal: true });
|
|
138
|
+
const db = new Database(file, { wal: true, fileLock: false });
|
|
139
139
|
ok('旧格式数组 WAL 能被回放', !!db._tables.legacy, Object.keys(db._tables));
|
|
140
140
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
141
141
|
}
|
|
@@ -148,7 +148,7 @@ const SCHEMA = { id: { type: 'integer', primaryKey: true }, v: { type: 'string'
|
|
|
148
148
|
db.createTable && 0;
|
|
149
149
|
for (let i = 1; i <= 30; i++) await db.insert('t', { id: i, v: 'v' + i, n: i });
|
|
150
150
|
db._tables.t.createIndex('n');
|
|
151
|
-
const db2 = new Database(file, { wal: true });
|
|
151
|
+
const db2 = new Database(file, { wal: true, fileLock: false });
|
|
152
152
|
const found = await db2.find('t', { n: 17 });
|
|
153
153
|
ok('回放后按索引字段查询正确', found.length === 1 && found[0].id === 17, found);
|
|
154
154
|
const cnt = await db2.find('t', { n: { $gte: 25 } });
|
|
@@ -170,7 +170,7 @@ const SCHEMA = { id: { type: 'integer', primaryKey: true }, v: { type: 'string'
|
|
|
170
170
|
await db.delete('np', { x: 'n1' });
|
|
171
171
|
ok('写入后立即产生 .wal', fs.existsSync(file + '.wal'));
|
|
172
172
|
|
|
173
|
-
const db2 = new Database(file); // 不传 wal,模拟进程崩溃后重启
|
|
173
|
+
const db2 = new Database(file, { fileLock: false }); // 不传 wal,模拟进程崩溃后重启
|
|
174
174
|
const rows = await db2.find('t', {});
|
|
175
175
|
const npRows = await db2.find('np', {});
|
|
176
176
|
ok('默认 WAL 恢复主键表', rows.length === 1 && rows[0].v === 'a2', rows);
|