From 2606e50f02b525ac89012bbca9ed7ca863b215a9 Mon Sep 17 00:00:00 2001 From: Pavel Lang Date: Mon, 11 Mar 2024 03:28:54 +0100 Subject: [PATCH] Document `using` keyword syntax (#475) * doc: Pool connection handling using `using` keyword * 0.19.3 --- deno.json | 2 +- docs/README.md | 37 ++++++++++++++++++++++++++++++------- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/deno.json b/deno.json index d387deb..f4697e7 100644 --- a/deno.json +++ b/deno.json @@ -1,6 +1,6 @@ { "lock": false, "name": "@bartlomieju/postgres", - "version": "0.19.2", + "version": "0.19.3", "exports": "./mod.ts" } diff --git a/docs/README.md b/docs/README.md index c476307..aad68e4 100644 --- a/docs/README.md +++ b/docs/README.md @@ -450,9 +450,12 @@ const dbPool = new Pool( POOL_CONNECTIONS, ); -const client = await dbPool.connect(); // 19 connections are still available -await client.queryArray`UPDATE X SET Y = 'Z'`; -client.release(); // This connection is now available for use again +// Note the `using` keyword in block scope +{ + using client = await dbPool.connect(); + // 19 connections are still available + await client.queryArray`UPDATE X SET Y = 'Z'`; +} // This connection is now available for use again ``` The number of pools is up to you, but a pool of 20 is good for small @@ -515,9 +518,9 @@ await client_3.release(); #### Pools made simple -The following example is a simple abstraction over pools that allows you to -execute one query and release the used client after returning the result in a -single function call +Because of `using` keyword there is no need for manually releasing pool client. + +Legacy code like this ```ts async function runQuery(query: string) { @@ -532,7 +535,27 @@ async function runQuery(query: string) { } await runQuery("SELECT ID, NAME FROM USERS"); // [{id: 1, name: 'Carlos'}, {id: 2, name: 'John'}, ...] -await runQuery("SELECT ID, NAME FROM USERS WHERE ID = '1'"); // [{id: 1, name: 'Carlos'}, {id: 2, name: 'John'}, ...] +await runQuery("SELECT ID, NAME FROM USERS WHERE ID = '1'"); // [{id: 1, name: 'Carlos'}] +``` + +Can now be written simply as + +```ts +async function runQuery(query: string) { + using client = await pool.connect(); + return await client.queryObject(query); +} + +await runQuery("SELECT ID, NAME FROM USERS"); // [{id: 1, name: 'Carlos'}, {id: 2, name: 'John'}, ...] +await runQuery("SELECT ID, NAME FROM USERS WHERE ID = '1'"); // [{id: 1, name: 'Carlos'}] +``` + +But you can release pool client manually if you wish + +```ts +const client = await dbPool.connect(); // note the `const` instead of `using` keyword +await client.queryArray`UPDATE X SET Y = 'Z'`; +client.release(); // This connection is now available for use again ``` ## Executing queries