LoginSignup
14
14

More than 5 years have passed since last update.

gorpでサーバー起動時に自動でCREATE DADABASEする

Last updated at Posted at 2014-04-30

gorpを使ってて、typeで各テーブルの定義をしておくと、こちらでCREATE TABLEしなくても、自動でやってくれる仕組みがあって感動していたのですが、どうやらDBはつくってくれない感じだったので、何も考えなくていいように最初にDBもつくるようにしました。

main.go
package main

func main() {
    // initialize the DbMap
    dbmap := initDb()
    defer dbmap.Db.Close()

    // なにかしらの処理…

次にinitDbを定義してるスクリプト。

自分はめんどくさいのでmain.goの隣に置いてます。

sql.Openの部分でまずはDB名を指定せずに接続し、クリエイトのためのSQLを流し、そのあとDB名を指定して接続しにいってます。あとは標準的なgorpの使い方になっているかと思います。

db.go
package main

import (
    "database/sql"
    "github.com/coopernurse/gorp"
    _ "github.com/go-sql-driver/mysql"
    "log"
)

type PostInfo struct {
    Title       string
    Body        string
}

type Post struct {
    Id int64
    PostInfo
    CreatedAt int64
    UpdatedAt int64
}

func checkErr(err error, msg string) {
    if err != nil {
        log.Fatalln(msg, err)
    }
}

func initDb() *gorp.DbMap {
    // connect mysql
    db, err := sql.Open("mysql", "user_name:pass_word@/")
    checkErr(err, "sql.Open failed")
    dbmap := &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{"InnoDB", "UTF8"}}

    // create db if not exists
    _, err = dbmap.Exec("CREATE DATABASE IF NOT EXISTS your_project_name DEFAULT CHARACTER SET utf8;")
    checkErr(err, "create db failed")

    // connect db
    db, err = sql.Open("mysql", "user_name:pass_word@/your_project_name")
    checkErr(err, "sql.Open failed")
    dbmap = &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{"InnoDB", "UTF8"}}

    // add table
    dbmap.AddTableWithName(Post{}, "posts").SetKeys(true, "Id")

    // create the table
    err = dbmap.CreateTablesIfNotExists()
    checkErr(err, "Create tables failed")

    return dbmap
}

余談

最近ずっとRailsでActiverecord使っていたので、gorpの中途半端なORM感がちょっと微妙だなぁって思ってました。

探したらgormが使いやすそうです。

乗り換えようかな。。。

14
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14