feat(tx): add WithTxValue for transactional return values
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>
This commit is contained in:
+40
@@ -0,0 +1,40 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user