| sidebar_position | 6 |
|---|---|
| title | Database Migrations |
| sidebar_label | 6. Database Migrations |
| description | Learn how to manage changes to your database schema safely and consistently across your entire team. |
Imagine you are working in a team of 5 developers at CodeHarborHub. You decide to add a profile_picture column to the Users table. You run the SQL command on your local computer, and everything works.
But when your teammate pulls your code, their app crashes. Why? Because their local database doesn't have that new column. Migrations solve this "It works on my machine" problem.
A migration is a small file (usually JS, TS, or SQL) that describes a specific change to the database. These files are saved in your Git repository along with your code.
Each migration file usually has two parts:
- Up: The instructions to apply the change (e.g.,
ADD COLUMN bio). - Down: The instructions to undo the change (e.g.,
DROP COLUMN bio).
Instead of manually typing SQL in a terminal, a professional developer follows this cycle:
- Create Migration: You run a command to generate a new file.
- Write Logic: You define the change (e.g., "Create a table called
Lessons"). - Run Migration: The tool executes the SQL and updates your local DB.
- Commit to Git: Your teammates pull the file and run it. Now everyone is perfectly synced!
At CodeHarborHub, we often use Prisma. Here is what a small migration looks like in the background:
-- Migration: Add bio to Users
-- UP
ALTER TABLE "Users" ADD COLUMN "bio" TEXT;
-- DOWN
ALTER TABLE "Users" DROP COLUMN "bio";- [x] I understand that migrations are "Version Control" for the database.
- [x] I know that migration files should be saved in Git.
- [x] I understand the difference between Up (Apply) and Down (Undo).
- [x] I recognize that migrations prevent "schema mismatch" errors in teams.
:::warning The Golden Rule Never manually change your database structure in a production environment. Always use a migration. If you skip a migration, your code and your database will eventually "drift" apart, leading to nightmare bugs! :::