mirror of
https://github.com/1f349/lavender.git
synced 2024-12-22 23:54:10 +00:00
27 lines
502 B
Go
27 lines
502 B
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
)
|
|
|
|
var errCannotOpenTransactionWithoutSqlDB = errors.New("cannot open transaction without sql.DB")
|
|
|
|
func (q *Queries) UseTx(ctx context.Context, cb func(tx *Queries) error) error {
|
|
sqlDB, ok := q.db.(*sql.DB)
|
|
if !ok {
|
|
panic(errCannotOpenTransactionWithoutSqlDB)
|
|
}
|
|
tx, err := sqlDB.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
err = cb(q.WithTx(tx))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|