weblog

技術的なメモ置き場。

Gradle + Flyway + PostgreSQLでマイグレーション

以下の環境

準備

build.gradleに以下を記述する。

plugins {
    id "org.flywaydb.flyway" version "7.2.1"
}

dependencies {
    runtimeOnly "org.postgresql:postgresql:42.2.14"
}

flyway {
    driver = 'org.postgresql.Driver'
    url = 'jdbc:postgresql://localhost:5432/postgres'
    user = 'postgres'
    password = 'password'
    schemas = ['public']
    locations = ['classpath:db/migration']
}

マイグレーション

src/main/resources/db/migration に以下の内容でsqlファイルを作成する。 ファイル名はV1__init.sqlとする。

CREATE TABLE cities
(
    id   int         NOT NULL,
    name varchar(80) NOT NULL
);

flywayInfo

準備ができたら flywayInfo を実行する。

$ gradle flywayInfo
...

Schema version: << Empty Schema >>
+----------+---------+-------------+------+--------------+-------+
| Category | Version | Description | Type | Installed On | State |
+----------+---------+-------------+------+--------------+-------+
| No migrations found                                            |
+----------+---------+-------------+------+--------------+-------+


BUILD SUCCESSFUL in 499ms
1 actionable task: 1 executed
Unable to resolve location classpath:db/migration.

classpath:db/migration が見つからないと言われるので、gradle classes を実行後再度行う。

$ gradle classes
...

$ gradle flywayInfo
...

Schema version: << Empty Schema >>
+-----------+---------+-------------+------+--------------+---------+
| Category  | Version | Description | Type | Installed On | State   |
+-----------+---------+-------------+------+--------------+---------+
| Versioned | 1       | init        | SQL  |              | Pending |
+-----------+---------+-------------+------+--------------+---------+


BUILD SUCCESSFUL in 518ms
1 actionable task: 1 executed

マイグレーションペンディングなのがわかる。

flywayMigration

次に実際に flywayMigrate マイグレーションする。 -i をつけると詳細が出力される。

$ gradle flywayMigrate -i
...

Flyway Community Edition 7.2.1 by Redgate
Database: jdbc:postgresql://localhost:5432/postgres (PostgreSQL 12.5)
Successfully validated 1 migration (execution time 00:00.010s)
Creating Schema History table "public"."flyway_schema_history" ...
Current version of schema "public": << Empty Schema >>
Migrating schema "public" to version "1 - init"
Successfully applied 1 migration to schema "public" (execution time 00:00.092s)

...

$ gradle flywayInfo
...

Schema version: 1
+-----------+---------+-------------+------+---------------------+---------+
| Category  | Version | Description | Type | Installed On        | State   |
+-----------+---------+-------------+------+---------------------+---------+
| Versioned | 1       | init        | SQL  | 2020-11-22 09:42:30 | Success |
+-----------+---------+-------------+------+---------------------+---------+


BUILD SUCCESSFUL in 452ms
1 actionable task: 1 executed