@@ -450,9 +450,12 @@ const dbPool = new Pool(
450450 POOL_CONNECTIONS ,
451451);
452452
453- const client = await dbPool .connect (); // 19 connections are still available
454- await client .queryArray ` UPDATE X SET Y = 'Z' ` ;
455- client .release (); // This connection is now available for use again
453+ // Note the `using` keyword in block scope
454+ {
455+ using client = await dbPool .connect ();
456+ // 19 connections are still available
457+ await client .queryArray ` UPDATE X SET Y = 'Z' ` ;
458+ } // This connection is now available for use again
456459```
457460
458461The number of pools is up to you, but a pool of 20 is good for small
@@ -515,9 +518,9 @@ await client_3.release();
515518
516519#### Pools made simple
517520
518- The following example is a simple abstraction over pools that allows you to
519- execute one query and release the used client after returning the result in a
520- single function call
521+ Because of ` using ` keyword there is no need for manually releasing pool client.
522+
523+ Legacy code like this
521524
522525``` ts
523526async function runQuery(query : string ) {
@@ -532,7 +535,27 @@ async function runQuery(query: string) {
532535}
533536
534537await runQuery (" SELECT ID, NAME FROM USERS" ); // [{id: 1, name: 'Carlos'}, {id: 2, name: 'John'}, ...]
535- await runQuery (" SELECT ID, NAME FROM USERS WHERE ID = '1'" ); // [{id: 1, name: 'Carlos'}, {id: 2, name: 'John'}, ...]
538+ await runQuery (" SELECT ID, NAME FROM USERS WHERE ID = '1'" ); // [{id: 1, name: 'Carlos'}]
539+ ```
540+
541+ Can now be written simply as
542+
543+ ``` ts
544+ async function runQuery(query : string ) {
545+ using client = await pool .connect ();
546+ return await client .queryObject (query );
547+ }
548+
549+ await runQuery (" SELECT ID, NAME FROM USERS" ); // [{id: 1, name: 'Carlos'}, {id: 2, name: 'John'}, ...]
550+ await runQuery (" SELECT ID, NAME FROM USERS WHERE ID = '1'" ); // [{id: 1, name: 'Carlos'}]
551+ ```
552+
553+ But you can release pool client manually if you wish
554+
555+ ``` ts
556+ const client = await dbPool .connect (); // note the `const` instead of `using` keyword
557+ await client .queryArray ` UPDATE X SET Y = 'Z' ` ;
558+ client .release (); // This connection is now available for use again
536559```
537560
538561## Executing queries
0 commit comments