Thursday, May 14, 2015

Day 8 - ORM comparison in Go using MySql, today gorp

The first ORM im testing is gorp, because its the first that poked my eye, is easy to use and is not part of a larger framework.

As my code is growing im not posting the full source, but only snippets which  handle gorp code.

To test it you need a MySql installation, create a Schema golang for a user golang with password golang: MySql Readme

 Open the database:

    db, err := sql.Open("mysql", "golang:golang@/golang")
    if err != nil {
        return errors.New("sql.Open failed: " + err.Error())

    // Open doesn't open a connection. Validate DSN data:
    err = db.Ping()
    if err != nil {
        return errors.New("db.Ping failed: " + err.Error())

    // construct a gorp DbMap
    dbmap := &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{"InnoDB", "UTF8"}}
    defer dbmap.Db.Close()

Create a table if it does not exist:

    // SetKeys(true) means we have a auto increment primary key, which 
    // will get automatically bound to your struct post-insert
    table := dbmap.AddTableWithName(post.Post{}, "posts")
    table.SetKeys(true, "Id")

Check if the post already is in the database:

     // check if post already exists
      count, err := dbmap.SelectInt("select count(*) from posts where PostId = ?", post.PostId)
      if err != nil {
          return errors.New("select count(*) from posts failed: " + err.Error())

Do an insert if count == 0
         err = dbmap.Insert(&post) 
         if err != nil {
             return errors.New("insert into table posts failed: " + err.Error())

Edit 2015.05.21:
The code for fetching and the post structure have been changed to use gorp with indexes, please look at Day 11 of my blog for details how to create indexes with gorp.

No comments:

Post a Comment