node-postgres/docs/pages/features/transactions.mdx
Brian C 0c1629bea2
Update docs - add ESM info
* Update docs - start

* Add logo & discord

* Start updating docs for esm style imports

* Update docs with logo & info on pooling

* Update more import statements

---------

Co-authored-by: Brian Carlson <brian.carlson@getcruise.com>
2025-04-23 16:46:21 -05:00

40 lines
1.3 KiB
Plaintext

---
title: Transactions
---
import { Alert } from '/components/alert.tsx'
To execute a transaction with node-postgres you simply execute `BEGIN / COMMIT / ROLLBACK` queries yourself through a client. Because node-postgres strives to be low level and un-opinionated, it doesn't provide any higher level abstractions specifically around transactions.
<Alert>
You <strong>must</strong> use the <em>same</em> client instance for all statements within a transaction. PostgreSQL
isolates a transaction to individual clients. This means if you initialize or use transactions with the{' '}
<span className="code">pool.query</span> method you <strong>will</strong> have problems. Do not use transactions with
the <span className="code">pool.query</span> method.
</Alert>
## Examples
```js
import { Pool } from 'pg'
const pool = new Pool()
const client = await pool.connect()
try {
await client.query('BEGIN')
const queryText = 'INSERT INTO users(name) VALUES($1) RETURNING id'
const res = await client.query(queryText, ['brianc'])
const insertPhotoText = 'INSERT INTO photos(user_id, photo_url) VALUES ($1, $2)'
const insertPhotoValues = [res.rows[0].id, 's3.bucket.foo']
await client.query(insertPhotoText, insertPhotoValues)
await client.query('COMMIT')
} catch (e) {
await client.query('ROLLBACK')
throw e
} finally {
client.release()
}
```