Do you need to call transaction.RollBack if transaction.Commit fails for SQLX with posgres connection

huangapple go评论77阅读模式
英文:

Do you need to call transaction.RollBack if transaction.Commit fails for SQLX with posgres connection

问题

我正在使用https://pkg.go.dev/github.com/jmoiron/sqlx@v1.2.0来连接到PostgreSQL并执行查询。如果我的事务提交失败,我应该执行transaction.Rollback吗?

示例:

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

// 然后使用tx引用进行一些查询

在提交事务之后,我们应该使用哪种方法:
方法1:

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

还是应该使用方法2:

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

I am using

https://pkg.go.dev/github.com/jmoiron/sqlx@v1.2.0

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
   }
}

答案1

得分: 3

sqlx Tx类型是对sql.Tx的封装,该类型的文档说明如下:

>在调用Commit或Rollback之后,事务上的所有操作都会失败并返回ErrTxDone。

因此,在调用Commit之后再调用Rollback(无论成功与否)都不会产生影响(并且会返回ErrTxDone)。你可以在这里的代码中看到这一点。这意味着在已经调用Commit之后没有理由再调用Rollback(所以使用第一种方法)。

英文:

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

huangapple
  • 本文由 发表于 2022年11月1日 02:04:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/74267427.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定