Go製のmigrationツール、gooseを試してみる。
https://bitbucket.org/liamstask/goose/src/master/
なお、github版とbitbucket版があるようだが、他の方の使用例を見た感じ bitbucket を利用している方がほとんどのように思えたので、そちらを利用する。
github版はbitbucketをcloneしているようだ。特色については下記に記載があった。
https://github.com/pressly/goose#goals-of-this-fork
作ってみるデータベース構成は下記の通り。 とてもシンプルな構成
Team ↓Teamは複数のUserに紐付いている関係 User
ちなみに実際にデータを取得する処理も書こうと思うが、ORMについてはgormを使う。
GORM - The fantastic ORM library for Golang, aims to be developer friendly.
gooseのセットアップ
まずは gooseのインストールを行う
go get bitbucket.org/liamstask/goose/cmd/goose
DB接続のための設定ファイルを用意する
(defaultは db ディレクトリをみるようだ)
mkdir db vim db/cdbconf.yml
dbconf.yml を作成し、こちらにDB接続に関する設定を記述する
development:
    driver: mymysql
    open: tcp:localhost:3306*[db_name]/[user_name]/[password]
書き方のサンプルはこちら
https://bitbucket.org/liamstask/goose/src/master/db-sample/dbconf.yml
ちなみにgoose実行時のコマンドオプションは下記で見れる
goose help # もしくは $GOPATH/bin/goose help
optionはこんな感じ
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)
実際に下記のようなコマンドを打って疎通確認をした。 なお、自身はローカルのmacで動くdocker上でmysqlを動かして、そこにアクセスしている。
goose status
gooseを使ってmigrationファイルを作成する
migrationファイルの作成は下記のコマンドで行うよう
goose create AddSomeColumns
実際にteamsテーブルとusersテーブルを作成するmigrationファイルを作成する。
最後に付けたsqlで、migration用のsqlファイルを生成する。
これをつけない場合、.goでmigrationファイルが作られるがこちらはまだ試していない。
goをまだあまり理解していないので、とりあえずsqlで試す。
(そういえば、公式だとmigrationファイルがPascal caseだったが、実際そうなのだろうか?Go書き慣れていないのでここらへんも詳しくない)
goose create CreateTeamsTable sql goose create CreateUsersTable sql
すると、下記のような感じにmigrationファイルが生成される
db/migrations/20191221231458_CreateTeamsTable.sql
あとはこちらにテーブル定義を書いていけば良い
teamsテーブル
-- +goose Up -- SQL in section 'Up' is executed when this migration is applied CREATE TABLE teams ( id int NOT NULL, name varchar(255) NOT NULL, PRIMARY KEY(id) ); -- +goose Down -- SQL section 'Down' is executed when this migration is rolled back DROP TABLE teams;
usersテーブル
-- +goose Up -- SQL in section 'Up' is executed when this migration is applied CREATE TABLE users ( id int NOT NULL, teamId int NOT NULL, name varchar(255) NOT NULL, PRIMARY KEY(id) ); -- +goose Down -- SQL section 'Down' is executed when this migration is rolled back DROP TABLE users;
DBのmigrationを行う
goose up # 以下ログ goose: migrating db environment 'development', current version: 0, target: 20191221231510 OK 20191221231458_CreateTeamsTable.sql OK 20191221231510_CreateUsersTable.sql
なお、戻す場合はdownで良い
goose down
migration に関する履歴はgoose_db_versionというところで管理されているようだ。
statusで現在の状態も確認できるので、わからなくなったときは打てば良さそう。
goose status
goose: status for environment 'development'
    Applied At                  Migration
    =======================================
    Sat Dec 21 14:19:23 2019 -- 20191221231458_CreateTeamsTable.sql
    Sat Dec 21 14:20:28 2019 -- 20191221231510_CreateUsersTable.sql
ちょっと長くなってしまったので、gorm使ってデータを実際に取得するところは後日やる。