Skip to content

Error: Transaction client already released

golergka edited this page May 8, 2021 · 1 revision

The purpose of this package is to make sure that you don't run queries outside of the transaction. To ensure this, we use a proxy client that employs a disposable pattern. After transaction that is has been created for has been committed or rolled back, the client is released, and all subsequent attempts to make any queries with it will end up with this error.

When you get this error, it means that your code tried to run a query after the transaction has been ended. This error is triggered the moment your code launches a query. Most likely, you got this error because your forgot to await for some async operation, for example, like this:

async function doSomething(db: PoolClient) {
  // Assume that this will take longer than the postgres query with an error below
  await externalApiCall()
  
  // This will immediately trigger this error, because the client will have already been released
  await pg.query(`SELECT 1`)
}

async function useTransaction(pg: Pool) {
  await tx(pg, async (db) => {
    // Here's the error — you launched an operation, but forgot to await on it
    doSomething(db)
    
    // When postgresql replies with SQL error, this terminates the transaction and releases the client
    db.query(`this query has an error`)
  })
}
Clone this wiki locally