github.com/acoshift/pgsql@v0.15.3/json_test.go (about) 1 package pgsql_test 2 3 import ( 4 "testing" 5 6 "github.com/stretchr/testify/assert" 7 8 "github.com/acoshift/pgsql" 9 ) 10 11 func TestJSON(t *testing.T) { 12 t.Parallel() 13 14 db := open(t) 15 defer db.Close() 16 17 _, err := db.Exec(` 18 drop table if exists test_pgsql_json; 19 create table test_pgsql_json ( 20 id int primary key, 21 value json 22 ); 23 `) 24 if !assert.NoError(t, err) { 25 return 26 } 27 defer db.Exec(`drop table test_pgsql_json`) 28 29 var obj struct { 30 A string 31 B int 32 } 33 34 obj.A = "test" 35 obj.B = 7 36 37 var ok bool 38 err = db.QueryRow(` 39 insert into test_pgsql_json (id, value) 40 values (1, $1) 41 returning value is not null 42 `, pgsql.JSON(&obj)).Scan(&ok) 43 assert.NoError(t, err) 44 assert.True(t, ok) 45 46 obj.A = "" 47 obj.B = 0 48 err = db.QueryRow(` 49 select value 50 from test_pgsql_json 51 where id = 1 52 `).Scan(pgsql.JSON(&obj)) 53 if !assert.NoError(t, err) { 54 return 55 } 56 assert.Equal(t, "test", obj.A) 57 assert.Equal(t, 7, obj.B) 58 59 obj.A = "" 60 obj.B = 0 61 err = db.QueryRow(`select null`).Scan(pgsql.JSON(&obj)) 62 assert.NoError(t, err) 63 }