@@ -450,9 +450,12 @@ const dbPool = new Pool(
450
450
POOL_CONNECTIONS ,
451
451
);
452
452
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
456
459
```
457
460
458
461
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();
515
518
516
519
#### Pools made simple
517
520
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
521
524
522
525
``` ts
523
526
async function runQuery(query : string ) {
@@ -532,7 +535,27 @@ async function runQuery(query: string) {
532
535
}
533
536
534
537
await 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
536
559
```
537
560
538
561
## Executing queries
0 commit comments