code smith

開発で日々の生活をもっと楽しく

playframeworkでdbマイグレーションツールのEvolustionsを利用する

依存の追加

libraryDependencies ++= Seq(
  jdbc,
  evolutions,
  "org.postgresql" % "postgresql" % "42.2.18"
)

今回はpostgresと接続するためpostgres用のドライバと、evolutionsを利用するための依存を追加します。

databaseの用意

databaseはdockerで用意します。以下のようなdocker-compose.ymlを作成し起動しておきます。

version: '3.1'

services:
  db:
    image: postgres:13.1
    restart: always
    environment:
      POSTGRES_PASSWORD: password
      POSTGRES_USER: user
      POSTGRES_DB: db
    ports:
      - 5432:5432

接続設定

conf/application.confに以下を追加し、databaseとの接続設定を記載します。

db.default {
    driver=org.postgresql.Driver
    url="postgres://user:password@localhost:5432/db"
}

migrationファイルの追加

conf/evolutions/defaultというフォルダを作成し、migrationファイルを作成します。 今回は以下のようなファイルを用意しました。

-- 1.sql
--- !Ups
CREATE TABLE profiles
(
    uid      text,
    nickname text
);

--- !Downs
DROP TABLE profiles;

適用

これでPlayFrameworkを起動すると、このような画面になるので[Apply this script now!]をクリック f:id:gaku3601:20210103110351p:plain

Evolutionsを利用して追加テーブルが無事データベースに追加されました。 f:id:gaku3601:20210103110450p:plain

補足

この状態だと、migrationファイルを追加すると毎回このような画面になって、migrationを追加するか聞かれるので鬱陶しい。 f:id:gaku3601:20210103110851p:plain

conf/application.confに以下を追加することで、migrationのupもdownもfileを追加すれば自動的に行ってくれるようになる。

play.evolutions.db.default {
    enabled = true
    autoApply=true
    autoApplyDowns=true
}

まとめ

railsのmigrationより個人的には好き。(sqlで書けるし、fileの作成・削除だけで適用してくれるのですごく楽。