I’m currently in the middle of re-working my side project to use the pg npm package. As part of that, I now have to worry about managing the connection pool, which is something that was handled behind the scenes with the ORM that I was using previously, the ORM that I was having problems getting to play nicely with Typescript.
Online, I saw a recommendation to create a pool like so:
import { Pool } from 'pg';
const pool = new Pool({
host: 'localhost',
user: 'database-user',
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
})
And then to execute database operations like so:
const wrapperFunc = async (): Promise<void> => {
const client = await pool.connect(); // create a connection
try {
const query = `
CREATE TABLE users (
email varchar,
firstName varchar,
lastName varchar,
age int
);
`;
await client.query(query); // use the connection
} catch (error) {
// Deal with your catch error
} finally {
client.release(); // release the connection
}
}
Releasing the connection is important because otherwise you end up with a bunch of zombie connections that your database is waiting on, but which aren’t live anymore. Eventually, if you don’t release the connections, then your database hits its max connection count and it starts refusing new connections.
I had the bright idea of changing up my code to look more like this, which I thought would work just as well:
const wrapperFunc = async (): Promise<void> => {
const client = await pool.connect(); // create a connection
try {
const query = `
CREATE TABLE users (
email varchar,
firstName varchar,
lastName varchar,
age int
);
`;
await client.query(query); // use the connection
client.release(); // release the connection
return
} catch (error) {
client.release(); // release the connection
// Deal with your catch error
}
}
I thought that would still result in the client being released regardless of whether we threw an error or not, but quickly started getting errors while trying to run my unit tests.
I can’t explain why yet, but for some reason, a client.release() position like I’ve got above doesn’t release the clients like it should, so I’ll be sticking with putting my client.release() statements in my finally block going forward.