Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixed empty slice bug on slices.Float #798

Merged
merged 1 commit into from Nov 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 18 additions & 7 deletions slices/float.go
Expand Up @@ -27,8 +27,9 @@ func (f *Float) Scan(src interface{}) error {
default:
return fmt.Errorf("scan source was not []byte nor string but %T", src)
}
*f = strToFloat(str)
return nil
v, err := strToFloat(str)
*f = v
return err
}

// Value implements the driver.Valuer interface.
Expand Down Expand Up @@ -56,12 +57,22 @@ func (f *Float) UnmarshalText(text []byte) error {
return nil
}

func strToFloat(s string) []float64 {
func strToFloat(s string) ([]float64, error) {
r := strings.Trim(s, "{}")
a := make([]float64, 0, 10)
for _, t := range strings.Split(r, ",") {
i, _ := strconv.ParseFloat(t, 64)
a = append(a, i)

elems := strings.Split(r, ",")
if len(elems) == 1 && elems[0] == "" {
return a, nil
}
return a

for _, t := range elems {
f, err := strconv.ParseFloat(t, 64)
if err != nil {
return nil, err
}
a = append(a, f)
}

return a, nil
}
30 changes: 30 additions & 0 deletions slices/float_test.go
@@ -0,0 +1,30 @@
package slices

import (
"testing"

"github.com/stretchr/testify/require"
)

func Test_Float_Scan(t *testing.T) {
r := require.New(t)
t.Run("empty slice", func(t *testing.T) {
in := "{}"
v := &Float{}
r.NoError(v.Scan(in))
r.Len(*v, 0)
})

t.Run("non-empty slice", func(t *testing.T) {
in := "{3.14,9.999}"
v := &Float{}
r.NoError(v.Scan(in))
r.Equal([]float64(*v), []float64{3.14, 9.999})
})

t.Run("invalid entry", func(t *testing.T) {
in := "{44,word}"
v := &Float{}
r.Error(v.Scan(in))
})
}
2 changes: 2 additions & 0 deletions slices_test.go
Expand Up @@ -44,6 +44,7 @@ func (s *PostgreSQLSuite) Test_Int() {
err = tx.Reload(c)
r.NoError(err)
r.Equal(slices.Int{1, 2, 3}, c.Int)
r.Equal(slices.Float{}, c.Float)
})
}

Expand All @@ -59,6 +60,7 @@ func (s *PostgreSQLSuite) Test_Float() {

err = tx.Reload(c)
r.NoError(err)
r.Equal(slices.Int{}, c.Int)
r.Equal(slices.Float{1.0, 2.1, 3.2}, c.Float)
})
}