Skip to content

Commit 2606e50

Browse files
authored
Document using keyword syntax (denodrivers#475)
* doc: Pool connection handling using `using` keyword * 0.19.3
1 parent 499143f commit 2606e50

File tree

2 files changed

+31
-8
lines changed

2 files changed

+31
-8
lines changed

deno.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"lock": false,
33
"name": "@bartlomieju/postgres",
4-
"version": "0.19.2",
4+
"version": "0.19.3",
55
"exports": "./mod.ts"
66
}

docs/README.md

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -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

458461
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();
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
523526
async function runQuery(query: string) {
@@ -532,7 +535,27 @@ async function runQuery(query: string) {
532535
}
533536

534537
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
536559
```
537560

538561
## Executing queries

0 commit comments

Comments
 (0)