Skip to content

Commit cff37b4

Browse files
committed
Fix json example
Because of sqlite's flexible typing, even though the column was declared as jsonb, the values are stored as the TEXT-typed json because they're converted to strings by Value/Scan. If the table is strict with a BLOB column, the example fails because of the type mismatch. This can be fixed by using the `jsonb()` function to convert incoming string-typed json and the `json()` function to convert outgoing binary-typed jsonb. The example is expanded to show both of these approaches. Note that both approaches use the same string-typed marshalling functions because the conversion to jsonb occurs within sqlite3, not within the Go code. SQLite docs state that the binary format is internal and applications shouldn't try to generate it: https://sqlite.org/json1.html#jsonb
1 parent 7658c06 commit cff37b4

1 file changed

Lines changed: 49 additions & 1 deletion

File tree

_example/json/json.go

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,9 @@ func main() {
3333
}
3434
defer db.Close()
3535

36-
_, err = db.Exec(`create table foo (tag jsonb)`)
36+
// Using a json-typed column
37+
// Verify type: `create table foo (tag text) strict`
38+
_, err = db.Exec(`create table foo (tag json)`)
3739
if err != nil {
3840
log.Fatal(err)
3941
}
@@ -78,4 +80,50 @@ func main() {
7880
log.Fatal(err)
7981
}
8082
fmt.Println(country)
83+
84+
// Using a jsonb-typed column
85+
// Verify type: `create table bar (tag blob) strict`
86+
_, err = db.Exec(`create table bar (tag jsonb)`)
87+
if err != nil {
88+
log.Fatal(err)
89+
}
90+
91+
stmt, err = db.Prepare("insert into bar(tag) values(jsonb(?))")
92+
if err != nil {
93+
log.Fatal(err)
94+
}
95+
defer stmt.Close()
96+
_, err = stmt.Exec(`{"name": "mattn", "country": "japan"}`)
97+
if err != nil {
98+
log.Fatal(err)
99+
}
100+
_, err = stmt.Exec(`{"name": "michael", "country": "usa"}`)
101+
if err != nil {
102+
log.Fatal(err)
103+
}
104+
105+
err = db.QueryRow("select tag->>'country' from bar where tag->>'name' = 'mattn'").Scan(&country)
106+
if err != nil {
107+
log.Fatal(err)
108+
}
109+
fmt.Println(country)
110+
111+
err = db.QueryRow("select json(tag) from bar where tag->>'name' = 'mattn'").Scan(&tag)
112+
if err != nil {
113+
log.Fatal(err)
114+
}
115+
116+
fmt.Println(tag.Name)
117+
118+
tag.Country = "日本"
119+
_, err = db.Exec(`update bar set tag = jsonb(?) where tag->>'name' == 'mattn'`, &tag)
120+
if err != nil {
121+
log.Fatal(err)
122+
}
123+
124+
err = db.QueryRow("select tag->>'country' from bar where tag->>'name' = 'mattn'").Scan(&country)
125+
if err != nil {
126+
log.Fatal(err)
127+
}
128+
fmt.Println(country)
81129
}

0 commit comments

Comments
 (0)