Skip to content
This repository was archived by the owner on Jun 12, 2024. It is now read-only.

Commit fe27e62

Browse files
authored
Allow scanning string and nil values from the db (#21)
**What** - Expand scan support so that nil and string values are supported Signed-off-by: Lucas Roesler <[email protected]>
1 parent 2a90cca commit fe27e62

File tree

2 files changed

+29
-8
lines changed

2 files changed

+29
-8
lines changed

pkg/db/serialization/json_blob.go

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ package serialization
33
import (
44
"database/sql/driver"
55
"encoding/json"
6-
"errors"
6+
"fmt"
77
)
88

99
// JSONBlob returns an Serializable using json to []byte serialization
@@ -21,11 +21,17 @@ func (b jsonBlob) GetData() interface{} {
2121
}
2222

2323
func (b jsonBlob) Scan(src interface{}) error {
24-
bs, ok := src.([]byte)
25-
if !ok {
26-
return errors.New("source must be a byte slice")
24+
switch value := src.(type) {
25+
case nil:
26+
b.data = nil
27+
return nil
28+
case []byte:
29+
return json.Unmarshal(value, b.data)
30+
case string:
31+
return json.Unmarshal([]byte(value), b.data)
32+
default:
33+
return fmt.Errorf("unknown json object type %T", src)
2734
}
28-
return json.Unmarshal(bs, b.data)
2935
}
3036

3137
func (b jsonBlob) Value() (driver.Value, error) {

pkg/db/serialization/json_blob_test.go

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package serialization
22

33
import (
44
"testing"
5+
"time"
56

67
"github.com/stretchr/testify/require"
78
)
@@ -15,13 +16,27 @@ func TestJSONBlobScan(t *testing.T) {
1516
err string
1617
}{
1718
{
18-
name: "Populates the underlying struct with values when source is valid",
19+
name: "Populates the underlying struct with values when source is byte slice",
1920
data: &struct{ Name string }{},
2021
src: []byte(`{"Name":"value"}`),
2122
expected: &struct {
2223
Name string
2324
}{Name: "value"},
2425
},
26+
{
27+
name: "Populates the underlying struct with values when source is string",
28+
data: &struct{ Name string }{},
29+
src: `{"Name":"value"}`,
30+
expected: &struct {
31+
Name string
32+
}{Name: "value"},
33+
},
34+
{
35+
name: "Support scanning nil",
36+
data: &struct{ Name string }{},
37+
src: nil,
38+
expected: &struct{ Name string }{},
39+
},
2540
{
2641
name: "Returns error when the source is not a valid JSON",
2742
data: &struct{ Name string }{},
@@ -34,11 +49,11 @@ func TestJSONBlobScan(t *testing.T) {
3449
{
3550
name: "Returns error when the source is not a byte slice",
3651
data: &struct{ Name string }{},
37-
src: `{"Name":"value"}`,
52+
src: time.Now(),
3853
expected: &struct {
3954
Name string
4055
}{Name: "value"},
41-
err: "source must be a byte slice",
56+
err: "unknown json object type time.Time",
4257
},
4358
}
4459

0 commit comments

Comments
 (0)