Skip to content

Commit

Permalink
feat: add string scan support for JSONRawMessage
Browse files Browse the repository at this point in the history
Now JSONRawMessage accepts both byte slice and string as source, improving the flexibility. Updated corresponding unit tests to reflect this change.
  • Loading branch information
lefinal committed Dec 19, 2023
1 parent 8590d9c commit e744f76
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
12 changes: 8 additions & 4 deletions json_raw_message.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"database/sql/driver"
"encoding/json"
"fmt"
"reflect"
)

// JSONRawMessage holds a json.RawMessage. Keep in mind, that the JSON NULL
Expand Down Expand Up @@ -53,9 +52,14 @@ func (rm *JSONRawMessage) Scan(src any) error {
}
rm.Valid = true
// Copy bytes.
srcBytes, ok := src.([]byte)
if !ok {
return fmt.Errorf("cannot convert to byte slice: %s", reflect.TypeOf(src).String())
var srcBytes []byte
switch src := src.(type) {
case []byte:
srcBytes = src
case string:
srcBytes = []byte(src)
default:
return fmt.Errorf("unsupported source value type: %T", src)
}
b := make([]byte, len(srcBytes))
copy(b, srcBytes)
Expand Down
13 changes: 11 additions & 2 deletions json_raw_message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,11 @@ func (suite *JSONRawMessageScanSuite) TestJSONNull() {

func (suite *JSONRawMessageScanSuite) TestUnexpectedValue() {
var rm JSONRawMessage
err := rm.Scan("I'm not a byte slice.")
err := rm.Scan(1234)
suite.Error(err, "should fail")
}

func (suite *JSONRawMessageScanSuite) TestOK() {
func (suite *JSONRawMessageScanSuite) TestOKByteSlice() {
v := json.RawMessage(`{"meow":"woof"}`)
var rm JSONRawMessage
err := rm.Scan([]byte(v))
Expand All @@ -123,6 +123,15 @@ func (suite *JSONRawMessageScanSuite) TestOK() {
suite.Equal(v, rm.RawMessage, "should scan correct value")
}

func (suite *JSONRawMessageScanSuite) TestOKString() {
v := json.RawMessage(`{"meow":"woof"}`)
var rm JSONRawMessage
err := rm.Scan(string(v))
suite.Require().NoError(err, "should not fail")
suite.True(rm.Valid, "should be valid")
suite.Equal(v, rm.RawMessage, "should scan correct value")
}

func TestJSONRawMessage_Scan(t *testing.T) {
suite.Run(t, new(JSONRawMessageScanSuite))
}
Expand Down

0 comments on commit e744f76

Please sign in to comment.