Skip to content

Instantly share code, notes, and snippets.

@whatupdave
Last active August 29, 2015 14:02
Show Gist options
  • Save whatupdave/79e8912d85fd0707cf43 to your computer and use it in GitHub Desktop.
Save whatupdave/79e8912d85fd0707cf43 to your computer and use it in GitHub Desktop.
JSON load failed with lib/pq
package main
import (
"database/sql"
"encoding/json"
"fmt"
_ "github.com/lib/pq"
)
type Article struct {
Id int
Doc *json.RawMessage
}
func main() {
db, err := sql.Open("postgres", "postgres://localhost/json_test?sslmode=disable")
if err != nil {
panic(err)
}
_, err = db.Query(`create table if not exists articles (id serial primary key, doc json)`)
if err != nil {
panic(err)
}
_, err = db.Query(`truncate articles`)
if err != nil {
panic(err)
}
docs := []string{
`{"type":"event1"}`,
`{"type":"event2"}`,
}
for _, doc := range docs {
_, err = db.Query(`insert into articles ("doc") values ($1)`, doc)
if err != nil {
panic(err)
}
}
rows, err := db.Query(`select id, doc from articles`)
if err != nil {
panic(err)
}
articles := make([]Article, 0)
for rows.Next() {
var a Article
err := rows.Scan(
&a.Id,
&a.Doc,
)
if err != nil {
panic(err)
}
articles = append(articles, a)
fmt.Println("scan", string(*a.Doc), len(*a.Doc))
}
fmt.Println()
for _, a := range articles {
fmt.Println("loop", string(*a.Doc), len(*a.Doc))
}
}
Expected:
scan {"type":"event1"} 17
scan {"type":"event2"} 17
loop {"type":"event1"} 17
loop {"type":"event2"} 17
But I got:
scan {"type":"event1"} 17
scan {"type":"event2"} 17
loop {"type":"event2"} 17
loop {"type":"event2"} 17
After the appends, the docs are all the same
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment