Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix json example #1313

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 49 additions & 1 deletion _example/json/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ func main() {
}
defer db.Close()

_, err = db.Exec(`create table foo (tag jsonb)`)
// Using a json-typed column
// Verify type: `create table foo (tag text) strict`
_, err = db.Exec(`create table foo (tag json)`)
if err != nil {
log.Fatal(err)
}
Expand Down Expand Up @@ -78,4 +80,50 @@ func main() {
log.Fatal(err)
}
fmt.Println(country)

// Using a jsonb-typed column
// Verify type: `create table bar (tag blob) strict`
_, err = db.Exec(`create table bar (tag jsonb)`)
if err != nil {
log.Fatal(err)
}

stmt, err = db.Prepare("insert into bar(tag) values(jsonb(?))")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
_, err = stmt.Exec(`{"name": "mattn", "country": "japan"}`)
if err != nil {
log.Fatal(err)
}
_, err = stmt.Exec(`{"name": "michael", "country": "usa"}`)
if err != nil {
log.Fatal(err)
}

err = db.QueryRow("select tag->>'country' from bar where tag->>'name' = 'mattn'").Scan(&country)
if err != nil {
log.Fatal(err)
}
fmt.Println(country)

err = db.QueryRow("select json(tag) from bar where tag->>'name' = 'mattn'").Scan(&tag)
if err != nil {
log.Fatal(err)
}

fmt.Println(tag.Name)

tag.Country = "日本"
_, err = db.Exec(`update bar set tag = jsonb(?) where tag->>'name' == 'mattn'`, &tag)
if err != nil {
log.Fatal(err)
}

err = db.QueryRow("select tag->>'country' from bar where tag->>'name' = 'mattn'").Scan(&country)
if err != nil {
log.Fatal(err)
}
fmt.Println(country)
}