Sub topic 1
Why Version Your Database Schema
Prerequisites
Assume you know basic Spring Boot configuration, SQL DDL and DML, Maven or Gradle dependencies, and relational databases such as PostgreSQL. You should also know basic Git workflow.
Why Version Your Database Schema
An application and its database must change together. Manual database changes are difficult to repeat, review, or reproduce in another environment. A schema migration is a recorded change to database structure or data. A migration tool applies these changes in a known order.
Flyway stores migrations with the application source code. Developers can create the same schema in local, test, staging, and production databases. Code review can also examine the SQL before it runs.
Adding Flyway to a Spring Boot Project
Add Flyway and the database-specific module to your build. For PostgreSQL, a Maven configuration includes:
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-database-postgresql</artifactId>
</dependency>Spring Boot finds Flyway and configures it from the application's datasource settings. The migration files normally live in src/main/resources/db/migration.
Writing Versioned SQL Migrations
A versioned migration runs once. Its filename follows this pattern:
V<version>__<description>.sql
The separator is two underscores. For example:
-- 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
);To change the table later, add a new file. Do not edit an applied migration.
-- src/main/resources/db/migration/V2__add_display_name.sql
ALTER TABLE app_user ADD COLUMN display_name VARCHAR(200);Flyway compares migration versions and applies pending files in order.
What Happens When the Application Starts
Spring Boot creates the datasource, then Flyway checks its migration location and its history table. Flyway applies pending migrations before the application finishes starting. If a migration fails, startup normally fails too, preventing the application from using an incomplete schema.
Exercise
Where should a later change to the app_user table be recorded?
Show answer
In a new, higher-numbered migration file such as V2_adddisplay_name.sql.