[go: nahoru, domu]

Skip to content

Commit

Permalink
add simple value and scan (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentserpoul authored and rs committed Mar 31, 2019
1 parent cc5ec57 commit bd5a590
Show file tree
Hide file tree
Showing 3 changed files with 128 additions and 0 deletions.
4 changes: 4 additions & 0 deletions b/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Bytes storage

This subpackage is there to allow storage of XIDs in a binary format in, for example, a database.
It allows some data size optimisation as the 12 bytes will be smaller to store than a string.
38 changes: 38 additions & 0 deletions b/id.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package xidb

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

"github.com/rs/xid"
)

type ID struct {
xid.ID
}

// Value implements the driver.Valuer interface.
func (id ID) Value() (driver.Value, error) {
if id.ID.IsNil() {
return nil, nil
}
return id.ID[:], nil
}

// Scan implements the sql.Scanner interface.
func (id *ID) Scan(value interface{}) (err error) {
switch val := value.(type) {
case []byte:
i, err := xid.FromBytes(val)
if err != nil {
return err
}
*id = ID{ID: i}
return nil
case nil:
*id = ID{ID: xid.NilID()}
return nil
default:
return fmt.Errorf("xid: scanning unsupported type: %T", value)
}
}
86 changes: 86 additions & 0 deletions b/id_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package xidb

import (
"reflect"
"testing"

"github.com/rs/xid"
)

func TestIDValue(t *testing.T) {
i, _ := xid.FromString("9m4e2mr0ui3e8a215n4g")

tests := []struct {
name string
id ID
expectedVal interface{}
}{
{
name: "non nil id",
id: ID{ID: i},
expectedVal: i.Bytes(),
},
{
name: "nil id",
id: ID{ID: xid.NilID()},
expectedVal: nil,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, _ := tt.id.Value()
if !reflect.DeepEqual(got, tt.expectedVal) {
t.Errorf("wanted %v, got %v", tt.expectedVal, got)
}
})
}
}

func TestIDScan(t *testing.T) {
i, _ := xid.FromString("9m4e2mr0ui3e8a215n4g")

tests := []struct {
name string
val interface{}
expectedID ID
expectedErr bool
}{
{
name: "bytes id",
val: i.Bytes(),
expectedID: ID{ID: i},
},
{
name: "nil id",
val: nil,
expectedID: ID{ID: xid.NilID()},
},
{
name: "wrong bytes",
val: []byte{0x01},
expectedErr: true,
},
{
name: "unknown type",
val: 1,
expectedErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
id := &ID{}
err := id.Scan(tt.val)
if (err != nil) != tt.expectedErr {
t.Errorf("error expected: %t, got %t", tt.expectedErr, (err != nil))
}
if err == nil {
if !reflect.DeepEqual(id.ID, tt.expectedID.ID) {
t.Errorf("wanted %v, got %v", tt.expectedID, id)
}
}

})
}
}

0 comments on commit bd5a590

Please sign in to comment.