github.com/ncruces/go-sqlite3@v0.15.1-0.20240520133447-53eef1510ff0/tests/json_test.go (about) 1 package tests 2 3 import ( 4 "context" 5 "encoding/json" 6 "math" 7 "testing" 8 "time" 9 10 "github.com/ncruces/go-sqlite3" 11 "github.com/ncruces/go-sqlite3/driver" 12 _ "github.com/ncruces/go-sqlite3/embed" 13 _ "github.com/ncruces/go-sqlite3/tests/testcfg" 14 "github.com/ncruces/julianday" 15 ) 16 17 func TestJSON(t *testing.T) { 18 t.Parallel() 19 20 ctx, cancel := context.WithCancel(context.Background()) 21 defer cancel() 22 23 db, err := driver.Open(":memory:", nil) 24 if err != nil { 25 t.Fatal(err) 26 } 27 defer db.Close() 28 29 conn, err := db.Conn(ctx) 30 if err != nil { 31 t.Fatal(err) 32 } 33 defer conn.Close() 34 35 _, err = conn.ExecContext(ctx, `CREATE TABLE test (col)`) 36 if err != nil { 37 t.Fatal(err) 38 } 39 40 reference := time.Date(2013, 10, 7, 4, 23, 19, 120_000_000, time.FixedZone("", -4*3600)) 41 42 _, err = conn.ExecContext(ctx, 43 `INSERT INTO test (col) VALUES (?), (?), (?), (?)`, 44 nil, 1, math.Pi, reference, 45 ) 46 if err != nil { 47 t.Fatal(err) 48 } 49 50 _, err = conn.ExecContext(ctx, 51 `INSERT INTO test (col) VALUES (?), (?), (?), (?)`, 52 sqlite3.JSON(math.Pi), sqlite3.JSON(false), 53 julianday.Format(reference), sqlite3.JSON([]string{})) 54 if err != nil { 55 t.Fatal(err) 56 } 57 58 rows, err := conn.QueryContext(ctx, "SELECT * FROM test") 59 if err != nil { 60 t.Fatal(err) 61 } 62 defer rows.Close() 63 64 want := []string{ 65 "null", "1", "3.141592653589793", 66 `"2013-10-07T04:23:19.12-04:00"`, 67 "3.141592653589793", "false", 68 "2456572.849526851851852", "[]", 69 } 70 for rows.Next() { 71 var got json.RawMessage 72 err = rows.Scan(sqlite3.JSON(&got)) 73 if err != nil { 74 t.Fatal(err) 75 } 76 if string(got) != want[0] { 77 t.Errorf("got %q, want %q", got, want[0]) 78 } 79 want = want[1:] 80 } 81 }