Home > Back-end >  Do you need to call transaction.RollBack if transaction.Commit fails for SQLX with posgres connectio
Do you need to call transaction.RollBack if transaction.Commit fails for SQLX with posgres connectio

Time:11-01

I am using

https://pkg.go.dev/github.com/jmoiron/[email protected]

to connect to postgres and do queries. Should I do transaction.Rollback if my transaction.Commit fails

Example

    tx, err := appState.PgConn.Beginx()
    if err != nil {
        return err
    }

    // then some queries using this tx reference

After that when we commit the transaction should we do .. Approach 1

err:= tx.Commit()
if err != nil {
    return err;
}

or should we use Approach 2

err1 := tx.Commit()
if err1 != nil {
   err2:= tx.Rollback()
   if err2 !=nil {
      return err2
   }
}

CodePudding user response:

The sqlx Tx type is a wrapper around sql.Tx and the docs for that type state:

After a call to Commit or Rollback, all operations on the transaction fail with ErrTxDone.

So calling RollBack after Commit (whether successful or not) will have no impact (and will return ErrTxDone). You can see this in the code here. This means that there is no reason to call Rollback after already calling Commit (so use Approach 1).

  • Related