github.com/jxskiss/gopkg@v0.17.3/sqlutil/types_test.go (about) 1 package sqlutil 2 3 import ( 4 "database/sql" 5 "database/sql/driver" 6 "encoding/json" 7 "testing" 8 9 "github.com/stretchr/testify/assert" 10 11 "github.com/jxskiss/gopkg/gemap" 12 ) 13 14 func TestTypes(t *testing.T) { 15 var testcases = []struct { 16 a driver.Valuer 17 b sql.Scanner 18 }{ 19 { 20 a: &JSON{Map: gemap.Map{"a": "1", "b": float64(2), "c": []interface{}{"a", "b", "c"}}}, 21 b: &JSON{}, 22 }, 23 } 24 25 for _, tc := range testcases { 26 buf, err := tc.a.Value() 27 assert.Nil(t, err) 28 assert.NotNil(t, buf) 29 30 err = tc.b.Scan(buf) 31 assert.Nil(t, err) 32 assert.Equal(t, tc.a.(*JSON).GetString("a"), "1") 33 assert.Equal(t, tc.a.(*JSON).GetFloat64("b"), float64(2)) 34 assert.Equal(t, tc.a.(*JSON).MustGet("c"), tc.b.(*JSON).MustGet("c")) 35 } 36 } 37 38 type Record struct { 39 ID int64 `json:"id" db:"db"` // bigint unsigned not null primary_key 40 Column1 string `json:"column1" db:"column1"` // varchar(32) not null 41 Extra LazyBinary `json:"extra" db:"extra"` // blob 42 } 43 44 func (p *Record) GetExtra() (map[string]string, error) { 45 unmarshaler := func(b []byte) (interface{}, error) { 46 var out = map[string]string{} 47 var err error 48 if len(b) > 0 { 49 err = json.Unmarshal(b, &out) 50 } 51 return out, err 52 } 53 54 extra, err := p.Extra.Get(unmarshaler) 55 if err != nil { 56 return nil, err 57 } 58 return extra.(map[string]string), nil 59 } 60 61 func (p *Record) SetExtra(extra map[string]string) { 62 buf, _ := json.Marshal(extra) 63 p.Extra.Set(buf, extra) 64 } 65 66 func TestLazyBinary(t *testing.T) { 67 extra := map[string]string{ 68 "a": "123", 69 "b": "234", 70 "c": "345", 71 } 72 extraBuf, _ := json.Marshal(extra) 73 74 row := &Record{} 75 assert.Len(t, row.Extra.GetBytes(), 0) 76 _, err := row.GetExtra() 77 assert.Nil(t, err) 78 79 row.Extra.Set(extraBuf, nil) 80 assert.Len(t, row.Extra.GetBytes(), len(extraBuf)) 81 82 got1, _ := row.GetExtra() 83 got2, _ := row.GetExtra() 84 assert.Equal(t, extra, got1) 85 assert.Equal(t, extra, got2) 86 87 delete(extra, "a") 88 row.SetExtra(extra) 89 got3, _ := row.GetExtra() 90 assert.Equal(t, extra, got3) 91 92 row.Extra.Set(extraBuf, nil) 93 got4, _ := row.GetExtra() 94 assert.Len(t, got4, 3) 95 } 96 97 func TestJSONMarshal(t *testing.T) { 98 data := JSON{ 99 Map: map[string]interface{}{ 100 "a": 123, 101 }, 102 } 103 want := `{"a":123}` 104 got, err := data.MarshalJSON() 105 assert.Nil(t, err) 106 assert.Equal(t, want, string(got)) 107 108 data = JSON{} 109 want = "null" 110 got, err = data.MarshalJSON() 111 assert.Nil(t, err) 112 assert.Equal(t, want, string(got)) 113 } 114 115 func TestJSONUnmarshal(t *testing.T) { 116 data := []byte(`{"a":123}`) 117 obj := JSON{} 118 err := obj.UnmarshalJSON(data) 119 assert.Nil(t, err) 120 assert.Equal(t, gemap.Map{"a": 123.0}, obj.Map) 121 122 data = []byte("null") 123 obj = JSON{} 124 err = obj.UnmarshalJSON(data) 125 assert.Nil(t, err) 126 assert.Nil(t, obj.Map) 127 }