• features
  • 事务

要使用 node-postgres 执行事务,你只需通过客户端自己执行 BEGIN / COMMIT / ROLLBACK 查询即可。由于 node-postgres 力求底层和不有态度,因此它不提供任何专门围绕事务的高级抽象。

¥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.

⚠️

mustsame 客户端实例用于事务中的所有语句。PostgreSQL 将事务隔离到各个客户端。这意味着如果你使用 pool.query 方法初始化或使用事务,你将遇到问题。不要将事务与 pool.query 方法一起使用。

¥You must use the same 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 pool.query method you will have problems. Do not use transactions with the pool.query method.

示例

¥Examples

import pg from 'pg'
const { Pool } = 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()
}
Last updated on August 24, 2024