@@ -75,6 +75,9 @@ export default class MySQLConnection extends SQLLikeConnection {
7575 protected pool : Pool | undefined ;
7676 protected currentConnection : PoolConnection | undefined ;
7777 protected onStateChangedCallback : ( state : string ) => void ;
78+ protected lastActivity = 0 ;
79+ protected isRunning = false ;
80+ protected keepAliveTimerId ?: NodeJS . Timer ;
7881
7982 constructor (
8083 connectionConfig : DatabaseConnectionConfig ,
@@ -94,8 +97,16 @@ export default class MySQLConnection extends SQLLikeConnection {
9497 connectionLimit : 1 ,
9598 } ) ;
9699
100+ this . lastActivity = Date . now ( ) ;
97101 this . onStateChangedCallback ( 'Connected' ) ;
98102
103+ this . keepAliveTimerId = setInterval ( ( ) => {
104+ if ( Date . now ( ) - this . lastActivity > 6000 && ! this . isRunning ) {
105+ this . lastActivity = Date . now ( ) ;
106+ this . ping ( ) ;
107+ }
108+ } , 5000 ) ;
109+
99110 this . pool . on ( 'connection' , ( connection ) => {
100111 this . currentConnection = connection ;
101112 } ) ;
@@ -104,6 +115,10 @@ export default class MySQLConnection extends SQLLikeConnection {
104115 return this . pool ;
105116 }
106117
118+ protected async ping ( ) {
119+ this . currentConnection ?. ping ( ) ;
120+ }
121+
107122 async killCurrentQuery ( ) {
108123 if ( this . currentConnection ) {
109124 // Make another connection quickly to cancel the query
@@ -121,6 +136,9 @@ export default class MySQLConnection extends SQLLikeConnection {
121136 sql : string ,
122137 params ?: Record < string , unknown >
123138 ) : Promise < QueryResult > {
139+ this . lastActivity = Date . now ( ) ;
140+ this . isRunning = true ;
141+
124142 try {
125143 const conn = await this . getConnection ( ) ;
126144 const result = await conn . query ( sql , params ) ;
@@ -144,13 +162,16 @@ export default class MySQLConnection extends SQLLikeConnection {
144162 mapHeaderType
145163 ) ;
146164
165+ this . isRunning = false ;
147166 return {
148167 headers,
149168 rows : result [ 0 ] as Record < string , unknown > [ ] ,
150169 keys : { } ,
151170 error : null ,
152171 } ;
153172 } catch ( e : unknown ) {
173+ this . isRunning = false ;
174+
154175 return {
155176 headers : [ ] ,
156177 rows : [ ] ,
@@ -168,5 +189,9 @@ export default class MySQLConnection extends SQLLikeConnection {
168189 conn . end ( ) ;
169190 conn . destroy ( ) ;
170191 }
192+
193+ if ( this . keepAliveTimerId ) {
194+ clearTimeout ( this . keepAliveTimerId ) ;
195+ }
171196 }
172197}
0 commit comments