Sub topic 10
Adopting Flyway on an existing database
This chapter assumes you can already write versioned migrations, read the flyway_schema_history table, and set spring.flyway.* properties. It also assumes you can run pg_dump against PostgreSQL. Here you will bring Flyway to a database that already has tables, data, and no migration history.
The problem with a non-empty schema
Flyway tracks state in the flyway_schema_history table. A database that predates Flyway has no such table, but it may hold years of tables and rows. If you add Flyway and start the application, Flyway sees a non-empty schema with no history and stops:
FlywayException: Found non-empty schema(s) "public" but no schema history table.
Use baseline() or set baselineOnMigrate to true to initialize the schema history table.This is a safety check. Flyway cannot know whether the existing tables match your V1 script, so it refuses to guess. A baseline is how you tell it: "the database is already at version N, so start counting from there."
What a baseline is
A baseline creates the history table and inserts one marker row. The row has type BASELINE, the version you chose, and the default description << Flyway Baseline >>. No SQL from your migration files runs.
After that, Flyway treats every migration with a version at or below the baseline as already covered. It skips those migrations, and info reports them as "Below Baseline". Migrations above the baseline are pending and apply in order.
SELECT installed_rank, version, description, type, success
FROM flyway_schema_history
ORDER BY installed_rank; installed_rank | version | description | type | success
----------------+---------+------------------------+----------+---------
1 | 1 | << Flyway Baseline >> | BASELINE | t
2 | 2 | add display name | SQL | tPlan the two kinds of environment
Adopting Flyway usually involves two groups of databases that must end up identical.
- Existing environments, such as production and staging, already contain the schema. They need a baseline.
- New environments, such as a developer laptop, CI, or a fresh test database, start empty. They need a script that builds the old schema from nothing.
The standard approach serves both with one file. You capture the current schema as V1__baseline.sql. Existing databases are baselined at version 1, so they skip it. Empty databases run it and get the same schema.
Step 1: Capture the current schema
Dump only the structure of the schema from a database that matches production, with no data. Skip ownership and privilege statements so the script works under any role.
pg_dump --schema-only --no-owner --no-privileges \
--schema=public \
--file=src/main/resources/db/migration/V1__baseline.sql \
"postgresql://app@localhost:5432/appdb"Then clean the file by hand.
- Remove any
flyway_schema_historydefinition if the dump contains one. - Remove the line
SELECT pg_catalog.set_config('search_path', '', false);. It clears the session search path, and Flyway's later statements on the same connection can fail or land in the wrong schema. - Remove
CREATE EXTENSIONorCOMMENT ON EXTENSIONlines if your deployment role cannot create extensions. Create those once, outside Flyway. - Read the file. A dump is generated code, so check it as you would any other change.
If the schema has reference data the application needs, such as a table of country codes, add INSERT statements to the same file or to a V1.1 file. --schema-only leaves them out.
Step 2: Choose the baseline version
The baseline version must be at or above the version of the last script that describes the existing schema. For a single dump named V1__baseline.sql, that version is 1.
The default spring.flyway.baseline-version is 1, so the default fits this layout.
The default also causes a common mistake. Suppose you keep the default baseline of 1 and your first new migration is also V1__add_column.sql. Flyway treats V1 as covered by the baseline and never runs it. Always start new work above the baseline version. The baseline script is V1, and the first real change is V2.
Step 3: Configure the baseline
For Spring Boot, enable baselining on migrate:
spring:
flyway:
enabled: true
locations: classpath:db/migration
baseline-on-migrate: true
baseline-version: "1"
baseline-description: Pre-Flyway production schema
jpa:
hibernate:
ddl-auto: validateWith baseline-on-migrate: true, Flyway applies this rule when it starts:
- History table exists: nothing changes, and the baseline setting is ignored.
- No history table and the schema is empty: Flyway runs migrations from
V1. It does not baseline. - No history table and the schema is non-empty: Flyway creates the history table, inserts the baseline row, then applies anything above the baseline version.
Quote the version in YAML. An unquoted 1.0 becomes a number and can lose its form, for example 1.10 turns into 1.1.
Start the application against a copy of production first. Then query the history table. You should see exactly one BASELINE row, followed by any pending migrations you added.
Why baseline-on-migrate can be risky
The setting is convenient, and it also removes the check from the earlier error. If the application is pointed at the wrong database, one that contains unrelated tables and has no history, Flyway baselines it silently and then applies your migrations on top of it.
Use these practices to reduce the risk:
- Keep
baseline-on-migratein a one-off profile or environment variable, for exampleSPRING_FLYWAY_BASELINE_ON_MIGRATE=true. Use it for the first deploy to each environment. - Remove it once every existing environment has a history table. After that it has no effect on those databases and only guards against mistakes.
- Alternatively, baseline explicitly outside the application. The Flyway CLI command
flyway baseline -baselineVersion=1runs only the baseline step, and you can run it as a reviewed deployment action.
Step 4: Confirm the schemas match
A baselined database and a database built from V1 must have the same structure. If they differ, later migrations succeed in one environment and fail in the other. Check three ways:
- Compare a fresh
pg_dump --schema-onlyof a database built by Flyway with one from production. Differences in constraint names, defaults, or index definitions are real drift. - Keep
ddl-auto: validate. Hibernate checks that entities match tables on startup, which catches missing or mistyped columns. - Build a new database from
V1in an automated test and run your application's integration tests against it. Later chapters cover this in more detail.
Drift is common in databases with a long history. Someone added an index by hand, or a column type differs between staging and production. Decide which version is correct, then fix the other environments with a normal migration, such as V2__align_indexes.sql. Do not make V1 describe a mix of the two.
Edge cases
| Situation | What happens | What to do |
|---|---|---|
| Baseline version is lower than an existing script, for example baseline `1` with `V1` and `V2` already live in production | Flyway applies `V2` again | Set the baseline to `2`, or delete the old scripts and use one dump |
| Baseline version is higher than any file | Every file is skipped | Check the version you set |
| History table exists but has no `BASELINE` row and no migrations | Flyway applies from `V1`, with no baseline step | Delete the empty table and baseline, or run `baseline` with the CLI |
| Several schemas | Each schema needs its own baseline and history | Set `spring.flyway.schemas` and test each one |
| Baseline was done at the wrong version | Wrong scripts are skipped or re-run | Delete the baseline row only on a test copy. In production, take a backup, then fix the history table with `repair` or a supervised update |
If production already has V1 and V2 in a scheme of your own and you want to keep that numbering, baseline at 2. The marker row then tells Flyway that everything up to V2 is done.
Summary of the workflow
- Dump the schema into
V1__baseline.sqland clean it. - Set
baseline-versionto1and enablebaseline-on-migratefor the first deploy. - Write all new changes as
V2and higher. - Test on a copy of production, then in staging, then in production.
- Verify the
BASELINErow in each environment, then removebaseline-on-migrate.
Exercise
A production database has 40 tables and no history table. You add Flyway, keep the default baseline version, and add V1__baseline.sql (a schema dump) and V1__add_audit_column.sql is not used. You enable baseline-on-migrate. A developer starts the app on an empty local database. What does Flyway do in production and locally?
Show answer
In production, the schema is non-empty and has no history, so Flyway creates the history table, inserts a BASELINE row at version 1, and skips V1__baseline.sql. It applies only migrations above version 1. Locally, the schema is empty, so Flyway does not baseline. It runs V1__baseline.sql and every later migration, and both databases end with the same structure.
Exercise
You baselined at the default version 1 and then added V1__add_index.sql as your first new migration. Why does the index never appear, and how do you fix it?
Show answer
Flyway treats every migration at or below the baseline version as already applied, so V1__add_index.sql is skipped. Rename it to V2__add_index.sql (or higher). Since it was never applied, no history row exists for it, and renaming is safe.