diff --git a/satellite/satellitedb/database.go b/satellite/satellitedb/database.go index 498b0df53..aada891a1 100644 --- a/satellite/satellitedb/database.go +++ b/satellite/satellitedb/database.go @@ -398,13 +398,3 @@ func (dbc *satelliteDBCollectionTesting) ProductionMigration() *migrate.Migratio func (dbc *satelliteDBCollectionTesting) TestMigration() *migrate.Migration { return dbc.getByName("").TestMigration() } - -func withRows(rows tagsql.Rows, err error) func(func(tagsql.Rows) error) error { - return func(callback func(tagsql.Rows) error) error { - if err != nil { - return err - } - err := callback(rows) - return errs.Combine(rows.Err(), rows.Close(), err) - } -} diff --git a/satellite/satellitedb/util.go b/satellite/satellitedb/util.go new file mode 100644 index 000000000..6e21f395e --- /dev/null +++ b/satellite/satellitedb/util.go @@ -0,0 +1,36 @@ +// Copyright (C) 2023 Storj Labs, Inc. +// See LICENSE for copying information. + +package satellitedb + +import ( + "github.com/zeebo/errs" + + "storj.io/private/tagsql" +) + +// withRows ensures that rows get properly closed after the callback finishes. +func withRows(rows tagsql.Rows, err error) func(func(tagsql.Rows) error) error { + return func(callback func(tagsql.Rows) error) error { + if err != nil { + return err + } + err := callback(rows) + return errs.Combine(rows.Err(), rows.Close(), err) + } +} + +// convertSlice converts xs by applying fn to each element. +// If there's an error during conversion, the function +// returns an empty slice and the error. +func convertSlice[In, Out any](xs []In, fn func(In) (Out, error)) ([]Out, error) { + rs := make([]Out, len(xs)) + for i := range xs { + var err error + rs[i], err = fn(xs[i]) + if err != nil { + return nil, err + } + } + return rs, nil +} diff --git a/satellite/satellitedb/util_test.go b/satellite/satellitedb/util_test.go new file mode 100644 index 000000000..002c5835a --- /dev/null +++ b/satellite/satellitedb/util_test.go @@ -0,0 +1,23 @@ +// Copyright (C) 2023 Storj Labs, Inc. +// See LICENSE for copying information. + +package satellitedb + +import ( + "strconv" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestConvertSlice(t *testing.T) { + good := []string{"1", "2", "3", "4"} + out, err := convertSlice(good, strconv.Atoi) + require.NoError(t, err) + require.Equal(t, []int{1, 2, 3, 4}, out) + + bad := []string{"1", "bad", "asdf", ""} + out, err = convertSlice(bad, strconv.Atoi) + require.Error(t, err) + require.Nil(t, out) +}