Last active
August 29, 2015 14:23
-
-
Save cs2dsb/5a0efee98e1725fd2723 to your computer and use it in GitHub Desktop.
Reproduce Gorp issue #265
This file contains 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" | |
"log" | |
"github.com/go-gorp/gorp" | |
_ "github.com/mattn/go-sqlite3" | |
) | |
type Post struct { | |
// db tag lets you specify the column name if it differs from the struct field | |
Id int64 `db:"post_id"` | |
Created int64 | |
Title string `db:",size:50"` // Column size set to 50 | |
Body string `db:"article_body,size:1024"` // Set both column name and size | |
} | |
func main() { | |
dbmap := initDb() | |
defer dbmap.Db.Close() | |
var posts []Post | |
_, err := dbmap.Select(&posts, "select * from posts") | |
if err != nil { | |
log.Fatalf("Error fetching posts: %v\n", err) | |
} | |
log.Println(posts) | |
} | |
func initDb() *gorp.DbMap { | |
// connect to db using standard Go database/sql API | |
// use whatever database/sql driver you wish | |
db, err := sql.Open("sqlite3", "gorptest.sqlite") | |
checkErr(err, "sql.Open failed") | |
// construct a gorp DbMap | |
dbmap := &gorp.DbMap{Db: db, Dialect: gorp.SqliteDialect{}} | |
// add a table, setting the table name to 'posts' and | |
// specifying that the Id property is an auto incrementing PK | |
dbmap.AddTableWithName(Post{}, "posts").SetKeys(true, "Id") | |
// create the table. in a production system you'd generally | |
// use a migration tool, or create the tables via scripts | |
err = dbmap.CreateTablesIfNotExists() | |
checkErr(err, "Create tables failed") | |
return dbmap | |
} | |
func checkErr(err error, msg string) { | |
if err != nil { | |
log.Fatalln(msg, err) | |
} | |
} |
This file contains 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
2015/06/30 12:42:24 Error fetching posts: gorp: No fields [title article_body] in type Post | |
exit status 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment