Go migrateion goose setup

Goのマイグレーションツール

goose

bitbucket.org

Go製のmigration ツールでは人気のある方?

業務でも採用されていたので使ってみました。

情報にバラつきがありセットアップまでに時間がかかりました。

goose

bitbucket版 と github版があります。

githubhttps://github.com/pressly/goose

同じかと思いきや、微妙に挙動が違うので要注意です。

今回はbitbucket版を使用します。

install

bitbucketを使用します。 githubと間違わないよう注意です。

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

configure

db/dbconf.yml デフォルトでこのパスを見にいくみたいです。

development:
  driver: mysql
  open: $DB_URL

production:
  driver: mysql
  open: $DB_URL
% echo $DB_URL

root:password@tcp(db:3306)/sample_pj

{username}:{password}@tcp({host}:3306/{db_name}

上記の形式で指定します。 私の場合はdocker-composeを使用している為 hostがdb(コンテナ名)を指定しています。

docker-compose

app:
    environment:
      DB_URL: root:password@tcp(db:3306)/sample_pj

db:
    environment:
      MYSQL_DATABASE: sample_pj
      MYSQL_ROOT_PASSWORD: password

バージョンによって書き方が違うみたいです。

commands

% 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

create

マイグレーションファイルの生成 db/migrations/ 配下にmigrationファイルが生成されます。

github版だとなぜかルートにマイグレーションファイルが生成されます。

goose create AddSomeColumns sql

sqlを指定しない場合はgoファイルで生成されます。

migrationfile

db/migrations/20210526144142_AddSomeColumns.sql 生成されたファイルに以下を追加

-- +goose Up
-- SQL in section 'Up' is executed when this migration is applied
CREATE TABLE samples (
  id int UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  first_name varchar(255) NOT NULL,
  last_name varchar(255) NOT NULL,
  super_user int(8) UNSIGNED,
  created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);

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

migration

% goose up

これでマイグレーションされます。

逆にdownすると

% goose down

テーブルは削除されます。

またup or down 時に goose_db_versionというテーブルが生成され 変更のたびにversionが記録されていきます。

f:id:shikatech:20210526210120p:plain

以上です。

bitbucket製とgithub製、configファイルの書き方に苦戦しました。

他にもコマンドがあるのでもう少し触ってみようと思います。