Database Migrations
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.
What is a Migration?
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).
The Migration Workflow
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!
Why use Migrations?
- 📜 History
- 🛡️ Safety
- 🤖 Automation
You can see exactly who changed the database, when they changed it, and why.
If a database change breaks the app, you can "Rollback" to the previous version in seconds.
When you deploy your app to a server (like AWS or Vercel), the server can automatically update the database during the build process.
Example: A Migration File (Prisma)
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";
Summary Checklist
- I understand that migrations are "Version Control" for the database.
- I know that migration files should be saved in Git.
- I understand the difference between Up (Apply) and Down (Undo).
- I recognize that migrations prevent "schema mismatch" errors in teams.
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!