Last active
August 29, 2015 14:12
-
-
Save Acconut/9e5d1ec197fca909c030 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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