File tree Expand file tree Collapse file tree 2 files changed +57
-0
lines changed
Expand file tree Collapse file tree 2 files changed +57
-0
lines changed Original file line number Diff line number Diff line change @@ -121,6 +121,32 @@ func (j JSONText) String() string {
121121 return string (j )
122122}
123123
124+ // NullJSONText represents a JSONText that may be null.
125+ // NullJSONText implements the scanner interface so
126+ // it can be used as a scan destination, similar to NullString.
127+ type NullJSONText struct {
128+ JSONText
129+ Valid bool // Valid is true if JSONText is not NULL
130+ }
131+
132+ // Scan implements the Scanner interface.
133+ func (n * NullJSONText ) Scan (value interface {}) error {
134+ if value == nil {
135+ n .JSONText , n .Valid = _EMPTY_JSON , false
136+ return nil
137+ }
138+ n .Valid = true
139+ return n .JSONText .Scan (value )
140+ }
141+
142+ // Value implements the driver Valuer interface.
143+ func (n * NullJSONText ) Value () (driver.Value , error ) {
144+ if ! n .Valid {
145+ return nil , nil
146+ }
147+ return n .JSONText .Value ()
148+ }
149+
124150// BitBool is an implementation of a bool for the MySQL type BIT(1).
125151// This type allows you to avoid wasting an entire byte for MySQL's boolean type TINYINT.
126152type BitBool bool
Original file line number Diff line number Diff line change @@ -63,6 +63,37 @@ func TestJSONText(t *testing.T) {
6363 }
6464}
6565
66+ func TestNullJSONText (t * testing.T ) {
67+ j := NullJSONText {}
68+ err := j .Scan (`{"foo": 1, "bar": 2}` )
69+ if err != nil {
70+ t .Errorf ("Was not expecting an error" )
71+ }
72+ v , err := j .Value ()
73+ if err != nil {
74+ t .Errorf ("Was not expecting an error" )
75+ }
76+ err = (& j ).Scan (v )
77+ if err != nil {
78+ t .Errorf ("Was not expecting an error" )
79+ }
80+ m := map [string ]interface {}{}
81+ j .Unmarshal (& m )
82+
83+ if m ["foo" ].(float64 ) != 1 || m ["bar" ].(float64 ) != 2 {
84+ t .Errorf ("Expected valid json but got some garbage instead? %#v" , m )
85+ }
86+
87+ j = NullJSONText {}
88+ err = j .Scan (nil )
89+ if err != nil {
90+ t .Errorf ("Was not expecting an error" )
91+ }
92+ if j .Valid != false {
93+ t .Errorf ("Expected valid to be false, but got true" )
94+ }
95+ }
96+
6697func TestBitBool (t * testing.T ) {
6798 // Test true value
6899 var b BitBool = true
You can’t perform that action at this time.
0 commit comments