Skip to content

Commit e804768

Browse files
authored
Add JSON-encoded version of NULL uniqueidentifier (#238)
* Add JSON-encoded version of NULL uniqueidentifier * as literal name according RFC 7159 * Fix test to verify that Marshal writes the correct value
1 parent d27f997 commit e804768

File tree

2 files changed

+48
-3
lines changed

2 files changed

+48
-3
lines changed

uniqueidentifier_null.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package mssql
22

33
import (
44
"database/sql/driver"
5+
"encoding/json"
56
)
67

78
type NullUniqueIdentifier struct {
@@ -63,3 +64,10 @@ func (n *NullUniqueIdentifier) UnmarshalJSON(b []byte) error {
6364
}
6465
return err
6566
}
67+
68+
func (n NullUniqueIdentifier) MarshalJSON() ([]byte, error) {
69+
if !n.Valid {
70+
return []byte("null"), nil
71+
}
72+
return json.Marshal(n.UUID)
73+
}

uniqueidentifier_null_test.go

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"database/sql"
66
"database/sql/driver"
7+
"encoding/json"
78
"fmt"
89
"reflect"
910
"testing"
@@ -210,6 +211,42 @@ func TestNullableUniqueIdentifierUnmarshalJSONNull(t *testing.T) {
210211
}
211212
}
212213

213-
var _ fmt.Stringer = NullUniqueIdentifier{}
214-
var _ sql.Scanner = &NullUniqueIdentifier{}
215-
var _ driver.Valuer = NullUniqueIdentifier{}
214+
func TestNullableUniqueIdentifierMarshalJSONNull(t *testing.T) {
215+
t.Parallel()
216+
nullUUID := NullUniqueIdentifier{
217+
UUID: [16]byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
218+
Valid: false,
219+
}
220+
221+
got, err := nullUUID.MarshalJSON()
222+
if err != nil {
223+
t.Fatal(err)
224+
}
225+
want := []byte{0x6e, 0x75, 0x6c, 0x6c} // null = %x6e.75.6c.6c
226+
if !reflect.DeepEqual(got, want) {
227+
t.Errorf("got %v; want %v", got, want)
228+
}
229+
}
230+
231+
func TestNullableUniqueIdentifierJSONMarshalNull(t *testing.T) {
232+
t.Parallel()
233+
nullUUID := NullUniqueIdentifier{
234+
UUID: [16]byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
235+
Valid: false,
236+
}
237+
238+
got, err := json.Marshal(nullUUID)
239+
if err != nil {
240+
t.Fatal(err)
241+
}
242+
want := []byte{0x6e, 0x75, 0x6c, 0x6c}
243+
if !reflect.DeepEqual(got, want) {
244+
t.Errorf("got %v; want %v", got, want)
245+
}
246+
}
247+
248+
var (
249+
_ fmt.Stringer = NullUniqueIdentifier{}
250+
_ sql.Scanner = &NullUniqueIdentifier{}
251+
_ driver.Valuer = NullUniqueIdentifier{}
252+
)

0 commit comments

Comments
 (0)