08f8387856
WithTxValue runs a callback inside a transaction and returns its result, with rollback on error. Includes tests and documentation updates. Co-authored-by: Cursor <cursoragent@cursor.com>
41 lines
877 B
Go
41 lines
877 B
Go
package dbx
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestWithTxValue_ReturnsResult(t *testing.T) {
|
|
db := openTestDB(t)
|
|
|
|
result, err := WithTxValue(context.Background(), db, func(tx QueryExec) (int, error) {
|
|
return 42, nil
|
|
})
|
|
require.NoError(t, err)
|
|
assert.Equal(t, 42, result)
|
|
}
|
|
|
|
func TestWithTxValue_RollbackOnError(t *testing.T) {
|
|
db := openTestDB(t)
|
|
fail := errors.New("fail")
|
|
|
|
_, err := WithTxValue(context.Background(), db, func(tx QueryExec) (int, error) {
|
|
return 0, fail
|
|
})
|
|
assert.ErrorIs(t, err, fail)
|
|
}
|
|
|
|
func TestWithTxValue_CancelledContext(t *testing.T) {
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
cancel()
|
|
|
|
_, err := WithTxValue(ctx, openTestDB(t), func(tx QueryExec) (int, error) {
|
|
return 1, nil
|
|
})
|
|
assert.ErrorIs(t, err, context.Canceled)
|
|
}
|