我想知道 Go 如何處理失敗的資料庫事務。我的代碼看起來像:
func assert(e interface{}) {
if e != nil {
panic(e)
}
}
//the caller will handle panics
func SomeDBOperation(db *sql.DB) {
tx, err := db.Begin()
assert(err)
defer func() {
if e := recover(); e != nil {
tx.Rollback()
panic(e)
}
assert(tx.Commit())
}()
// some code that can possibly panic...
}
我可以像這樣簡化錯誤檢查:
func SomeDBOperation(db *sql.DB) {
tx, err := db.Begin()
assert(err)
defer func() { assert(tx.Commit()) }()
// some code that can possibly panic...
}
順便說一句,我正在使用 SQLite,如果任何答案是特定于資料庫的,我也想知道 MySQL 的行為。
uj5u.com熱心網友回復:
默認情況下,任何資料庫錯誤都會自動取消和回滾事務。這就是交易的目的。所以嚴格來說,在出現資料庫錯誤(即外鍵違規什么的)的情況下,沒有必要自己回滾事務。
但是,您應該始終在創建事務后立即推遲回滾。這是為了如果有任何與資料庫無關的錯誤,事務將被回滾并清理。在這種情況下,回滾已經中止的事務將是無操作的,因此無害。
這在代碼中看起來是這樣的:
func SomeDBOperation(db *sql.DB) error {
txn, err := db.Begin()
if err != nil {
return fmt.Errorf("failed to start transaction: %w", err)
}
defer txn.Rollback() // nolint:errcheck
/* ... whatever other logic and DB operations you care about */
return nil
}
uj5u.com熱心網友回復:
如果在執行任何查詢時出現錯誤,回滾 tx 很重要,否則它仍在運行并持有鎖。看看這篇文章。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/383189.html
下一篇:R:直接在服務器上創建表
