go/sqliteutil/tx.go
2024-11-11 06:36:55 +01:00

29 lines
405 B
Go

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
}