Migrations concept
Migrations are versioned scripts that change your database structure step by step and can be undone.
In this page:
Migrations concept
Each migration has an up step to apply a change and a down step to revert it, and a table records which have run. This keeps every environment's schema in sync and reviewable in git. Tools include Knex, Prisma Migrate and Sequelize CLI.
Note:
Never edit a migration that has already run in production; add a new one.
Example: Migrations concept
const applied = new Set();
const migrations = [
{ id: 1, up: () => "CREATE TABLE users (id INT)", down: () => "DROP TABLE users" },
{ id: 2, up: () => "ALTER TABLE users ADD name TEXT", down: () => "ALTER TABLE users DROP name" },
];
for (const m of migrations) if (!applied.has(m.id)) { console.log("up ", m.id, m.up()); applied.add(m.id); }
const last = migrations[migrations.length - 1];
console.log("down", last.id, last.down());
// Output:
// up 1 CREATE TABLE users (id INT)
// up 2 ALTER TABLE users ADD name TEXT
// down 2 ALTER TABLE users DROP name
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Editing old migrations
- Making manual schema changes
- Forgetting the down step
Chapter Summary
- Migrations version schema changes
- up applies, down reverts
- A table tracks applied ones
- Commit them to git
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: