What Is Flyway and How Does It Work?
What Is Flyway and How Does It Work?
www.thoughts-on-java.org
Getting Started with Flyway
I store these SQL statements in a file called V1__create_database.
The file name follows Flyway’s default naming convention:
V<VERSION>__DESCRIPTION.sql.
So, this file contains the SQL statements for database version 1 and
Flyway will store it with the description “create_database” in the
SCHEMA_VERSION table.
flyway.url=jdbc:postgresql://localhost:5433/recipes
flyway.user=postgres
flyway.password=postgres
The flyway.url parameter defines the JDBC url which Flyway shall use
to connect to the database. For most databases, Flyway will detect
the required JDBC driver based on the flyway.url.
The parameters flyway.user and flyway.password are optional. The
command line client will prompt you for the user information, if you
don’t provide them in the configuration file.
www.thoughts-on-java.org
Getting Started with Flyway
OK, so let’s run Flyway and initialize the database to version 1. You can
do that by calling the command line client with the migrate command.
C:\dev\wrk\Flyway\flyway-4.2.0>flyway migrate
Flyway 4.2.0 by Boxfuse
Database: jdbc:postgresql://localhost:5433/recipes
(PostgreSQL 9.6)
Successfully validated 1 migration (execution time
00:00.038s)
Current version of schema "public": << Empty Schema >>
Migrating schema "public" to version 1 - create database
Successfully applied 1 migration to schema "public"
(execution time 00:00.076s).
And you’re done. As you can see in the log output, Flyway found an
empty database and applied the migration script for version 1.
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>4.2.0</version>
</dependency>
www.thoughts-on-java.org
Getting Started with Flyway
And after you’ve done that, you can trigger the Flyway database
migration from your Java code.
You can do that by creating a new Flyway instance, configuring the
datasource and calling the migrate() method. You can either call the
setDataSource method with a DataSource object or provide the JDBC
connection, username and password as Strings.
OK, you’re almost done. The only thing that’s missing are the migration
scripts. I’m reusing the SQL script from the previous example and copy
it to the src/main/resources/db/migration folder. Similar to the
command line client, Flyway’s API integration checks all files in that
folder and uses them to update the database if necessary.
www.thoughts-on-java.org