Skip to content

Commit

Permalink
Merge remote-tracking branch 'pakohan/master' into NullJSONText
Browse files Browse the repository at this point in the history
  • Loading branch information
Taik committed Nov 9, 2016
2 parents 5f97679 + c52770c commit 27160f2
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 6 deletions.
26 changes: 20 additions & 6 deletions types/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,14 @@ func (g *GzippedText) Scan(src interface{}) error {
// implements `Unmarshal`, which unmarshals the json within to an interface{}
type JSONText json.RawMessage

// MarshalJSON returns j as the JSON encoding of j.
func (j JSONText) MarshalJSON() ([]byte, error) {
return j, nil
var _EMPTY_JSON = JSONText("{}")

// MarshalJSON returns the *j as the JSON encoding of j.
func (j *JSONText) MarshalJSON() ([]byte, error) {
if len(*j) == 0 {
*j = _EMPTY_JSON
}
return *j, nil
}

// UnmarshalJSON sets *j to a copy of data
Expand All @@ -86,11 +91,17 @@ func (j JSONText) Value() (driver.Value, error) {
// Scan stores the src in *j. No validation is done.
func (j *JSONText) Scan(src interface{}) error {
var source []byte
switch src.(type) {
switch t := src.(type) {
case string:
source = []byte(src.(string))
source = []byte(t)
case []byte:
source = src.([]byte)
if len(t) == 0 {
source = _EMPTY_JSON
} else {
source = t
}
case nil:
*j = _EMPTY_JSON
default:
return errors.New("Incompatible type for JSONText")
}
Expand All @@ -100,6 +111,9 @@ func (j *JSONText) Scan(src interface{}) error {

// Unmarshal unmarshal's the json in j to v, as in json.Unmarshal.
func (j *JSONText) Unmarshal(v interface{}) error {
if len(*j) == 0 {
*j = _EMPTY_JSON
}
return json.Unmarshal([]byte(*j), v)
}

Expand Down
22 changes: 22 additions & 0 deletions types/types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,28 @@ func TestJSONText(t *testing.T) {
if err == nil {
t.Errorf("Was expecting invalid json to fail!")
}

j = JSONText("")
v, err = j.Value()
if err != nil {
t.Errorf("Was not expecting an error")
}

err = (&j).Scan(v)
if err != nil {
t.Errorf("Was not expecting an error")
}

j = JSONText(nil)
v, err = j.Value()
if err != nil {
t.Errorf("Was not expecting an error")
}

err = (&j).Scan(v)
if err != nil {
t.Errorf("Was not expecting an error")
}
}

func TestBitBool(t *testing.T) {
Expand Down

0 comments on commit 27160f2

Please sign in to comment.