1
1
'use strict' ;
2
2
3
3
const process = require ( 'process' ) ;
4
+ const Timers = require ( 'timers' ) ;
4
5
5
6
const Readable = require ( 'stream' ) . Readable ;
6
7
@@ -21,6 +22,8 @@ class Query extends Command {
21
22
this . _queryOptions = options ;
22
23
this . namedPlaceholders = options . namedPlaceholders || false ;
23
24
this . onResult = callback ;
25
+ this . timeout = options . timeout ;
26
+ this . queryTimeout = null ;
24
27
this . _fieldCount = 0 ;
25
28
this . _rowParser = null ;
26
29
this . _fields = [ ] ;
@@ -48,6 +51,15 @@ class Query extends Command {
48
51
}
49
52
this . _connection = connection ;
50
53
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
+
51
63
const cmdPacket = new Packets . Query (
52
64
this . sql ,
53
65
connection . config . charsetNumber
@@ -58,6 +70,10 @@ class Query extends Command {
58
70
59
71
done ( ) {
60
72
this . _unpipeStream ( ) ;
73
+ if ( this . queryTimeout ) {
74
+ Timers . clearTimeout ( this . queryTimeout ) ;
75
+ this . queryTimeout = null ;
76
+ }
61
77
if ( this . onResult ) {
62
78
let rows , fields ;
63
79
if ( this . _resultIndex === 0 ) {
@@ -272,6 +288,24 @@ class Query extends Command {
272
288
} ) ;
273
289
return stream ;
274
290
}
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
+ }
275
309
}
276
310
277
311
Query . prototype . catch = Query . prototype . then ;
0 commit comments