省エネ

Flutter、vue3修行中。

【Go】database migration tool

qkuronekop.hatenablog.jp

こちらに引き続き、環境の構築をしているのでメモ的に残そうと思います。

Databaseはmysqlを使っていて、テーブルを作成するのにgooseを使っています。

bitbucket.org

こちらは、プロジェクトにimportしていないので、go getで別途取得します。

install

go get bitbucket.org/liamstask/goose/cmd/goose

.bash_profile

export PATH="$GOPATH/bin:$PATH"

これでgooseコマンドが使えるようになります。

$ goose

goose is a database migration management system for Go projects.

Usage:
    goose [options] <subcommand> [subcommand options]

Options:
  -env string
        which DB environment to use (default "development")
  -path string
        folder containing db info (default "db")
  -pgschema string
        which postgres-schema to migrate (default = none)

Commands:
    up         Migrate the DB to the most recent version available
    down       Roll back the version by 1
    redo       Re-run the latest migration
    status     dump the migration status for the current DB
    create     Create the scaffolding for a new migration
    dbversion  Print the current version of the database

Configuration

プロジェクトフォルダの下にdbというフォルダを作成します。 dbの下にdbconf.ymlファイルを作ります。

ファイルの中はこんな感じ。

# test:
#     driver: mysql
#     open: tcp:localhost:3306*[db_name]/[user_name]/[password]

development:
    driver: mymysql
    open: tcp:localhost:3306*[db_name]/[user_name]/[password]

# production:
#     driver: postgres
#     open: user=liam dbname=tester sslmode=verify-full

customimport:
    driver: customdriver
    open: customdriver open
    import: github.com/custom/driver
    dialect: mysql

environment_variable_config:
    driver: $DB_DRIVER
    open: $DATABASE_URL

今はdevelopmentしか使ってないです。

migrationファイル

goose create [マイグレーション名] sql でファイルを作成できます。

-- +goose Up
-- SQL in section 'Up' is executed when this migration is applied


-- +goose Down
-- SQL section 'Down' is executed when this migration is rolled back

中はただこれだけなので、ここにSQLを書いていきます。

例えばこんな感じ。

-- +goose Up
-- SQL in section 'Up' is executed when this migration is applied
CREATE TABLE IF NOT EXISTS sample (
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(255),
  update_at DATETIME,
  create_at DATETIME,
  PRIMARY KEY (id)
) ENGINE = InnoDB;

-- +goose Down
-- SQL section 'Down' is executed when this migration is rolled back
DROP TABLE sample;

UP

$ goose up
goose: migrating db environment 'development', current version: 20170923140458, target: 20180129163234
OK    20180129163234_sample.sql

できた。

DOWN

$ goose down
goose: migrating db environment 'development', current version: 20180129163234, target: 20170923140458
OK    20180129163234_sample.sql

簡単です。