go/sqliteutil/tx.go

29 lines
405 B
Go
Raw Permalink Normal View History

2024-11-11 05:36:55 +00:00
package sqliteutil
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
// This is a convenience function to run a function within a transaction.
func WithTx(db *sql.DB, fn func(*sql.Tx) error) error {
// Start a transaction.
tx, err := db.Begin()
if err != nil {
return err
}
err = fn(tx)
if err == nil {
err = tx.Commit()
}
if err != nil {
_ = tx.Rollback()
}
return err
}