RFC Allow repeat calls to `connect()` to resolve
See original GitHub issueIt seems that there is a common use where developers would like to call ConnectionPool.connect()
repeatedly to then chain on a request.
For example:
const pool = new ConnectionPool();
function runQuery(query) {
return pool.connect().then(connectedPool => {
return connectedPool.request().query('SELECT 1');
});
}
At the moment, repeat calls to connect()
in the above example will throw an error because the pool is already connected.
This also has the advantage of allowing developers not to have to worry about whether the pool is connected or closed. At the moment, to achieve something similar you’d need to do the following:
const pool = new ConnectionPool();
function runQuery(query) {
return Promise.resolve(pool.connected ? pool : pool.connect()).then(connectedPool => {
return connectedPool.request().query('SELECT 1');
});
}
This feels overly verbose and needless and should be simple to solve.
As an enhancement, we may wish to do something similar for when the pool is in a “connecting” state. At the moment if two process call connect()
whilst the pool is connecting, we will see an error, which will mean that using the pool.connect().then()
pattern will be inherently unsafe for any parallel execution of queries on a pool that’s not yet connected.
It feels like we are relying on devs to do too much caretaking of the pool when the library should be able to abstract that away.
Potentially the final solution could just be a lazily invoked connection. eg:
const pool = new ConnectionPool();
function runQuery(query) {
// internally it will check if the pool has connected, if not it will attempt to connect and then run the query
return pool.request().query(query);
}
developers can still call connect()
to validate the connection is working but they wouldn’t need to worry about the connected
or connecting
state of the pool at all.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:4
- Comments:12
Shouldn’t the docs and examples also be updated?
Here’s the other solution I was talking about. This one I actually tested.
I’m using Typescript because the example is from a project of mine. It’s not part of a
runQuery
function but a get a pool that’s actually connected before trying to run a query function.