AI Hints
Home›CI/CD with GitHub Actions Tutorial›Migrations and Delivery Practice
CI/CD with GitHub Actions · Lesson 97 of 138

Database Migrations

Changing the schema.

⏱ 2 min read▶ Video at 1:51:58🎓 Free
Watch this lesson in the CI/CD with GitHub Actions courseWatch on YouTube ↗Full CI/CD with GitHub Actions course

Code is easy to roll back, but data isn't. When a release needs a new table or column, you change the database with a migration. A small script, with a number, that runs once, in order.

Database Migrations
From the video: Database Migrations
  • Data can't just roll back
  • Migrations change the schema
  • Numbered, run once

A tiny migration runner

There are two migration files. One creates the orders table. One adds a column. The runner applies any it hasn't applied yet, and records them in a done table. The first run applies both. The second run applies nothing, because the database is up to date. That's what makes it safe to run on every deploy.

Terminal
ls migrations
001_create_orders.sql  002_add_status.sql
cat migrations/002_add_status.sql
ALTER TABLE orders ADD COLUMN status TEXT DEFAULT 'new';
python3 migrate.py
applied 001_create_orders.sql
applied 002_add_status.sql
database is up to date
python3 migrate.py
database is up to date

Safe migrations

Run migrations as a pipeline step, before the new code starts. Make changes backward compatible, so the old code still works with the new schema, in case you roll back. Add a column first, and remove the old one in a later release. And back up the database before big changes.

keyvalue
A pipeline stepbefore new code
Backward compatibleold code still works
Expand, then contracttwo releases
Back upbefore big changes

Summary

Migrations are numbered scripts that change the schema once, in order. Keep them backward compatible, so rollbacks still work. Next, practice deploying on a tag.

Key takeaways
  • Numbered scripts
  • Run once, in order
  • Backward compatible
Next up: Practice: Deploy on Tag — test, then ship