go data_error ai_generated true

error: sql: transaction has already been committed or rolled back

ID: go/database-sql-transaction-commit-before-rollback

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2025-06-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active
1.21 active

Root Cause

Attempting to commit or rollback a transaction that has already been finalized, often due to double call or logic error.

generic

中文

尝试提交或回滚已最终确定的事务,通常由于重复调用或逻辑错误。

Workarounds

  1. 95% success Use a helper function to manage transaction lifecycle
    func withTx(db *sql.DB, fn func(*sql.Tx) error) error {
        tx, err := db.Begin()
        if err != nil { return err }
        defer tx.Rollback()
        if err := fn(tx); err != nil { return err }
        return tx.Commit()
    }

Dead Ends

Common approaches that don't work:

  1. Calling Rollback after Commit in defer 80% fail

    Defer executes after Commit, causing panic; use flag to check.