Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Flyway SQL migrations: record ordered schema changes against a real database

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A versioned Flyway migration applies a named SQL file once and records its outcome in a schema-history table.

Download Spring source kit

The checked sequence

The source kit ships V1__create_receipts.sql, V2__expand_tenant.sql and V3__backfill_and_contract.sql under a test-only migration location. FlywayReceiptMigrationTest applies versions 1, 2 and 3 in separate steps against one H2 database. It asserts one executed migration at each step, three successful versioned history entries after version 3 and zero new executions on a second migrate call.

The test configures Flyway through its Java API. The dependency is test-scoped; the downloadable application does not run migrations on production startup. The older runner-boundary lesson now points to this checked fixture. Boot integration remains an explicit deployment choice.

Own the files, not just the final schema

Changing a SQL file after it has been applied changes what the version claims to mean. Commit migration files with the application change and review the old application against every intermediate schema. A migration version is not a license to skip the compatibility interval.

The first file creates one receipt table and a seed row. That seed is fixture data, not a recommendation to store business seed records in every production migration. Keep a separate procedure for large data backfills and target-engine DDL planning.

Checked source

Java
Flyway.configure().dataSource(source)
    .locations("classpath:db/relay-migration").target("2").load().migrate();
// The test then runs the old insert while tenant_id is nullable.

Verification boundary

FlywayReceiptMigrationTest.orderedFilesPreserveTheOldWriterUntilContract. The excerpt is shortened or a labelled design sketch; the kit contains the checked tests.

Costs and limits

Flyway runs through its Java API on H2 2.3.232. This is not a Spring Boot auto-configuration test or a deployment against PostgreSQL, MySQL or another production engine.

Common Mistakes

  • Do not call direct ALTER TABLE tests migration-history tests.
  • Do not edit an applied versioned file as a normal repair.
  • Do not place an unbounded production backfill in application startup.

Read next

Flyway expand and contract: show exactly when an old writer breaks, Flyway validation: detect a changed applied migration before another write, Spring Boot and Flyway: choose who runs migrations before traffic starts, Spring Boot migrations: what a versioned runner must add to the SQL test.

spring
spring-boot
migration
Storage details