Skip to content

Commit 5fa053a

Browse files
committed
feat(query): add timeout option
1 parent 4e22e33 commit 5fa053a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

lib/commands/query.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'use strict';
22

33
const process = require('process');
4+
const Timers = require('timers');
45

56
const Readable = require('stream').Readable;
67

@@ -21,6 +22,8 @@ class Query extends Command {
2122
this._queryOptions = options;
2223
this.namedPlaceholders = options.namedPlaceholders || false;
2324
this.onResult = callback;
25+
this.timeout = options.timeout;
26+
this.queryTimeout = null;
2427
this._fieldCount = 0;
2528
this._rowParser = null;
2629
this._fields = [];
@@ -48,6 +51,15 @@ class Query extends Command {
4851
}
4952
this._connection = connection;
5053
this.options = Object.assign({}, connection.config, this._queryOptions);
54+
55+
if (this.timeout) {
56+
const timeoutHandler = this._handleTimeoutError.bind(this);
57+
this.queryTimeout = Timers.setTimeout(
58+
timeoutHandler,
59+
this.timeout
60+
);
61+
}
62+
5163
const cmdPacket = new Packets.Query(
5264
this.sql,
5365
connection.config.charsetNumber
@@ -58,6 +70,10 @@ class Query extends Command {
5870

5971
done() {
6072
this._unpipeStream();
73+
if (this.queryTimeout) {
74+
Timers.clearTimeout(this.queryTimeout);
75+
this.queryTimeout = null;
76+
}
6177
if (this.onResult) {
6278
let rows, fields;
6379
if (this._resultIndex === 0) {
@@ -272,6 +288,24 @@ class Query extends Command {
272288
});
273289
return stream;
274290
}
291+
292+
_handleTimeoutError() {
293+
if (this.queryTimeout) {
294+
Timers.clearTimeout(this.queryTimeout);
295+
this.queryTimeout = null;
296+
}
297+
298+
const err = new Error('Query inactivity timeout');
299+
err.errorno = 'PROTOCOL_SEQUENCE_TIMEOUT';
300+
err.code = 'PROTOCOL_SEQUENCE_TIMEOUT';
301+
err.syscall = 'query';
302+
303+
if (this.onResult) {
304+
this.onResult(err);
305+
} else {
306+
this.emit('error', err);
307+
}
308+
}
275309
}
276310

277311
Query.prototype.catch = Query.prototype.then;

0 commit comments

Comments
 (0)