Lesson 18 / 35

Why Migrations Beat Auto-Sync

Explain what a migration is, how the ORM tracks which ones ran, and why auto-sync is unsafe for shared or production databases.

By · 15 years in web development

Version control for your database

Your code lives in Git, so every teammate and every server can reach the same version. The database schema needs the same discipline. A migration is a small, ordered script, usually SQL or code that produces SQL, that moves the schema from one version to the next: create a table, add a column, add an index. Each migration is committed with the code that needs it. The ORM records which migrations have already run in a bookkeeping table (_prisma_migrations for Prisma, migrations for TypeORM by default, SequelizeMeta for Sequelize CLI) and applies only the pending ones, in order. Contrast this with auto-sync (synchronize: true in TypeORM, sequelize.sync({ alter: true })): the ORM compares models with the live database and changes it directly. Auto-sync leaves no reviewable history, may guess wrong about renames, and can drop data. It is acceptable for a throwaway prototype, never for a shared or production database.

The migration workflow

Change the model, generate or write a migration, read the SQL it contains, then let the deploy pipeline apply it.

Four connected stages: edit the schema or models, generate a migration, review the generated SQL, apply the migration during deployment.
Figure 6.1: edit schema -> generate migration -> review SQL -> apply on deploy

Minutes of a society meeting

A housing society does not just repaint the gate; it records 'Resolution 14: repaint gate' in the minutes book. Anyone joining later can read the resolutions in order and know exactly how things got to their current state. Migrations are those minutes for your schema.

Expand, then contract

Renaming a column in one step breaks the old version of your app that is still running during a deploy. Safer: add the new column, deploy code that writes both and reads the new one, backfill old rows, then drop the old column in a later migration. This expand-and-contract pattern is a common interview topic for zero-downtime deploys.

Quick check: How does an ORM know which migrations still need to run on a database?

  • It compares file modification dates with the server clock
  • It reruns every migration each time and ignores errors
  • It reads a bookkeeping table in that database that lists applied migrations
  • It asks the developer interactively in production
Answer

It reads a bookkeeping table in that database that lists applied migrations — Each ORM stores applied migration names in a table such as _prisma_migrations, migrations or SequelizeMeta, and applies only those not yet recorded.