Skip to content

Commit 24caf46

Browse files
committed
pool: Add support for client.release(true) with Symbol.dispose
Add a `destroyOnDispose` property on the client to signal that `[Symbol.dispose]()` should call `client.release(true)` instead of `client.release()`.
1 parent 06eb20f commit 24caf46

3 files changed

Lines changed: 34 additions & 2 deletions

File tree

docs/pages/apis/pool.mdx

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,10 @@ assert(pool.idleCount === 0)
187187
assert(pool.totalCount === 0)
188188
```
189189

190+
`client.destroyOnDispose: boolean`
191+
192+
`client[Symbol.dispose]() => void`
193+
190194
Alternatively, pool clients support [Explicit Resource Management](https://tc39.es/proposal-explicit-resource-management/), which means you can use the `using` syntax to release them if your runtime supports it.
191195

192196
```js
@@ -195,14 +199,23 @@ import { Pool } from 'pg'
195199

196200
const pool = new Pool()
197201
{
198-
199202
// check out a single client
200203
using client = await pool.connect()
201204

202205
// client.release() implicitly called at the end of scope
203206
}
207+
208+
{
209+
// check out a single client
210+
using client = await pool.connnect()
211+
client.destroyOnDispose = true;
212+
213+
// client.release(true) implicitly called at the end of scope
214+
}
204215
```
205216

217+
If you want the client to be destroyed instead of being returned to the pool at the end of the scope, (i.e. calling `client.release(true)` at the end of the scope), set the `destroyOnRelease` property to `true`.
218+
206219
<Alert>
207220
<div>
208221
You <strong>must</strong> release a client when you are finished with it.

packages/pg-pool/index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -342,8 +342,9 @@ class Pool extends EventEmitter {
342342
client.release = this._releaseOnce(client, idleListener)
343343

344344
if (Symbol.dispose) {
345+
client.destroyOnDispose = false
345346
client[Symbol.dispose] = function () {
346-
this.release()
347+
this.release(this.destroyOnDispose)
347348
}
348349
}
349350

packages/pg-pool/test/disposable-clients/using.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,21 @@ it('supports releasing clients via `using`', async () => {
1818

1919
await pool.end()
2020
})
21+
22+
it('supports destroying clients via `using`', async () => {
23+
const pool = new Pool({ max: 1 })
24+
expect(pool.totalCount).to.eql(0)
25+
26+
{
27+
using client = await pool.connect()
28+
client.destroyOnDispose = true
29+
expect(pool.totalCount).to.eql(1)
30+
expect(pool.idleCount).to.eql(0)
31+
await client.query('SELECT NOW()')
32+
}
33+
34+
expect(pool.totalCount).to.eql(0)
35+
expect(pool.idleCount).to.eql(0)
36+
37+
await pool.end()
38+
})

0 commit comments

Comments
 (0)