Applications and operations
Run an application transaction
Keep several queries on one checked-out client and always commit, roll back, and release it.
8 minute lesson
~~~
A transaction belongs to one connection. Check out one client and use it for every statement:
const client = await pool.connect()
try {
await client.query('BEGIN')
const note = await client.query(
'INSERT INTO app.notes (title) VALUES ($1) RETURNING id',
['Plan the week']
)
await client.query(
'INSERT INTO app.note_tags (note_id, tag_id) VALUES ($1, $2)',
[note.rows[0].id, 1]
)
await client.query('COMMIT')
} catch (error) {
await client.query('ROLLBACK')
throw error
} finally {
client.release()
}
Do not call pool.query() inside this transaction. The pool may choose another connection.
Lesson completed