From b744ff362be51a937a9099ee9dd67452d68789e3 Mon Sep 17 00:00:00 2001 From: Stef Date: Sat, 30 Apr 2022 14:10:54 +0100 Subject: [PATCH 1/2] Update README.md Use try/finally to always release the client on error before handling Refs: https://node-postgres.com/features/pooling#examples --- README.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 4cc75c7..3b12f50 100644 --- a/README.md +++ b/README.md @@ -64,11 +64,14 @@ fastify.register(require('@fastify/postgres'), { fastify.get('/user/:id', async (req, reply) => { const client = await fastify.pg.connect() - const { rows } = await client.query( - 'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id], - ) - client.release() - return rows + try { + const { rows } = await client.query( + 'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id], + ) + return rows + } finally { + client.release() + } }) fastify.listen(3000, err => { @@ -233,7 +236,7 @@ fastify.listen(3000, err => { ``` ### Transact route option -It is possible to automatically wrap a route handler in a transaction by using the `transact` option when registering a route with Fastify. Note that the option must be scoped within a `pg` options object to take effect. +It is possible to automatically wrap a route handler in a transaction by using the `transact` option when registering a route with Fastify. Note that the option must be scoped within a `pg` options object to take effect. `query` commands can then be accessed at `request.pg` or `request.pg[name]` and `transact` can be set for either the root pg client with value `true` or for a pg client at a particular namespace with value `name`. Note that the namespace needs to be set when registering the plugin in order to be available on the request object. From af42c190d1078bd9049ef2cdbe730f922b467c52 Mon Sep 17 00:00:00 2001 From: Stef Date: Sat, 30 Apr 2022 14:40:42 +0100 Subject: [PATCH 2/2] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 3b12f50..39ed5cb 100644 --- a/README.md +++ b/README.md @@ -68,8 +68,10 @@ fastify.get('/user/:id', async (req, reply) => { const { rows } = await client.query( 'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id], ) + // Note: avoid doing expensive computation here, this will block releasing the client return rows } finally { + // Release the client immediately after query resolves, or upon error client.release() } })