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

feat: add string scan support for JSONRawMessage #12

Merged
merged 1 commit into from
Dec 19, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading