Several weeks ago I started to learn go and trying to build a simple blogging application while learning the basics.
Currently I'm trying to fetch and persist blog posts using database/sql and github.com/lib/pq packages. I dont prefer utilizing 3rd party packages like sqlx or gorm without fully understand the native behaviours and basics of the go.
My Post struct is something like this:
type Post struct {
Id int
Title string
Body string
Tags json.RawMessage
}
When persisting posts, my save() function works without any problem:
func (p *Post) save() (int, error) {
const query = `INSERT INTO post (title, body, tags) VALUES($1, $2, $3) RETURNING id`
db := GetDB()
var postid int
err := db.QueryRow(query, p.Title, p.Body, p.Tags).Scan(&postid)
return postid, err
}
and to read the latest posts, I wrote a small function:
func getLatestPosts(page int) (*[]Post, error) {
const query = `SELECT id, title, body, tags FROM posts ORDER BY id DESC LIMIT 10`
var items []Post
db := GetDB()
rows, err := db.Query(query)
if err != nil {
return nil, err
}
for rows.Next() {
var item Post
if err := rows.Scan(&item.Id, &item.Title, &item.Body, &item.Tags); err != nil {
log.Fatal(err)
}
items = append(items, item)
}
return &items, err
}
This also works until hitting a post row which tags column is null and I'm getting the following error at this point:
2015/04/16 21:53:04 sql: Scan error on column index 4: unsupported driver -> Scan pair: -> *json.RawMessage
My question is, what is the proper way to handle nullable json columns while scanning the resultset? Is this error related with the lib/pq?
My schema is:
CREATE TABLE post (
"id" int4 NOT NULL DEFAULT nextval('post_id_seq'::regclass),
"title" varchar(255) NOT NULL COLLATE "default",
"body" text COLLATE "default",
"tags" json,
PRIMARY KEY ("id") NOT DEFERRABLE INITIALLY IMMEDIATE
);
and here is an already persisted (not-null) tags field content:
{
"black-and-white" : "Black and White",
"the-godfather" : "The Godfather"
}
Any ideas?
json.RawMessage? Why not just[]byte?