satellite/satellitedb: add utility for converting slices

Change-Id: I2654a9ef7c58016bd5af923c66f5f31819ab9b9d
This commit is contained in:
Egon Elbre 2023-06-01 14:53:44 +03:00 committed by Storj Robot
parent 52598d1545
commit 52cefb816c
3 changed files with 59 additions and 10 deletions

View File

@ -398,13 +398,3 @@ func (dbc *satelliteDBCollectionTesting) ProductionMigration() *migrate.Migratio
func (dbc *satelliteDBCollectionTesting) TestMigration() *migrate.Migration { func (dbc *satelliteDBCollectionTesting) TestMigration() *migrate.Migration {
return dbc.getByName("").TestMigration() 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)
}
}

View File

@ -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
}

View File

@ -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)
}