mysql icon indicating copy to clipboard operation
mysql copied to clipboard

Add idleConnectionTimeout to pool options

Open dicearr opened this issue 6 years ago • 7 comments

This option is specially useful when connecting to serverless databases, in which the instances are turned off when there is no connection alive.

Coming from #2195.

This aims to close #1276 and resolve #962.

dicearr avatar May 10 '19 13:05 dicearr

This option is great,and when will it be released to the official edition?@@dougwilson

gyj1278 avatar May 20 '19 11:05 gyj1278

I am working through this module prs and issues this week.

dougwilson avatar May 20 '19 11:05 dougwilson

@dicearr this would be ❤️ by many cloud users. Any plan to continue this PR?

akleiber avatar Mar 19 '20 21:03 akleiber

Hi @akleiber. After the review comment I tried to gracefully close the connection by using conn.end instead of conn.destroy in 6633202, which is a fixup commit. So, I don't think there is too much I can do here. If 6633202 is not what @dougwilson meant, some feedback would be appreciated. If it is, then I just need to squash the commits.

dicearr avatar Mar 21 '20 10:03 dicearr

We use this library with aws aurora and idleConnectionTimeout is really needed. I don't really have time to wait for this ticket to be merged. What do you guys think about attaching a timer on connection 'release' event, which will close connection if it's not acquired after 'x' time, can be done on top of library. update: Seems like you can't call conection.end() on released connection in 'release' event

rolandmarg avatar Jan 08 '21 16:01 rolandmarg

This is a temporary solution until this functionality has been merged. Place this right after importing the mysql library.

(() => {
	let createPool = mysql.createPool

	mysql.createPool = function(config){
		let pool = createPool(config)

		if(config.idleConnectionTimeout){
			let getConnection = pool.getConnection

			pool.getConnection = function(callback){
				getConnection.call(pool, (err, connection) => {
					if(err){
						callback(err, connection)
						return
					}

					if(connection.__lastUsed){
						if(Date.now() - connection.__lastUsed > config.idleConnectionTimeout){
							connection.destroy()
							pool.getConnection(callback)
							return
						}
					}

					connection.__lastUsed = Date.now()
					callback(err, connection)
				})
			}
		}

		return pool
	}
})()

This is forward compatible. So what it does is patch the createPool function to check for idleConnectionTimeout, if this setting is present, it patches the pool's getConnection function to destroy any connection, that it was about to serve, that has been been idle for longer than specified.

Mwni avatar Jan 13 '21 15:01 Mwni

https://github.com/mysqljs/mysql/pull/2507/files

Hello, everyone, I commit a pr and to solve this issue, any feedback would be appreciated.

qingyang-id avatar Jul 16 '21 13:07 qingyang-id