Sub topic 1
Why Version Your Database Schema
This chapter explains the problem that schema migration tools solve and the model that Flyway uses to solve it. Later chapters add Flyway to a project and write migrations. Here you learn why a tool is worth using and what it changes about how you work.
Prerequisites
This chapter assumes you have:
- Basic Spring Boot knowledge, including starters and
application.ymlorapplication.properties. - Working knowledge of SQL DDL (
CREATE,ALTER,DROP) and DML (INSERT,UPDATE,DELETE). - Familiarity with Maven or Gradle dependencies.
- A basic understanding of a relational database such as PostgreSQL.
- A basic Git workflow: branches, pull requests, and merges.
The problem: code is versioned, the schema is not
Your application code lives in Git. Every change has an author, a date, a diff, and a review. You can check out last month's commit and get last month's code.
The database schema is often treated differently. A developer opens a SQL console, runs an ALTER TABLE, and moves on. The change exists only in that one database. Nothing in the repository records it.
This works for a while on a single laptop. It breaks down as soon as there is more than one database, which in practice means:
- Each developer has a local database.
- A CI server creates a database for tests.
- A staging environment mirrors production.
- Production holds real data and must never be rebuilt from scratch.
Each of these databases must end up with the same structure as the code expects. If they drift apart, the application fails in ways that depend on where it runs.
What goes wrong without versioning
The following failures are common when schema changes are applied by hand or by ad hoc scripts.
- Missing column in one environment. A developer adds
display_namelocally and pushes code that reads it. Tests on CI fail withcolumn "display_name" does not exist, or worse, production fails after deployment. - Unknown state. Nobody can say which changes production has received. To find out, someone compares schemas by eye.
- Forgotten scripts. The change was written down in a wiki page or a chat message. It is applied in staging but skipped in production.
- Wrong order. Two scripts depend on each other, such as creating a table and then adding a foreign key to it. Run in the wrong order, the second one fails or leaves the schema half changed.
- Double application. A script that is not safe to repeat runs twice. An
INSERTof reference data creates duplicates, or anALTER TABLEfails midway. - No way to rebuild. A new team member or a new CI job cannot create a working database from the repository alone.
All of these have the same cause. The schema's history is not stored with the code, so the code and the database can disagree without anyone noticing.
Letting Hibernate create the schema is not a migration strategy
Spring Boot with JPA offers a shortcut. The property spring.jpa.hibernate.ddl-auto can be set to update or create, and Hibernate then changes the schema to match your entity classes.
This is convenient for a prototype, but it has limits that matter once real data exists.
- It cannot express every change. Renaming a column looks to Hibernate like dropping one column and adding another, and data in the old column is lost.
- It does not move data. If you split
full_nameintofirst_nameandlast_name, Hibernate will not copy values. - It is not reviewable. There is no file in a pull request showing what will run against production.
- It is not repeatable. The result depends on the state of the database at startup, so two environments can end up different.
- It cannot track what has been applied. It only compares the current state to the entities.
For these reasons, the common production setup is to let a migration tool own the schema and let Hibernate only check it. A later chapter shows that configuration.
The migration model
A schema migration tool replaces ad hoc changes with a simple model.
- Every change to the schema is written as a migration, a small script stored in the repository.
- Each migration has a version that defines its order.
- The tool keeps a record inside the database of which migrations have already been applied.
- When the tool runs, it compares the scripts in the repository to that record and applies only the ones that are missing, in order.
The result is that the repository fully describes how to build the schema from an empty database. It also describes how to bring an older database up to date.
The same set of files produces the same schema whether the database is empty, a week behind, or a year behind. A fresh developer database runs every migration. Production runs only the new ones.
Where Flyway fits
Flyway is a migration tool for relational databases. In Flyway, a migration is usually a plain SQL file whose name carries the version, for example V1__create_app_user.sql. Flyway stores its record in a table named flyway_schema_history, which it creates in your database.
Spring Boot integrates Flyway directly. If Flyway is on the classpath, Spring Boot configures it and runs it when the application starts, before your repositories and entities are used. The application therefore never starts against an out-of-date schema.
Flyway is one of several tools. Liquibase is the best-known alternative. It describes changes in XML, YAML, JSON, or SQL changelogs and can generate database-specific SQL from a neutral format. Flyway's approach is more direct: you write the SQL for your database yourself. The tradeoff is that your migrations are tied to one database's SQL dialect, but they stay easy to read and to review.
What the model gives you
| Without versioned migrations | With Flyway-style migrations |
|---|---|
| Schema changes live in consoles, chats, or wikis | Schema changes are files in Git |
| Each environment may differ | Each environment is brought to the same version |
| Order depends on human memory | Order is defined by the version number |
| Review of schema changes is informal | Changes go through pull requests like code |
| Building a new database is manual | A new database is built by running the migrations |
| Production state is unclear | The history table states what has been applied and when |
A first look at a migration
You do not need to set anything up yet. The example below shows what a first migration looks like, so the model above is concrete.
-- src/main/resources/db/migration/V1__create_app_user.sql
CREATE TABLE app_user (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
username VARCHAR(100) NOT NULL UNIQUE,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);The file name has three parts: the prefix V, the version 1, and, after two underscores, a description. Flyway runs this file once and then records it. If the application starts again, Flyway sees that version 1 is already applied and does nothing.
When you later need a new column, you do not edit this file. You add a new one:
-- src/main/resources/db/migration/V2__add_display_name.sql
ALTER TABLE app_user ADD COLUMN display_name VARCHAR(200);Version 2 runs on every database that has only version 1. A new database runs both files in order.
The core rules
Several rules follow from the model, and the rest of the tutorial builds on them.
- Applied migrations are immutable. Once a migration has run anywhere beyond your own machine, it is never edited. Flyway stores a checksum of each applied file and detects changes. To change the schema again, add a new migration.
- Order is by version, not by date written. Version numbers decide the order. Two developers who pick the same number cause a conflict, which a later chapter covers.
- Migrations are forward only. The free edition of Flyway applies changes upward. To undo a change you write a new migration that reverses it.
- Migrations run on every environment. Developers, CI, staging, and production all use the same files. Do not keep an environment-specific shortcut.
- Migrations are code. They are reviewed, tested, and merged like any other change.
Costs and limits to know about
Versioned migrations are not free, and it helps to know the costs early.
- Discipline is required. The model only works if all schema changes go through migrations. A change made by hand in production creates drift that the tool does not repair on its own.
- A failed migration needs attention. On databases that support transactional DDL, such as PostgreSQL, a failed migration rolls back. On databases that do not, such as MySQL, a half-applied migration can leave the schema in an intermediate state that you must fix manually.
- Long migrations hold locks. Some
ALTER TABLEstatements lock a large table. A migration that is fine on a small test database can block production traffic. Later chapters cover safe patterns. - The history grows. Hundreds of small migrations are normal, and a fresh database runs all of them. This is usually fast enough, but it is a reason to keep migrations small and fast.
What the rest of the tutorial covers
The following chapters follow the order in which you use Flyway in practice. You will add Flyway to a Spring Boot project, write versioned SQL migrations, and see what happens at startup. You will read the history table and configure Flyway with spring.flyway properties. You will coordinate it with Hibernate, add repeatable and Java migrations, and handle checksum failures. You will adopt Flyway on an existing database and test migrations. The last chapters cover team conflicts, backward-compatible changes, and production practice.
Exercise
A teammate fixes a typo in a column default by editing V1__create_app_user.sql, which was already applied to the staging database. Why is this a problem, and what should they do instead?
Show answer
Flyway stores a checksum of each applied migration. After the edit, the file no longer matches the checksum recorded in staging's history table, so validation fails and the application will not start there. Environments that ran the old version also keep the old default, so the change would not reach them. The teammate should revert the edit and add a new migration, such as V3__fix_created_at_default.sql, containing the ALTER TABLE statement for the fix.
Exercise
Name three reasons why spring.jpa.hibernate.ddl-auto=update is not enough for a production system that holds real data.
Show answer
Any three of these: it cannot express a rename and treats it as drop plus add, losing data; it does not move or transform data; its changes are not visible in a pull request; the result depends on the database's current state, so environments can differ; it keeps no record of what has been applied.