This tutorial assumes you have successfully completed the First Steps: Command-line tutorial. If you have not done so, please do so first. This tutorial picks up where that one left off.
This brief tutorial will teach how to use callbacks. It will take you through the steps on how to create and use them.
Callbacks let you hook into Flyway’s lifecycle. This is particularly useful when you execute the same housekeeping action over and over again.
They are typically used for
VACUUM
for PostgreSQL for example)After having completed the First Steps: Command-line, you can now execute
flyway-9.8.1> flyway info
This should give you the following status:
Database: jdbc:h2:file:./foobardb (H2 1.4) +-----------+---------+---------------------+------+---------------------+---------+----------+ | Category | Version | Description | Type | Installed On | State | Undoable | +-----------+---------+---------------------+------+---------------------+---------+----------+ | Versioned | 1 | Create person table | SQL | 2017-12-21 18:05:10 | Success | No | | Versioned | 2 | Add people | SQL | 2017-12-21 18:05:10 | Success | No | +-----------+---------+---------------------+------+---------------------+---------+----------+
Now let’s create a callback to flush all data to disk before a migration run. To do so, we’ll make use of Flyway’s
beforeMigrate
callback.
So go ahead and create beforeMigrate.sql
in the /sql
directory:
CHECKPOINT SYNC;
To trigger the execution of the callback, we’ll clean and migrate the database again.
So go ahead and invoke
flyway-9.8.1> flyway clean migrate
This will give you the following result:
Database: jdbc:h2:file:./foobardb (H2 1.4) Successfully cleaned schema "PUBLIC" (execution time 00:00.003s) Successfully validated 2 migrations (execution time 00:00.010s) Executing SQL callback: beforeMigrate Creating Schema History table: "PUBLIC"."flyway_schema_history" Current version of schema "PUBLIC": << Empty Schema >> Migrating schema "PUBLIC" to version 1 - Create person table Migrating schema "PUBLIC" to version 2 - Add people Successfully applied 2 migrations to schema "PUBLIC" (execution time 00:00.034s)
As expected we can see that the beforeMigrate
callback was triggered and executed successfully before the migrate
operation. Each time you invoke migrate again in the future, the callback will now be executed again.
In this brief tutorial we saw how to