go runtime_error ai_generated true

sql: transaction has already been committed or rolled back

ID: go/database-sql-tx-commit-rollback

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-03-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.14 active
1.18 active

Root Cause

Calling Commit() or Rollback() on a transaction that has already been finalized, leading to an error.

generic

中文

对已最终确定的事务调用 Commit() 或 Rollback(),导致错误。

Workarounds

  1. 90% success
    Use defer with a check: defer func() { if err := tx.Rollback(); err != sql.ErrTxDone { log.Fatal(err) } }()
  2. 85% success
    Track transaction state with a boolean: committed := false; if err := tx.Commit(); err == nil { committed = true }

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Transaction state is already final; continuing may lead to data inconsistency.

  2. 90% fail

    Rollback will also fail because the transaction is already done.