Schema Migrations
Change a database schema with numbered, versioned files that run once, in order, so every environment ends up identical.
Version control for the database shape
A migration is a file with the SQL that moves a database from one version of its schema to the next: create a table, add a column, add a rule. Migrations are numbered, kept in your repository next to the code, and applied in order by a migration tool, such as Flyway.
The tool keeps a history table inside the database that records which migrations have already run, together with a checksum (a fingerprint) of each file.
Same schema on every machine
Your laptop, the test server and production must have the same tables, or the code that works on one fails on another. Typing ALTER TABLE by hand on each one does not scale. With migrations, to bring any database up to date you run the tool, and it applies what is missing, once, in order.
Run migrate
V1__create_products.sql
V2__seed_products.sql
V3__add_price.sql
V4__price_is_required.sqlOn an empty database the tool applies V1, V2 and V3 in version order and records each in the history table. Run it again and nothing happens, because every file is already there: running migrate is safe to repeat.
V4 runs ALTER TABLE products ALTER COLUMN price SET NOT NULL, but the rows added in V2 have no price, so PostgreSQL refuses: column "price" of relation "products" contains null values. Each migration is one transaction and PostgreSQL can roll back DDL, so V4 leaves no trace: the table is exactly as V3 left it, and V4 is not in the history.
Because V4 was never applied, you can simply fix the file. Fill in the prices first, then add the rule, and run migrate again. Now V4 is applied.
Replay a migration tool
Press Run migrate and read the failure. Then fix V4 and run again. Next edit V2 and run migrate, and finally add V5.
| filetext | statustext |
|---|---|
| V1__create_products.sql | pending |
| V2__seed_products.sql | pending |
| V3__add_price.sql | pending |
| V4__price_is_required.sql | pending |
| versioninteger | descriptiontext | checksumtext |
|---|
No tables yet. Run migrate to create them.
Pick an action. Start with Run migrate, then try the others.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A migration is a numbered SQL file. A tool applies the missing ones once, in order, and records them in a history table with a checksum.
- Running migrate again is safe: applied files are skipped.
- Each migration is one transaction. In PostgreSQL a failed one leaves no trace, because DDL can be rolled back.
- Never edit a migration that has run, because validation will fail. Add a new one that fixes it.
Done with this concept?
Mark it complete to track your progress. No login needed.