node-postgres icon indicating copy to clipboard operation
node-postgres copied to clipboard

Symbol.asyncDispose support

Open mfulton26 opened this issue 5 months ago • 3 comments

I propose support AsyncDisposable on Client (https://github.com/tc39/proposal-explicit-resource-management) so that developers can opt-into ending the connection automatically at the end of the current scope.

before

import { Client } from 'pg'
const client = new Client()
await client.connect()
 
try {
   const res = await client.query('SELECT $1::text as message', ['Hello world!'])
   console.log(res.rows[0].message) // Hello world!
} catch (err) {
   console.error(err);
} finally {
   await client.end()
}

after

import { Client } from 'pg'
await using client = new Client()
await client.connect()
 
try {
   const res = await client.query('SELECT $1::text as message', ['Hello world!'])
   console.log(res.rows[0].message) // Hello world!
} catch (err) {
   console.error(err);
}

mfulton26 avatar Jul 17 '25 20:07 mfulton26

I am totally open to this. Do you know what versions of node support this natively?

brianc avatar Jul 17 '25 20:07 brianc

Looks like 24 according to node.green (https://node.green/#ESNEXT-Stage-3-Explicit-Resource-Management-await-using). It can be used on older runtims too via polyfills. TypeScript's blog post has some exmaples and they support with the polyfills: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html

mfulton26 avatar Jul 17 '25 20:07 mfulton26

nice - I think since it uses the symbol thing too its pretty backwards compatible. If you want to do a PR I'd love to take a look. I'd rather just not support it in older versions of node vs using any sort of polyfill at this point as pg itself is unfortunately not (yet) written in typescript.

brianc avatar Jul 17 '25 20:07 brianc