Node-mysql2: Releasing connections

Created on 23 Jan 2020  路  2Comments  路  Source: sidorares/node-mysql2

Hello,
In the documentation, the way to release a connection from the pool is to use the callback version of getting a connection.
```// For pool initialization, see above
pool.getConnection(function(err, conn) {
// Do something with the connection
conn.query(/* ... */);
// Don't forget to release the connection when finished!
pool.releaseConnection(conn);
})

By looking at the source code, I noticed that the promisified pool implementation did not have `releaseConnection` implemented, which explains the code example in README.

Because I dont want to deal with callback after finding, this lib this seems like one of the only callback methods left. I wanted to find a work around without any wrapper. And, I was able to come up with this.

const poolPromise = pool.promise()
var connection = await poolPromise.getConnection()
await connection.beginTransaction()
// couple queries
await connection.commit()
connection.release()
```
Is there any downside to releasing the connection directly and bypassing the pool's release method?

Most helpful comment

Great!! So the connection knows about its pool and calls the right method
I was not able to trace the code to that point.

Releasing from the connection seems to be easier than releasing from the pool because in most cases we never care to persist a local copy of the pool reference in the context of a transaction.

var connection = await pool.promise()getConnection()
await connection.beginTransaction()
// couple queries
await connection.commit()
connection.release()

I will try to submit a docs change if i managed to know how to do it in the next couple of days. I am kind of new to contributing.

All 2 comments

connection.release does exactly that - https://github.com/sidorares/node-mysql2/blob/a0ea513b0d4929e6ee61639a09f38a85ac01f7fa/lib/pool_connection.js#L25

we probably need to update example in documentation

Great!! So the connection knows about its pool and calls the right method
I was not able to trace the code to that point.

Releasing from the connection seems to be easier than releasing from the pool because in most cases we never care to persist a local copy of the pool reference in the context of a transaction.

var connection = await pool.promise()getConnection()
await connection.beginTransaction()
// couple queries
await connection.commit()
connection.release()

I will try to submit a docs change if i managed to know how to do it in the next couple of days. I am kind of new to contributing.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MHDante picture MHDante  路  4Comments

sidorares picture sidorares  路  7Comments

DirkWolthuis picture DirkWolthuis  路  3Comments

juliandavidmr picture juliandavidmr  路  4Comments

hezjing picture hezjing  路  3Comments