jsql-neo 6.8.27 → 6.10.2
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 +9 -4
- package/bin/jsql-server-control.js +58 -14
- package/index.d.ts +3 -0
- package/index.js +1 -1
- package/lib/bigint_json.js +13 -1
- package/lib/btree.js +12 -3
- package/lib/cache.js +12 -1
- package/lib/database.js +272 -36
- package/lib/jsql_format.js +22 -9
- package/lib/migrate.js +184 -98
- package/lib/mod.js +48 -13
- package/lib/mongo_server.js +652 -246
- package/lib/mysql_compat.js +54 -11
- package/lib/mysql_server.js +248 -65
- package/lib/nedb_compat.js +7 -1
- package/lib/objectid.js +14 -6
- package/lib/pg_server.js +385 -9
- package/lib/plugin.js +34 -3
- package/lib/query.js +12 -6
- package/lib/redis_server.js +102 -42
- package/lib/sql.js +446 -48
- package/lib/table.js +111 -41
- package/lib/tui.js +28 -9
- package/lib/web_ui.js +33 -2
- package/package.json +4 -4
- package/test/alter-table.test.js +11 -5
- package/test/compat-v1.test.js +1 -1
- package/test/extra-coverage.test.js +6 -7
- package/test/issue-258-300.test.js +6 -0
- package/test/issue-312-320.test.js +11 -4
- package/test/issue-326.test.js +42 -0
- package/test/issue-327-418.test.js +1 -1
- package/test/issue-336.test.js +56 -0
- package/test/issue-353.test.js +34 -0
- package/test/issue-356.test.js +27 -0
- package/test/issue-357-365.test.js +1 -1
- package/test/issue-361.test.js +55 -0
- package/test/issue-370.test.js +43 -0
- package/test/issue-373.test.js +40 -0
- package/test/issue-374.test.js +62 -0
- package/test/issue-378.test.js +39 -0
- package/test/issue-379.test.js +39 -0
- package/test/issue-38.test.js +2 -2
- package/test/issue-380.test.js +27 -0
- package/test/issue-383-402.test.js +4 -3
- package/test/issue-384.test.js +41 -0
- package/test/issue-392.test.js +25 -0
- package/test/issue-397.test.js +44 -0
- package/test/issue-403.test.js +47 -0
- package/test/issue-404.test.js +58 -0
- package/test/issue-407.test.js +40 -0
- package/test/issue-408.test.js +92 -0
- package/test/issue-409.test.js +32 -0
- package/test/issue-410.test.js +36 -0
- package/test/issue-411.test.js +38 -0
- package/test/issue-412.test.js +50 -0
- package/test/issue-414.test.js +46 -0
- package/test/issue-417.test.js +56 -0
- package/test/issue-420.test.js +87 -0
- package/test/issue-421.test.js +30 -0
- package/test/issue-422.test.js +33 -0
- package/test/issue-424.test.js +44 -0
- package/test/issue-425.test.js +22 -0
- package/test/issue-426.test.js +22 -0
- package/test/issue-427.test.js +36 -0
- package/test/issue-429.test.js +38 -0
- package/test/issue-431.test.js +41 -0
- package/test/issue-432.test.js +37 -0
- package/test/issue-436.test.js +47 -0
- package/test/issue-445-449.test.js +14 -7
- package/test/issue-455-459.test.js +6 -3
- package/test/issue-474.test.js +59 -0
- package/test/issue-475.test.js +38 -0
- package/test/issue-476.test.js +50 -0
- package/test/issue-477.test.js +54 -0
- package/test/issue-478.test.js +52 -0
- package/test/issue-479.test.js +44 -0
- package/test/issue-480.test.js +42 -0
- package/test/issue-481.test.js +51 -0
- package/test/issue-482.test.js +36 -0
- package/test/issue-483.test.js +57 -0
- package/test/issue-485.test.js +47 -0
- package/test/issue-486.test.js +69 -0
- package/test/issue-487.test.js +54 -0
- package/test/issue-488.test.js +69 -0
- package/test/issue-490.test.js +20 -0
- package/test/issue-491.test.js +21 -0
- package/test/issue-492.test.js +19 -0
- package/test/issue-493.test.js +30 -0
- package/test/issue-494.test.js +82 -0
- package/test/issue-495.test.js +86 -0
- package/test/issue-496.test.js +98 -0
- package/test/issue-497.test.js +29 -0
- package/test/issue-498.test.js +32 -0
- package/test/issue-499.test.js +41 -0
- package/test/issue-500.test.js +39 -0
- package/test/issue-501-506.test.js +29 -0
- package/test/issue-502.test.js +18 -0
- package/test/issue-503.test.js +43 -0
- package/test/issue-504.test.js +83 -0
- package/test/issue-505.test.js +29 -0
- package/test/issue-529.test.js +39 -0
- package/test/issue-530.test.js +69 -0
- package/test/issue-536.test.js +46 -0
- package/test/issue-537.test.js +52 -0
- package/test/issue-539.test.js +65 -0
- package/test/issue-540.test.js +31 -0
- package/test/issue-545.test.js +38 -0
- package/test/issue-546.test.js +68 -0
- package/test/issue-547.test.js +27 -0
- package/test/issue-548.test.js +68 -0
- package/test/issue-549.test.js +26 -0
- package/test/issue-550.test.js +52 -0
- package/test/issue-551.test.js +34 -0
- package/test/issue-552.test.js +30 -0
- package/test/issue-553.test.js +29 -0
- package/test/issue-554.test.js +29 -0
- package/test/issue-555.test.js +22 -0
- package/test/issue-556.test.js +25 -0
- package/test/issue-565.test.js +32 -0
- package/test/issue-566.test.js +30 -0
- package/test/issue-567.test.js +56 -0
- package/test/issue-568.test.js +46 -0
- package/test/issue-569.test.js +25 -0
- package/test/issue-570.test.js +30 -0
- package/test/issue-571.test.js +32 -0
- package/test/issue-572.test.js +64 -0
- package/test/issue-573.test.js +71 -0
- package/test/issue-574.test.js +63 -0
- package/test/issue-581.test.js +46 -0
- package/test/issue-59.test.js +17 -4
- package/test/issue-69-70.test.js +1 -1
- package/test/issue-mysql-harness.js +260 -0
- package/test/issue-pg5-helper.js +135 -0
- package/test/mongo-arrays.test.js +63 -0
- package/test/mongo-objectid.test.js +2 -2
- package/test/mongo-persistence.test.js +3 -3
- package/test/mongo-update-dates.test.js +128 -0
- package/test/wal-recovery.test.js +17 -9
package/lib/pg_server.js
CHANGED
|
@@ -83,6 +83,7 @@ function pgTypeLen(sqlType) {
|
|
|
83
83
|
if (t === 'bigint' || t === 'int8' || t === 'bigserial') return 8;
|
|
84
84
|
if (t === 'real' || t === 'float4') return 4;
|
|
85
85
|
if (t === 'double' || t === 'double precision' || t === 'float' || t === 'float8' || t === 'number') return 8;
|
|
86
|
+
// 保持 #371 既有的 typlen 口径(timestamptz/uuid 等仍通告 -1)
|
|
86
87
|
return -1;
|
|
87
88
|
}
|
|
88
89
|
|
|
@@ -127,6 +128,33 @@ function pgFormatValue(value, sqlType) {
|
|
|
127
128
|
return String(value);
|
|
128
129
|
}
|
|
129
130
|
|
|
131
|
+
// #378/#353/#370:解析层不认识的命令由服务端自己处理,Parse 校验时放行
|
|
132
|
+
function isPgSpecialCommand(sql) {
|
|
133
|
+
return /^\s*(LISTEN|UNLISTEN|NOTIFY|COPY)\b/i.test(String(sql || ''));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// #380:按顶层分号切分语句(跳过字符串/注释里的分号),用于判定是否需要隐式事务
|
|
137
|
+
function pgSplitStatements(sql) {
|
|
138
|
+
const parts = []; let cur = '';
|
|
139
|
+
let inSingle = false, inDouble = false, inLine = false, inBlock = false;
|
|
140
|
+
const s = String(sql || '');
|
|
141
|
+
for (let i = 0; i < s.length; i++) {
|
|
142
|
+
const c = s[i], n = s[i + 1];
|
|
143
|
+
if (inLine) { cur += c; if (c === '\n') inLine = false; continue; }
|
|
144
|
+
if (inBlock) { cur += c; if (c === '*' && n === '/') { cur += n; i++; inBlock = false; } continue; }
|
|
145
|
+
if (inSingle) { cur += c; if (c === "'") { if (n === "'") { cur += n; i++; } else inSingle = false; } continue; }
|
|
146
|
+
if (inDouble) { cur += c; if (c === '"') { if (n === '"') { cur += n; i++; } else inDouble = false; } continue; }
|
|
147
|
+
if (c === '-' && n === '-') { cur += '-'; cur += '-'; i++; inLine = true; continue; }
|
|
148
|
+
if (c === '/' && n === '*') { cur += '/'; cur += '*'; i++; inBlock = true; continue; }
|
|
149
|
+
if (c === "'") { inSingle = true; cur += c; continue; }
|
|
150
|
+
if (c === '"') { inDouble = true; cur += c; continue; }
|
|
151
|
+
if (c === ';') { parts.push(cur); cur = ''; continue; }
|
|
152
|
+
cur += c;
|
|
153
|
+
}
|
|
154
|
+
parts.push(cur);
|
|
155
|
+
return parts.map((p) => p.trim()).filter(Boolean);
|
|
156
|
+
}
|
|
157
|
+
|
|
130
158
|
// ---------------------------------------------------------------------------
|
|
131
159
|
// Message writer
|
|
132
160
|
// ---------------------------------------------------------------------------
|
|
@@ -165,19 +193,98 @@ function frame(type, payload) {
|
|
|
165
193
|
return Buffer.concat([head, payload]);
|
|
166
194
|
}
|
|
167
195
|
|
|
168
|
-
// #
|
|
196
|
+
// #374:PG 二进制 numeric — int16 ndigits/weight/sign/dscale + base-10000 数字数组
|
|
197
|
+
function pgEncodeNumericBinary(value) {
|
|
198
|
+
let s = String(value == null ? '' : value).trim();
|
|
199
|
+
if (!/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(s)) {
|
|
200
|
+
const b = Buffer.alloc(8); b.writeDoubleBE(Number(value) || 0, 0); return b;
|
|
201
|
+
}
|
|
202
|
+
let sign = 0;
|
|
203
|
+
if (s[0] === '-') { sign = 0x4000; s = s.slice(1); }
|
|
204
|
+
else if (s[0] === '+') s = s.slice(1);
|
|
205
|
+
let exp = 0;
|
|
206
|
+
const em = /[eE][+-]?\d+$/.exec(s);
|
|
207
|
+
if (em) { exp = Number(s.slice(em.index + 1)); s = s.slice(0, em.index); }
|
|
208
|
+
let [intPart, fracPart = ''] = s.split('.');
|
|
209
|
+
if (exp > 0) intPart += '0'.repeat(exp);
|
|
210
|
+
else if (exp < 0) {
|
|
211
|
+
const digits = intPart + fracPart, cut = -exp;
|
|
212
|
+
if (cut >= digits.length) { intPart = '0'; fracPart = '0'.repeat(cut - digits.length) + digits; }
|
|
213
|
+
else { const pos = digits.length - cut; intPart = digits.slice(0, pos); fracPart = digits.slice(pos); }
|
|
214
|
+
}
|
|
215
|
+
const dscale = fracPart.length;
|
|
216
|
+
const intPad = (4 - (intPart.length % 4)) % 4;
|
|
217
|
+
const fracPad = (4 - (fracPart.length % 4)) % 4;
|
|
218
|
+
const all = '0'.repeat(intPad) + intPart + fracPart + '0'.repeat(fracPad);
|
|
219
|
+
const groups = [];
|
|
220
|
+
for (let i = 0; i < all.length; i += 4) groups.push(Number(all.slice(i, i + 4)));
|
|
221
|
+
let weight = (intPart.length + intPad) / 4 - 1;
|
|
222
|
+
while (groups.length > 1 && groups[0] === 0) { groups.shift(); weight--; }
|
|
223
|
+
while (groups.length > 1 && groups[groups.length - 1] === 0) groups.pop();
|
|
224
|
+
if (groups.length === 1 && groups[0] === 0) { groups.length = 0; weight = 0; }
|
|
225
|
+
const p = new PgBuffer();
|
|
226
|
+
p.i16(groups.length); p.i16(weight); p.i16(sign); p.i16(dscale);
|
|
227
|
+
for (const g of groups) p.i16(g);
|
|
228
|
+
return p.build();
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function pgDateMillis(value) {
|
|
232
|
+
if (value instanceof Date) return Date.UTC(value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate());
|
|
233
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(value));
|
|
234
|
+
if (m) return Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
|
|
235
|
+
const ms = Date.parse(String(value));
|
|
236
|
+
return isNaN(ms) ? 0 : ms;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function pgTimestampMillis(value) {
|
|
240
|
+
if (typeof value === 'number') return value < 1e12 ? value * 1000 : value; // #215 引擎存 Unix 秒
|
|
241
|
+
if (value instanceof Date) return value.getTime();
|
|
242
|
+
let s = String(value).trim().replace(' ', 'T');
|
|
243
|
+
if (!/[zZ+-]\d{2}:?\d{2}$/.test(s)) s += 'Z';
|
|
244
|
+
const ms = Date.parse(s);
|
|
245
|
+
return isNaN(ms) ? 0 : ms;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// #277/#374:按列的结果格式码编码二进制 DataRow
|
|
169
249
|
function pgEncodeBinary(value, type) {
|
|
170
250
|
const t = String(type || '').toLowerCase();
|
|
251
|
+
if (value === null || value === undefined) return Buffer.alloc(0);
|
|
171
252
|
if (t === 'boolean' || t === 'bool') return Buffer.from([value ? 1 : 0]);
|
|
253
|
+
if (t === 'smallint' || t === 'int2') {
|
|
254
|
+
const b = Buffer.alloc(2); b.writeInt16BE(Number(value) | 0, 0); return b;
|
|
255
|
+
}
|
|
172
256
|
if (t === 'integer' || t === 'int' || t === 'int4' || t === 'serial') {
|
|
173
257
|
const b = Buffer.alloc(4); b.writeInt32BE(Number(value) | 0, 0); return b;
|
|
174
258
|
}
|
|
175
259
|
if (t === 'bigint' || t === 'int8' || t === 'bigserial') {
|
|
176
260
|
const b = Buffer.alloc(8); b.writeBigInt64BE(BigInt(value), 0); return b;
|
|
177
261
|
}
|
|
178
|
-
if (t === 'numeric' || t === 'decimal'
|
|
262
|
+
if (t === 'numeric' || t === 'decimal') return pgEncodeNumericBinary(value);
|
|
263
|
+
if (t === 'real' || t === 'float4') {
|
|
264
|
+
const b = Buffer.alloc(4); b.writeFloatBE(Number(value), 0); return b;
|
|
265
|
+
}
|
|
266
|
+
if (t === 'number' || t === 'float' || t === 'float8') {
|
|
179
267
|
const b = Buffer.alloc(8); b.writeDoubleBE(Number(value), 0); return b;
|
|
180
268
|
}
|
|
269
|
+
if (t === 'date') {
|
|
270
|
+
const b = Buffer.alloc(4);
|
|
271
|
+
b.writeInt32BE(Math.floor((pgDateMillis(value) - Date.UTC(2000, 0, 1)) / 86400000), 0);
|
|
272
|
+
return b;
|
|
273
|
+
}
|
|
274
|
+
if (t === 'timestamp' || t === 'timestamptz' || t === 'datetime') {
|
|
275
|
+
const b = Buffer.alloc(8);
|
|
276
|
+
b.writeBigInt64BE(BigInt((pgTimestampMillis(value) - Date.UTC(2000, 0, 1)) * 1000), 0);
|
|
277
|
+
return b;
|
|
278
|
+
}
|
|
279
|
+
if (t === 'uuid') return Buffer.from(String(value).replace(/-/g, ''), 'hex');
|
|
280
|
+
if (t === 'bytea') {
|
|
281
|
+
if (Buffer.isBuffer(value)) return value;
|
|
282
|
+
const s = String(value);
|
|
283
|
+
// 引擎可能吃掉 SQL 字面量里的反斜杠,兼容 `\x...` 与 `x...` 两种十六进制文本输出
|
|
284
|
+
const hm = /^(?:\\x|x)([0-9a-fA-F]+)$/.exec(s);
|
|
285
|
+
if (hm && hm[1].length % 2 === 0) return Buffer.from(hm[1], 'hex');
|
|
286
|
+
return Buffer.from(s, 'utf8');
|
|
287
|
+
}
|
|
181
288
|
return Buffer.from(pgFormatValue(value, type) === null ? '' : String(pgFormatValue(value, type)), 'utf8');
|
|
182
289
|
}
|
|
183
290
|
|
|
@@ -223,6 +330,29 @@ function buildCommandComplete(tag) {
|
|
|
223
330
|
return frame(0x43, p.build()); // 'C'
|
|
224
331
|
}
|
|
225
332
|
|
|
333
|
+
// #370:COPY 子协议帧
|
|
334
|
+
function buildCopyOutResponse(columns) {
|
|
335
|
+
const p = new PgBuffer();
|
|
336
|
+
p.c(0); p.i16(columns); // 整体 text 格式
|
|
337
|
+
for (let i = 0; i < columns; i++) p.i16(0); // 每列 text 格式
|
|
338
|
+
return frame(0x48, p.build()); // 'H'
|
|
339
|
+
}
|
|
340
|
+
function buildCopyInResponse(columns) {
|
|
341
|
+
const p = new PgBuffer();
|
|
342
|
+
p.c(0); p.i16(columns);
|
|
343
|
+
for (let i = 0; i < columns; i++) p.i16(0);
|
|
344
|
+
return frame(0x47, p.build()); // 'G'
|
|
345
|
+
}
|
|
346
|
+
function buildCopyData(buf) { return frame(0x64, buf); } // 'd'
|
|
347
|
+
function buildCopyDone() { return frame(0x63, Buffer.alloc(0)); } // 'c'
|
|
348
|
+
|
|
349
|
+
// #353:后端主动推送的异步通知帧
|
|
350
|
+
function buildNotification(pid, channel, payload) {
|
|
351
|
+
const p = new PgBuffer();
|
|
352
|
+
p.i32(pid); p.str(channel).nul(); p.str(payload || '').nul();
|
|
353
|
+
return frame(0x41, p.build()); // 'A'
|
|
354
|
+
}
|
|
355
|
+
|
|
226
356
|
function buildEmptyQuery() {
|
|
227
357
|
return frame(0x49, Buffer.alloc(0)); // 'I'
|
|
228
358
|
}
|
|
@@ -356,6 +486,8 @@ class PgConnection {
|
|
|
356
486
|
this.server = server;
|
|
357
487
|
this.buffer = Buffer.alloc(0);
|
|
358
488
|
this._extendedBatch = false; // #381
|
|
489
|
+
this._skipUntilSync = false; // #552:批次出错后丢弃消息直到 Sync
|
|
490
|
+
this._copyIn = null; // #370:COPY FROM STDIN 状态
|
|
359
491
|
this.authenticated = false;
|
|
360
492
|
this.user = null;
|
|
361
493
|
this.database = null;
|
|
@@ -377,6 +509,7 @@ class PgConnection {
|
|
|
377
509
|
this._scramCred = null;
|
|
378
510
|
this._prepared = new Map(); // name -> { sql, paramTypes }
|
|
379
511
|
this._portal = new Map(); // name -> { values }
|
|
512
|
+
this._listenChannels = new Set(); // #353:本连接订阅的频道
|
|
380
513
|
this._inTransaction = false;
|
|
381
514
|
this._txAborted = false;
|
|
382
515
|
this._txId = null;
|
|
@@ -393,6 +526,15 @@ class PgConnection {
|
|
|
393
526
|
|
|
394
527
|
_onClose() {
|
|
395
528
|
this.server._sockets.delete(this.socket);
|
|
529
|
+
if (this._pid && this._secret) {
|
|
530
|
+
this.server._backends.delete(this._pid + ':' + this._secret); // #379
|
|
531
|
+
}
|
|
532
|
+
if (this._listenChannels) { // #353
|
|
533
|
+
for (const ch of this._listenChannels) {
|
|
534
|
+
const set = this.server._channels.get(ch);
|
|
535
|
+
if (set) { set.delete(this); if (set.size === 0) this.server._channels.delete(ch); }
|
|
536
|
+
}
|
|
537
|
+
}
|
|
396
538
|
}
|
|
397
539
|
|
|
398
540
|
_send(buf) {
|
|
@@ -447,6 +589,15 @@ class PgConnection {
|
|
|
447
589
|
}
|
|
448
590
|
this._pending = (this._pending || Promise.resolve()).then(async () => {
|
|
449
591
|
try {
|
|
592
|
+
// #552:批次内任一消息出错后,丢弃剩余消息直到 Sync,只允许一个 ErrorResponse
|
|
593
|
+
if (this._skipUntilSync) {
|
|
594
|
+
if (type === 0x53) { // 'S' Sync:结束丢弃状态并回 ReadyForQuery
|
|
595
|
+
this._skipUntilSync = false;
|
|
596
|
+
this._extendedBatch = false;
|
|
597
|
+
this._send(buildReadyForQuery(this._rfqStatus()));
|
|
598
|
+
}
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
450
601
|
if (type === 0x51) { // 'Q' simple query(async)
|
|
451
602
|
await this._handleSimpleQuery(body.toString('utf8').replace(/\0$/, ''));
|
|
452
603
|
} else {
|
|
@@ -462,6 +613,7 @@ class PgConnection {
|
|
|
462
613
|
detail: e && e.detail, hint: e && e.hint }));
|
|
463
614
|
// #381:扩展协议错误不能在 Sync 之前发 ReadyForQuery,否则 Sync 再发一帧 → 双 Z
|
|
464
615
|
if (!this._extendedBatch) this._send(buildReadyForQuery(this._rfqStatus()));
|
|
616
|
+
else this._skipUntilSync = true; // #552:等待 Sync,期间所有消息丢弃
|
|
465
617
|
}
|
|
466
618
|
});
|
|
467
619
|
}
|
|
@@ -475,8 +627,17 @@ class PgConnection {
|
|
|
475
627
|
|
|
476
628
|
_handleStartup(body) {
|
|
477
629
|
const version = body.readInt32BE(4);
|
|
478
|
-
// #
|
|
479
|
-
if (version === 80877102) {
|
|
630
|
+
// #379:CancelRequest 在新建连接上发送,载荷 pid+secret 必须匹配活动后端
|
|
631
|
+
if (version === 80877102) {
|
|
632
|
+
if (body.length >= 16) {
|
|
633
|
+
const pid = body.readInt32BE(8);
|
|
634
|
+
const secret = body.readInt32BE(12);
|
|
635
|
+
const target = this.server._backends.get(pid + ':' + secret);
|
|
636
|
+
if (target) target._cancelRequested = true; // 只给匹配后端打取消标记
|
|
637
|
+
}
|
|
638
|
+
this.socket.end(); // 取消连接本身不回任何帧
|
|
639
|
+
return;
|
|
640
|
+
}
|
|
480
641
|
if (version === 80877103) {
|
|
481
642
|
// SSLRequest: 拒绝后客户端重发 startup
|
|
482
643
|
this._send(Buffer.from([0x4e]));
|
|
@@ -527,6 +688,24 @@ class PgConnection {
|
|
|
527
688
|
this._completeAuth();
|
|
528
689
|
return;
|
|
529
690
|
}
|
|
691
|
+
// #336:默认 SCRAM,文档承诺的明文/MD5 通过 authMethod 显式启用
|
|
692
|
+
const entry = this.server.auth && this.server.auth[this.user];
|
|
693
|
+
const method = String((entry && typeof entry === 'object' && entry.authMethod)
|
|
694
|
+
|| this.server.options.authMethod || 'scram').toLowerCase();
|
|
695
|
+
if (method === 'cleartext' || method === 'password') {
|
|
696
|
+
this._authMethod = 'cleartext';
|
|
697
|
+
const p = new PgBuffer(); p.i32(AUTH_CLEARTEXT);
|
|
698
|
+
this._send(frame(0x52, p.build())); // 'R' AuthenticationCleartextPassword
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
if (method === 'md5') {
|
|
702
|
+
this._authMethod = 'md5';
|
|
703
|
+
this._md5Salt = crypto.randomBytes(4);
|
|
704
|
+
const p = new PgBuffer(); p.i32(AUTH_MD5); p.raw(this._md5Salt);
|
|
705
|
+
this._send(frame(0x52, p.build())); // 'R' AuthenticationMD5Password + salt
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
this._authMethod = 'scram';
|
|
530
709
|
// SCRAM-SHA-256(PG 13+ 默认)
|
|
531
710
|
this._scramCred = scramPrepare(password);
|
|
532
711
|
// AuthenticationSASL (code 10): int32 code + mechanism list (each nul-terminated) + extra nul
|
|
@@ -539,6 +718,20 @@ class PgConnection {
|
|
|
539
718
|
}
|
|
540
719
|
|
|
541
720
|
_handleAuthMessage(body) {
|
|
721
|
+
const expected = this.server._userPassword(this.user);
|
|
722
|
+
if (this._authMethod === 'cleartext') {
|
|
723
|
+
const received = body.toString('utf8').replace(/\0+$/, '');
|
|
724
|
+
if (received === expected) this._completeAuth();
|
|
725
|
+
else { this._send(buildErrorResponse('28P01', 'password authentication failed for user "' + this.user + '"')); this.socket.end(); }
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
if (this._authMethod === 'md5') {
|
|
729
|
+
const inner = crypto.createHash('md5').update(Buffer.concat([Buffer.from(String(expected)), this._md5Salt])).digest('hex');
|
|
730
|
+
const want = 'md5' + crypto.createHash('md5').update(inner + this._md5Salt.toString('hex'), 'utf8').digest('hex');
|
|
731
|
+
if (body.toString('utf8').replace(/\0+$/, '') === want) this._completeAuth();
|
|
732
|
+
else { this._send(buildErrorResponse('28P01', 'password authentication failed for user "' + this.user + '"')); this.socket.end(); }
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
542
735
|
if (this._scramStage === 'first') {
|
|
543
736
|
// SASLInitialResponse: mechanism(nul) + int32 dataLen + client-first
|
|
544
737
|
const mechEnd = body.indexOf(0);
|
|
@@ -598,6 +791,8 @@ class PgConnection {
|
|
|
598
791
|
this._send(buildParameterStatus('application_name', this._guc.application_name || ''));
|
|
599
792
|
this._send(buildParameterStatus('search_path', this._guc.search_path || 'public'));
|
|
600
793
|
this._send(buildBackendKeyData(this._pid, this._secret));
|
|
794
|
+
// #379:下发 BackendKeyData 时登记 pid/secret → 连接,供 CancelRequest 校验
|
|
795
|
+
this.server._backends.set(this._pid + ':' + this._secret, this);
|
|
601
796
|
this._send(buildReadyForQuery('I'));
|
|
602
797
|
}
|
|
603
798
|
|
|
@@ -615,6 +810,17 @@ class PgConnection {
|
|
|
615
810
|
const paramTypes = [];
|
|
616
811
|
let off = this._cstringLen(body, 0) + this._cstringLen(body, this._cstringLen(body, 0)) + 2;
|
|
617
812
|
for (let i = 0; i < nParams; i++) { paramTypes.push(body.readInt32BE(off)); off += 4; }
|
|
813
|
+
// #378:Parse 阶段做语法校验,非法 SQL 回 ErrorResponse 且不写入 _prepared
|
|
814
|
+
if (!isPgSpecialCommand(sql)) {
|
|
815
|
+
try {
|
|
816
|
+
this.server._parseForDescribe(sql, this.database);
|
|
817
|
+
} catch (e) {
|
|
818
|
+
const m = String((e && e.message) || '');
|
|
819
|
+
const pm = /at position (\d+)/.exec(m);
|
|
820
|
+
this._send(buildErrorResponse(this._pgErrorCode(e), m, 'ERROR', { position: pm ? Number(pm[1]) : undefined }));
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
618
824
|
this._prepared.set(name, { sql, paramTypes });
|
|
619
825
|
this._send(buildParseComplete());
|
|
620
826
|
break;
|
|
@@ -683,6 +889,15 @@ class PgConnection {
|
|
|
683
889
|
this._extendedBatch = false;
|
|
684
890
|
this._send(buildReadyForQuery(this._rfqStatus()));
|
|
685
891
|
break;
|
|
892
|
+
case 0x64: // 'd' CopyData(#370)
|
|
893
|
+
if (this._copyIn) this._copyIn.chunks.push(Buffer.from(body));
|
|
894
|
+
break;
|
|
895
|
+
case 0x63: // 'c' CopyDone(#370)
|
|
896
|
+
if (this._copyIn) await this._finishCopyIn(false);
|
|
897
|
+
break;
|
|
898
|
+
case 0x66: // 'f' CopyFail(#370)
|
|
899
|
+
if (this._copyIn) await this._finishCopyIn(true);
|
|
900
|
+
break;
|
|
686
901
|
case 0x46: // 'F' function call
|
|
687
902
|
this._send(buildErrorResponse('0A000', 'function call not supported'));
|
|
688
903
|
break;
|
|
@@ -750,8 +965,15 @@ class PgConnection {
|
|
|
750
965
|
const kind = body[0];
|
|
751
966
|
// #254:与 _handleDescribe 同样的 off-by-one(名称少读 1 字节)
|
|
752
967
|
const name = body.toString('utf8', 1, this._cstringLen(body, 1));
|
|
753
|
-
if (kind === 0x53)
|
|
754
|
-
|
|
968
|
+
if (kind === 0x53) { // 'S' 关闭预处理语句:级联关闭绑定到它的 portal(#493)
|
|
969
|
+
const stmt = this._prepared.get(name);
|
|
970
|
+
this._prepared.delete(name);
|
|
971
|
+
if (stmt) {
|
|
972
|
+
for (const [portalName, portal] of this._portal) {
|
|
973
|
+
if (portal.stmt === stmt) this._portal.delete(portalName);
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
} else if (kind === 0x50) this._portal.delete(name);
|
|
755
977
|
this._send(buildCloseComplete());
|
|
756
978
|
}
|
|
757
979
|
|
|
@@ -800,6 +1022,101 @@ class PgConnection {
|
|
|
800
1022
|
return 'string';
|
|
801
1023
|
}
|
|
802
1024
|
|
|
1025
|
+
// #370:服务器端 COPY TO STDOUT,发 H + d* + c + CommandComplete
|
|
1026
|
+
async _handleCopyOut(table) {
|
|
1027
|
+
const engine = await this._getEngine();
|
|
1028
|
+
const res = await executeSQL(engine, `SELECT * FROM ${table}`, {
|
|
1029
|
+
dialect: 'pg', safety: false, session: { currentDb: this.database, connectionId: this._pid }
|
|
1030
|
+
});
|
|
1031
|
+
const r = (Array.isArray(res) ? res : [res])[0] || {};
|
|
1032
|
+
const cols = r.columns || [];
|
|
1033
|
+
this._send(buildCopyOutResponse(cols.length));
|
|
1034
|
+
for (const row of r.rows || []) {
|
|
1035
|
+
const line = row.map((v) => v === null || v === undefined ? '\\N'
|
|
1036
|
+
: String(v).replace(/\\/g, '\\\\').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r')).join('\t') + '\n';
|
|
1037
|
+
this._send(buildCopyData(Buffer.from(line, 'utf8')));
|
|
1038
|
+
}
|
|
1039
|
+
this._send(buildCopyDone());
|
|
1040
|
+
this._send(buildCommandComplete(`COPY ${(r.rows || []).length}`));
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
// #370:COPY FROM STDIN 进入 Copy 状态,先回 G,等 CopyData/CopyDone
|
|
1044
|
+
_startCopyIn(table) {
|
|
1045
|
+
this._copyIn = { table, chunks: [] };
|
|
1046
|
+
const schema = this.server._tableSchema(this.database, String(table).replace(/"/g, ''));
|
|
1047
|
+
this._send(buildCopyInResponse(schema ? Object.keys(schema).length : 0));
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
async _finishCopyIn(failed) {
|
|
1051
|
+
const copy = this._copyIn;
|
|
1052
|
+
if (!copy) return;
|
|
1053
|
+
this._copyIn = null;
|
|
1054
|
+
if (failed) {
|
|
1055
|
+
this._send(buildErrorResponse('57014', 'COPY FROM STDIN failed'));
|
|
1056
|
+
this._send(buildReadyForQuery(this._rfqStatus()));
|
|
1057
|
+
return;
|
|
1058
|
+
}
|
|
1059
|
+
const text = Buffer.concat(copy.chunks).toString('utf8');
|
|
1060
|
+
const lines = text.split('\n').filter((l) => l.length > 0 && l !== '\\.');
|
|
1061
|
+
const engine = await this._getEngine();
|
|
1062
|
+
let inserted = 0;
|
|
1063
|
+
for (const line of lines) {
|
|
1064
|
+
const cells = line.split('\t').map((v) => v === '\\N' ? null
|
|
1065
|
+
: v.replace(/\\([\\tnr])/g, (m, c) => ({ '\\': '\\', t: '\t', n: '\n', r: '\r' })[c]));
|
|
1066
|
+
const literals = cells.map((v) => v === null ? 'NULL' : "'" + String(v).replace(/'/g, "''") + "'").join(', ');
|
|
1067
|
+
await executeSQL(engine, `INSERT INTO ${copy.table} VALUES (${literals})`, {
|
|
1068
|
+
dialect: 'pg', safety: false, session: { currentDb: this.database, connectionId: this._pid }
|
|
1069
|
+
});
|
|
1070
|
+
inserted++;
|
|
1071
|
+
}
|
|
1072
|
+
this._send(buildCommandComplete(`COPY ${inserted}`));
|
|
1073
|
+
this._send(buildReadyForQuery(this._rfqStatus()));
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
_unlisten(ch) {
|
|
1077
|
+
this._listenChannels.delete(ch);
|
|
1078
|
+
const set = this.server._channels.get(ch);
|
|
1079
|
+
if (set) { set.delete(this); if (set.size === 0) this.server._channels.delete(ch); }
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
// #353:LISTEN / UNLISTEN / NOTIFY 由服务端维护订阅表并广播 A 帧
|
|
1083
|
+
async _tryNotifyCommand(sql) {
|
|
1084
|
+
const s = String(sql || '').trim();
|
|
1085
|
+
let m = /^LISTEN\s+([A-Za-z_][\w$]*)\s*;?$/i.exec(s);
|
|
1086
|
+
if (m) {
|
|
1087
|
+
const ch = m[1];
|
|
1088
|
+
this._listenChannels.add(ch);
|
|
1089
|
+
let set = this.server._channels.get(ch);
|
|
1090
|
+
if (!set) { set = new Set(); this.server._channels.set(ch, set); }
|
|
1091
|
+
set.add(this);
|
|
1092
|
+
this._send(buildCommandComplete('LISTEN'));
|
|
1093
|
+
return true;
|
|
1094
|
+
}
|
|
1095
|
+
m = /^UNLISTEN\s+(\*|[A-Za-z_][\w$]*)\s*;?$/i.exec(s);
|
|
1096
|
+
if (m) {
|
|
1097
|
+
if (m[1] === '*') { for (const ch of Array.from(this._listenChannels)) this._unlisten(ch); }
|
|
1098
|
+
else this._unlisten(m[1]);
|
|
1099
|
+
this._send(buildCommandComplete('UNLISTEN'));
|
|
1100
|
+
return true;
|
|
1101
|
+
}
|
|
1102
|
+
m = /^NOTIFY\s+([A-Za-z_][\w$]*)(?:\s*,\s*(.+?))?\s*;?$/i.exec(s);
|
|
1103
|
+
if (m) {
|
|
1104
|
+
const ch = m[1];
|
|
1105
|
+
let payload = '';
|
|
1106
|
+
if (m[2]) {
|
|
1107
|
+
payload = m[2].trim().replace(/;\s*$/, '');
|
|
1108
|
+
if ((payload[0] === "'" && payload.endsWith("'")) || (payload[0] === '"' && payload.endsWith('"'))) {
|
|
1109
|
+
payload = payload.slice(1, -1).replace(/''/g, "'");
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
const set = this.server._channels.get(ch);
|
|
1113
|
+
if (set) for (const conn of set) conn._send(buildNotification(this._pid, ch, payload));
|
|
1114
|
+
this._send(buildCommandComplete('NOTIFY'));
|
|
1115
|
+
return true;
|
|
1116
|
+
}
|
|
1117
|
+
return false;
|
|
1118
|
+
}
|
|
1119
|
+
|
|
803
1120
|
async _handleSimpleQuery(sql) {
|
|
804
1121
|
const trimmed = sql.trim();
|
|
805
1122
|
// #387:只含空白/分号/注释的查询串不包含任何 SQL 语句,按协议必须回 EmptyQueryResponse。
|
|
@@ -823,6 +1140,41 @@ class PgConnection {
|
|
|
823
1140
|
this._handleSet(trimmed);
|
|
824
1141
|
return;
|
|
825
1142
|
}
|
|
1143
|
+
// #370:COPY 子协议(解析层不识别 COPY,需在服务端拦截)
|
|
1144
|
+
const copyOut = /^COPY\s+(\S+)\s+TO\s+STDOUT\b/i.exec(trimmed);
|
|
1145
|
+
if (copyOut) {
|
|
1146
|
+
await this._handleCopyOut(copyOut[1].replace(/;/g, ''));
|
|
1147
|
+
this._send(buildReadyForQuery(this._rfqStatus()));
|
|
1148
|
+
return;
|
|
1149
|
+
}
|
|
1150
|
+
const copyIn = /^COPY\s+(\S+)\s+FROM\s+STDIN\b/i.exec(trimmed);
|
|
1151
|
+
if (copyIn) {
|
|
1152
|
+
this._startCopyIn(copyIn[1].replace(/;/g, ''));
|
|
1153
|
+
return; // ReadyForQuery 延后到 CopyDone/CopyFail
|
|
1154
|
+
}
|
|
1155
|
+
// #353:LISTEN/UNLISTEN/NOTIFY
|
|
1156
|
+
if (await this._tryNotifyCommand(trimmed)) {
|
|
1157
|
+
this._send(buildReadyForQuery(this._rfqStatus()));
|
|
1158
|
+
return;
|
|
1159
|
+
}
|
|
1160
|
+
// #380:多语句简单查询包在隐式事务中,任一句失败整批回滚;显式事务保持原路径
|
|
1161
|
+
const statements = pgSplitStatements(sql);
|
|
1162
|
+
const hasExplicitTxn = statements.some((s) => /^(BEGIN|START\s+TRANSACTION|COMMIT|END|ROLLBACK|ABORT|SAVEPOINT|RELEASE)\b/i.test(s));
|
|
1163
|
+
if (statements.length > 1 && !hasExplicitTxn && !this._inTransaction) {
|
|
1164
|
+
const engine = await this._getEngine();
|
|
1165
|
+
if (engine && typeof engine.beginTx === 'function' && typeof engine.rollbackTx === 'function') {
|
|
1166
|
+
const tx = await engine.beginTx();
|
|
1167
|
+
try {
|
|
1168
|
+
await this._executeSql(sql, null, null);
|
|
1169
|
+
await engine.commitTx(tx);
|
|
1170
|
+
} catch (e) {
|
|
1171
|
+
await engine.rollbackTx(tx);
|
|
1172
|
+
throw e;
|
|
1173
|
+
}
|
|
1174
|
+
this._send(buildReadyForQuery(this._rfqStatus()));
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
826
1178
|
try {
|
|
827
1179
|
await this._executeSql(sql, null, null);
|
|
828
1180
|
} catch (e) {
|
|
@@ -890,6 +1242,10 @@ class PgConnection {
|
|
|
890
1242
|
}
|
|
891
1243
|
try {
|
|
892
1244
|
const { sql } = portal.stmt;
|
|
1245
|
+
// #353/#370:扩展协议下同样支持通知命令与 COPY TO STDOUT
|
|
1246
|
+
if (await this._tryNotifyCommand(sql)) return;
|
|
1247
|
+
const cm = /^COPY\s+(\S+)\s+TO\s+STDOUT\b/i.exec(String(sql).trim());
|
|
1248
|
+
if (cm) { await this._handleCopyOut(cm[1].replace(/;/g, '')); return; }
|
|
893
1249
|
await this._executeSql(sql, portal.values || [], portal.resultFormats);
|
|
894
1250
|
} catch (e) {
|
|
895
1251
|
if (this._inTransaction) this._txAborted = true;
|
|
@@ -898,6 +1254,13 @@ class PgConnection {
|
|
|
898
1254
|
}
|
|
899
1255
|
|
|
900
1256
|
async _executeSql(sql, values, resultFormats) {
|
|
1257
|
+
// #379:被 CancelRequest 标记的后端在(下一个/在途)语句入口回 57014
|
|
1258
|
+
if (this._cancelRequested) {
|
|
1259
|
+
this._cancelRequested = false;
|
|
1260
|
+
const err = new Error('canceling statement due to user request');
|
|
1261
|
+
err.sqlState = '57014';
|
|
1262
|
+
throw err;
|
|
1263
|
+
}
|
|
901
1264
|
const engine = await this._getEngine();
|
|
902
1265
|
const ctx = {
|
|
903
1266
|
session: { currentDb: this.database, connectionId: this._pid },
|
|
@@ -947,10 +1310,17 @@ class PgConnection {
|
|
|
947
1310
|
} else if (res.type === 'begin' || res.type === 'commit' || res.type === 'rollback') {
|
|
948
1311
|
this._inTransaction = res.type === 'begin';
|
|
949
1312
|
this._txAborted = false;
|
|
1313
|
+
// #551:portal 生命周期止于事务结束,COMMIT/ROLLBACK 后不可再 Execute
|
|
1314
|
+
if (res.type !== 'begin') this._portal.clear();
|
|
950
1315
|
this._send(buildCommandComplete(String(res.type).toUpperCase()));
|
|
951
|
-
} else if (res.type === 'createTable' || res.type === 'dropTable' || res.type === 'createDatabase' || res.type === 'dropDatabase'
|
|
952
|
-
|
|
953
|
-
|
|
1316
|
+
} else if (res.type === 'createTable' || res.type === 'dropTable' || res.type === 'createDatabase' || res.type === 'dropDatabase'
|
|
1317
|
+
|| res.type === 'alterTable' || res.type === 'createIndex' || res.type === 'dropIndex' || res.type === 'truncate') {
|
|
1318
|
+
// #308/#553:DDL CommandComplete tag 用真实语句类型,恒 OK 会让客户端误判命令
|
|
1319
|
+
const tags = {
|
|
1320
|
+
createTable: 'CREATE TABLE', dropTable: 'DROP TABLE', createDatabase: 'CREATE DATABASE', dropDatabase: 'DROP DATABASE',
|
|
1321
|
+
alterTable: 'ALTER TABLE', createIndex: 'CREATE INDEX', dropIndex: 'DROP INDEX',
|
|
1322
|
+
truncate: 'TRUNCATE TABLE 1' // PG 的 tag 数字为被截断的表数
|
|
1323
|
+
};
|
|
954
1324
|
this._send(buildCommandComplete(tags[res.type] || 'OK'));
|
|
955
1325
|
} else if (res.type === 'showTables' || res.type === 'showDatabases' || res.type === 'showColumns') {
|
|
956
1326
|
const types = (res.columns || []).map(() => 'string');
|
|
@@ -997,6 +1367,10 @@ class PgConnection {
|
|
|
997
1367
|
if (codeKey === 'ER_DATA_TOO_LONG' || /Data too long/i.test(m)) return '22001';
|
|
998
1368
|
if (codeKey === 'ER_OUT_OF_RANGE' || /Out of range/i.test(m)) return '22003';
|
|
999
1369
|
if (codeKey === 'ER_NO_REFERENCED_ROW' || /foreign key/i.test(m)) return '23503';
|
|
1370
|
+
// #556:调用不存在的函数为 42883 undefined_function(独立于缺列/语法)
|
|
1371
|
+
if (/FUNCTION\s+.*\s+does not exist/i.test(m)) return '42883';
|
|
1372
|
+
// #551/#493:portal 不存在 → 34000 invalid_portal_name / invalid_cursor_name
|
|
1373
|
+
if (/portal\s+".*"\s+does not exist/i.test(m)) return '34000';
|
|
1000
1374
|
if (codeKey === 'ER_SYNTAX_ERROR' || /syntax|Unexpected token|Expected/i.test(m)) return '42601';
|
|
1001
1375
|
// #465:日期/时间值越界 → 22008;格式无法解析 → 22007(ER_INVALID_DATE 码 1292)
|
|
1002
1376
|
if (/date\/time field value out of range|time value out of range/i.test(m)) return '22008';
|
|
@@ -1023,6 +1397,8 @@ class PgServer {
|
|
|
1023
1397
|
this._server = null;
|
|
1024
1398
|
this._sockets = new Set();
|
|
1025
1399
|
this._connSeq = 0;
|
|
1400
|
+
this._backends = new Map(); // #379:`pid:secret` → PgConnection
|
|
1401
|
+
this._channels = new Map(); // #353:channel → Set<PgConnection>
|
|
1026
1402
|
this._databases = new Map();
|
|
1027
1403
|
this._engines = new Map();
|
|
1028
1404
|
}
|
package/lib/plugin.js
CHANGED
|
@@ -167,6 +167,11 @@ function buildPluginContext(engine, plugin) {
|
|
|
167
167
|
if (typeof engine.getTables === 'function') return engine.getTables();
|
|
168
168
|
return [];
|
|
169
169
|
},
|
|
170
|
+
/** 表实例(Pure JS 引擎);不存在或非该引擎时返回 null (#500) */
|
|
171
|
+
table(t) {
|
|
172
|
+
if (engine._tables && engine._tables[t]) return engine._tables[t];
|
|
173
|
+
return null;
|
|
174
|
+
},
|
|
170
175
|
/** 表是否存在 */
|
|
171
176
|
hasTable(t) {
|
|
172
177
|
if (typeof engine.hasTable === 'function') return engine.hasTable(t);
|
|
@@ -207,8 +212,11 @@ function applyPlugin(engine, plugin, opts) {
|
|
|
207
212
|
if (!engine._plugins) engine._plugins = [];
|
|
208
213
|
if (!engine._eventListeners) engine._eventListeners = [];
|
|
209
214
|
|
|
210
|
-
// P3-2: 重复 use()
|
|
211
|
-
|
|
215
|
+
// P3-2 / #487: 重复 use() 同一插件钩子双触发——具名插件按 name 去重;
|
|
216
|
+
// 无名插件按对象引用去重,函数式插件按 install 函数引用去重。
|
|
217
|
+
if (engine._plugins.includes(plugin) || engine._plugins.some(p =>
|
|
218
|
+
(p.name && p.name === plugin.name) ||
|
|
219
|
+
(!p.name && !plugin.name && p.install && p.install === plugin.install))) {
|
|
212
220
|
return engine; // 已注册,跳过
|
|
213
221
|
}
|
|
214
222
|
|
|
@@ -221,10 +229,33 @@ function applyPlugin(engine, plugin, opts) {
|
|
|
221
229
|
}
|
|
222
230
|
}
|
|
223
231
|
|
|
232
|
+
// #530: install 失败必须回滚本次登记(含 install 内 ctx.on() 追加的钩子),
|
|
233
|
+
// 否则失败插件会以孤儿钩子身份继续参与后续写操作。
|
|
234
|
+
const hooksBefore = new Map();
|
|
235
|
+
if (engine._hooks) {
|
|
236
|
+
for (const [hook, list] of Object.entries(engine._hooks)) hooksBefore.set(hook, list.slice());
|
|
237
|
+
}
|
|
238
|
+
const listenersBefore = engine._eventListeners ? engine._eventListeners.slice() : [];
|
|
239
|
+
|
|
224
240
|
registerHooks(engine, plugin);
|
|
225
241
|
|
|
226
242
|
const ctx = buildPluginContext(engine, plugin);
|
|
227
|
-
|
|
243
|
+
try {
|
|
244
|
+
if (typeof plugin.install === 'function') plugin.install(engine, ctx);
|
|
245
|
+
} catch (e) {
|
|
246
|
+
if (engine._hooks) {
|
|
247
|
+
for (const hook of Object.keys(engine._hooks)) {
|
|
248
|
+
if (!hooksBefore.has(hook)) delete engine._hooks[hook];
|
|
249
|
+
else {
|
|
250
|
+
const before = hooksBefore.get(hook);
|
|
251
|
+
engine._hooks[hook].length = 0;
|
|
252
|
+
for (const entry of before) engine._hooks[hook].push(entry);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
engine._eventListeners = listenersBefore.slice();
|
|
257
|
+
throw e;
|
|
258
|
+
}
|
|
228
259
|
if (typeof plugin.onEvent === 'function') engine._eventListeners.push(plugin.onEvent);
|
|
229
260
|
|
|
230
261
|
engine._plugins.push(plugin);
|
package/lib/query.js
CHANGED
|
@@ -425,19 +425,25 @@ class Query {
|
|
|
425
425
|
return this._countRaw();
|
|
426
426
|
}
|
|
427
427
|
|
|
428
|
+
// #436:SQL 聚合忽略 NULL;空集的 SUM/AVG/MIN/MAX 返回 NULL
|
|
429
|
+
_nonNullRows(field) {
|
|
430
|
+
return this._getFilteredRows().filter(r => r[field] !== null && r[field] !== undefined);
|
|
431
|
+
}
|
|
432
|
+
|
|
428
433
|
sum(field) {
|
|
429
|
-
const rows = this.
|
|
434
|
+
const rows = this._nonNullRows(field);
|
|
435
|
+
if (rows.length === 0) return null;
|
|
430
436
|
return rows.reduce((acc, r) => acc + (Number(r[field]) || 0), 0);
|
|
431
437
|
}
|
|
432
438
|
|
|
433
439
|
avg(field) {
|
|
434
|
-
const rows = this.
|
|
435
|
-
if (rows.length === 0) return
|
|
436
|
-
return
|
|
440
|
+
const rows = this._nonNullRows(field);
|
|
441
|
+
if (rows.length === 0) return null;
|
|
442
|
+
return rows.reduce((acc, r) => acc + (Number(r[field]) || 0), 0) / rows.length;
|
|
437
443
|
}
|
|
438
444
|
|
|
439
445
|
min(field) {
|
|
440
|
-
const rows = this.
|
|
446
|
+
const rows = this._nonNullRows(field);
|
|
441
447
|
if (rows.length === 0) return null;
|
|
442
448
|
return rows.reduce((min, r) => {
|
|
443
449
|
const v = Number(r[field]);
|
|
@@ -446,7 +452,7 @@ class Query {
|
|
|
446
452
|
}
|
|
447
453
|
|
|
448
454
|
max(field) {
|
|
449
|
-
const rows = this.
|
|
455
|
+
const rows = this._nonNullRows(field);
|
|
450
456
|
if (rows.length === 0) return null;
|
|
451
457
|
return rows.reduce((max, r) => {
|
|
452
458
|
const v = Number(r[field]);
|