createdb dat_test
CREATE TABLE posts (
id bigserial PRIMARY KEY,
title text NOT NULL,
user_id bigint NOT NULL
);
INSERT INTO posts (title, user_id) VALUES ('a', 2);
package main | |
import ( | |
"fmt" | |
"github.com/mgutz/dat/v1/sqlx-runner" | |
) | |
// Columns are mapped to fields breadth-first | |
type Post struct { | |
ID int64 `db:"id"` | |
Title string `db:"title"` | |
User *struct { | |
ID int64 `db:"user_id"` | |
} | |
} | |
func main() { | |
conn := runner.NewConnectionFromString("postgres", "postgres://localhost/dat_test?sslmode=disable") | |
var post Post | |
err := conn. | |
Select("id, title, user_id"). | |
From("posts"). | |
Limit(1). | |
QueryStruct(&post) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(&post) | |
} |