Created
June 30, 2015 07:29
-
-
Save pierreprinetti/a081fdd931c8c6ccd14d to your computer and use it in GitHub Desktop.
Reproduce Gorp issue #265
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" | |
"log" | |
_ "github.com/mattn/go-sqlite3" | |
"github.com/qrawl/gorp" | |
) | |
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() | |
} | |
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", "/Users/pierre/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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment