Wednesday, 31 October 2012

Flyway Db Migrations with Maven

Flyway is a tool that can be used to make database migrations a little easier. Heres a quick walkthrough on how to set it up with maven.

Firstly add the following to your pom:
<profiles>
    <profile>
      <id>Dev</id>
      <dependencies>
          <!-- Fly way -->
          <dependency>
            <groupId>com.googlecode.flyway</groupId>
            <artifactId>flyway-core</artifactId>
            <version>1.7</version>
          </dependency>

          <!-- mysql jdbc driver -->
          <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>5.1.21</version>
          </dependency>

      </dependencies>

      <build>
        <plugins>
            <plugin>
              <groupId>com.googlecode.flyway</groupId>
              <artifactId>flyway-maven-plugin</artifactId>
              <version>1.7</version>
              <configuration>
                <user>riz</user>
                <password>password</password>
                <driver>com.mysql.jdbc.Driver</driver>
                <url>jdbc:mysql://localhost:3306/mydb</url>
              </configuration>
            </plugin>
        </plugins>
      </build>
    </profile>
 </profiles>

It isn't necessary to create a profile, you can place the setting in you global pom profile. Having a seperate profile allows to seperate the migration configurations per db and remove the migration from the main build phase making it optional. 

Migrations scripts are located under: src/main/resources/db/migration. The file names follow the default flyway conventions:
V0001__Some_description.sql

Now run the following commands to run the flyway goals to migrate the db.

mvn -PDev flyway:clean    //cleans the db (run first time)
mvn -PDev flyway:migrate  //run migration scripts

-PDev tells maven to use the dev profile


To find out more about flyway goals goto: https://flywaydb.org/

No comments:

Post a Comment