すでに存在するデータベースにFlywayを適用する #flyway
概要
Baselineを使って、MySQL+Mavenで、FlywayによるDB構成管理を既に存在するデータベースに適用する。
Flyway by Boxfuse • Database Migrations Made Easy.
テスト用のデータベースを作る
create database if not exists flyway_sample character set utf8
flyway管理外のテーブルを追加する
mysql -u root -D flyway_sample
create table person ( `person_id` int not null, `name` varchar(100) not null );
pom.xmlにFlywayを追加する
<build> <plugins> <plugin> <groupId>org.flywaydb</groupId> <artifactId>flyway-maven-plugin</artifactId> <version>4.0.3</version> <configuration> <url> jdbc:mysql://localhost:3306/flyway_sample </url> <user>root</user> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> </dependencies> </plugin> </plugins> </build>
flyway:baselineを実行する
mvn flyway:baseline
schema_versionが作成される
mysql> show tables; +-------------------------+ | Tables_in_flyway_sample | +-------------------------+ | person | | schema_version | +-------------------------+ 2 rows in set (0.00 sec) mysql> select * from schema_version; +----------------+---------+-----------------------+----------+-----------------------+----------+--------------+---------------------+----------------+---------+ | installed_rank | version | description | type | script | checksum | installed_by | installed_on | execution_time | success | +----------------+---------+-----------------------+----------+-----------------------+----------+--------------+---------------------+----------------+---------+ | 1 | 1 | << Flyway Baseline >> | BASELINE | << Flyway Baseline >> | NULL | root | 2017-06-08 09:27:41 | 0 | 1 | +----------------+---------+-----------------------+----------+-----------------------+----------+--------------+---------------------+----------------+---------+
新しいDDLを追加する
src/main/resources/db/migration/V1_0_1__create_demo.sql
あたりに。
create table demo ( `demo_id` int not null, `name` varchar(100) not null );
flyway:migrateを実行する
mvn flyway:migrate
構成管理ができている
mysql> select * from schema_version; +----------------+---------+-----------------------+----------+-------------------------+-------------+--------------+---------------------+----------------+---------+ | installed_rank | version | description | type | script | checksum | installed_by | installed_on | execution_time | success | +----------------+---------+-----------------------+----------+-------------------------+-------------+--------------+---------------------+----------------+---------+ | 1 | 1 | << Flyway Baseline >> | BASELINE | << Flyway Baseline >> | NULL | root | 2017-06-08 09:27:41 | 0 | 1 | | 2 | 1.0.1 | create demo | SQL | V1_0_1__create_demo.sql | -1142022008 | root | 2017-06-08 09:33:54 | 153 | 1 | +----------------+---------+-----------------------+----------+-------------------------+-------------+--------------+---------------------+----------------+---------+ 2 rows in set (0.00 sec)
まとめ
Flyway好きです。