Skip to content

Instantly share code, notes, and snippets.

@Acconut
Last active August 29, 2015 14:12
Show Gist options
  • Save Acconut/9e5d1ec197fca909c030 to your computer and use it in GitHub Desktop.
Save Acconut/9e5d1ec197fca909c030 to your computer and use it in GitHub Desktop.
package main
import (
"database/sql"
)
type Post struct {
Id string `db:"post_id"`
Title string `db:"title"`
Author User `db:"author"`
}
type User struct {
Id string `db:"user_id"`
Name string `db:"name"`
}
//db:getPosts []Post
/*
SELECT
post_id,
title,
users.user_id AS "author.user_id",
users.name AS "auther.name",
FROM
posts,
users
WHERE
posts.user_id = users.user_id
*/
func main() {
var user User
var err error
user.Posts, err = getPosts(db)
if err != nil {
panic(err)
}
}
func getPosts(db *sql.DB, args ...interface{}) ([]Post, error) {
dest := make([]Post, 0)
rows, err := db.Query(query, args...)
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
post := Post{}
if err := rows.Scan(&post.Id, &post.Title, &post.Author.Id, &post.Author.Name); err != nil {
panic(err)
}
dest = append(dest, &post)
}
err = rows.Err()
return dest, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment