Skip to content

Commit

Permalink
Add dbo.Set
Browse files Browse the repository at this point in the history
  • Loading branch information
christianezeani committed Oct 29, 2024
1 parent b4df8c1 commit 954a33f
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 2 deletions.
44 changes: 44 additions & 0 deletions dbo/set.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package dbo

import (
"database/sql/driver"
"encoding/json"
"fmt"

"github.com/Cyberpull/gokit"
)

type Set[T gokit.SetConstraint] struct {
Data []T
}

func (x *Set[T]) Scan(value any) (err error) {
switch data := value.(type) {
case []T:
x.Data = data

default:
x.Data, err = gokit.Split[T](fmt.Sprint(value), ",")
}

return
}

func (x Set[T]) Value() (value driver.Value, err error) {
value = gokit.Join(",", x.Data...)
return
}

func (x *Set[T]) UnmarshalJSON(b []byte) error {
var value T

if err := json.Unmarshal(b, &value); err != nil {
return err
}

return x.Scan(value)
}

func (x Set[T]) MarshalJSON() ([]byte, error) {
return json.Marshal(x.Data)
}
4 changes: 2 additions & 2 deletions set.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func In[T comparable](value T, entries ...T) bool {
return false
}

func JoinFunc(delim string, entries []any, callbacks ...JoinEntryFunc) string {
func JoinFunc[T any](delim string, entries []T, callbacks ...JoinEntryFunc) string {
var buff bytes.Buffer

for _, entry := range entries {
Expand Down Expand Up @@ -56,7 +56,7 @@ func JoinFunc(delim string, entries []any, callbacks ...JoinEntryFunc) string {
return buff.String()
}

func Join(delim string, entries ...any) string {
func Join[T any](delim string, entries ...T) string {
return JoinFunc(delim, entries)
}

Expand Down
31 changes: 31 additions & 0 deletions tests/dbo_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package tests

import (
"testing"

"github.com/Cyberpull/gokit/dbo"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
)

type DBOTestSuite struct {
suite.Suite
}

func (x *DBOTestSuite) TestSet() {
var data dbo.Set[string]

err := data.Scan("a,b,c,d,e")
require.NoError(x.T(), err)
require.EqualValues(x.T(), []string{"a", "b", "c", "d", "e"}, data.Data)

value, err := data.Value()
require.NoError(x.T(), err)
require.EqualValues(x.T(), "a,b,c,d,e", value)
}

// ===============================

func TestDBO(t *testing.T) {
suite.Run(t, new(DBOTestSuite))
}

0 comments on commit 954a33f

Please sign in to comment.