8d697eda5b
Add Delete/DeleteAffected, context-aware CRUD helpers, WithTx, ContainsCol, and queryReturning deduplication for returning statements. Co-authored-by: Cursor <cursoragent@cursor.com>
81 lines
1.7 KiB
Go
81 lines
1.7 KiB
Go
package dbx
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestFetch_EmptyOnNoRows(t *testing.T) {
|
|
stmt := mockStatement{
|
|
queryContextFn: func(_ context.Context, dest any) error {
|
|
return ErrNoRows
|
|
},
|
|
}
|
|
|
|
result, err := Fetch[row](mockQueryable{}, stmt)
|
|
require.NoError(t, err)
|
|
assert.Empty(t, result)
|
|
}
|
|
|
|
func TestFetch_ReturnsRows(t *testing.T) {
|
|
stmt := mockStatement{
|
|
queryContextFn: func(_ context.Context, dest any) error {
|
|
ptr := dest.(*[]*row)
|
|
*ptr = []*row{{ID: 1}, {ID: 2}}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
result, err := Fetch[row](mockQueryable{}, stmt)
|
|
require.NoError(t, err)
|
|
assert.Len(t, result, 2)
|
|
}
|
|
|
|
func TestMustFetch_NotFound(t *testing.T) {
|
|
errNotFound := errors.New("not found")
|
|
stmt := mockStatement{
|
|
queryContextFn: func(_ context.Context, _ any) error {
|
|
return ErrNoRows
|
|
},
|
|
}
|
|
|
|
result, err := MustFetch[row](mockQueryable{}, stmt, errNotFound)
|
|
assert.Nil(t, result)
|
|
assert.ErrorIs(t, err, errNotFound)
|
|
}
|
|
|
|
func TestFetchContext_PropagatesContext(t *testing.T) {
|
|
ctx := context.WithValue(context.Background(), testContextKey{}, "ok")
|
|
var gotCtx context.Context
|
|
stmt := mockStatement{
|
|
queryContextFn: func(c context.Context, dest any) error {
|
|
gotCtx = c
|
|
ptr := dest.(*[]*row)
|
|
*ptr = []*row{{ID: 3}}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
_, err := FetchContext[row](ctx, mockQueryable{}, stmt)
|
|
require.NoError(t, err)
|
|
assert.Equal(t, ctx, gotCtx)
|
|
}
|
|
|
|
type testContextKey struct{}
|
|
|
|
func TestFetchOne_NilWhenEmpty(t *testing.T) {
|
|
stmt := mockStatement{
|
|
queryContextFn: func(_ context.Context, _ any) error {
|
|
return ErrNoRows
|
|
},
|
|
}
|
|
|
|
result, err := FetchOne[row](mockQueryable{}, stmt)
|
|
require.NoError(t, err)
|
|
assert.Nil(t, result)
|
|
}
|