Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 62 ยท Databases with Doctrine

Migrations

Evolve your database safely with Doctrine Migrations: make:migration, migrate, status, rollback, schema validation and production-safe changes, with a stand-in runner.

An application's database is never finished. You add a column, rename a table, create an index, and every developer machine, test server and production database has to follow the same steps in the same order. Editing the schema by hand does not scale, and recreating it from scratch would destroy data. The answer is migrations: small, versioned scripts that move the schema from one state to the next, and that are committed with your code.

In Symfony this is the job of the doctrine/doctrine-migrations-bundle, part of the ORM pack. The workflow is: change an entity, generate a migration that captures the difference, review it, commit it, and run it everywhere. This lesson covers the commands, what a migration file looks like, how to roll back and validate, and how to change a live production database without downtime. The real commands are read-only on this site; two stand-ins re-create the core mechanics (a version table and a runner, and a schema diff) on SQLite.

The workflow

flowchart LR
    E["Edit an entity"] --> M["php bin/console make:migration"]
    M --> F["migrations/Version2025....php"]
    F --> R["Review the SQL and commit"]
    R --> X["php bin/console doctrine:migrations:migrate"]
    X --> DB[("Database<br/>+ version table updated")]

Edit the entity, generate a migration, review it, then run it; the database records which versions have run.

Generating a migration

After you change an entity (say you add a $sku property to Product):

Terminal
php bin/console make:migration

The command compares your entity mapping with the current database schema and writes a class into migrations/ named after a timestamp, for example Version20250301093000. Because it diffs against the real database, the database you point DATABASE_URL at must be at the previous state; generating with an out-of-date local database gives a wrong migration. A generated migration looks like this:

PHP
<?php

declare(strict_types=1);

namespace DoctrineMigrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

final class Version20250301093000 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Add a SKU to products';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE product ADD sku VARCHAR(40) DEFAULT NULL');
        $this->addSql('CREATE UNIQUE INDEX UNIQ_PRODUCT_SKU ON product (sku)');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('DROP INDEX UNIQ_PRODUCT_SKU ON product');
        $this->addSql('ALTER TABLE product DROP sku');
    }
}

up() applies the change and down() reverses it. Notice that migrations collect SQL with addSql() and the runner executes it; the SQL is specific to the platform that generated it (MySQL syntax above). Always read the generated SQL: the diff tool is clever, but it cannot know your intentions. It cannot tell a renamed column from a dropped one plus a new one (the rename would lose data), and you should add data-fixing statements by hand.

Running, checking and undoing

Terminal
php bin/console doctrine:migrations:status        # versions, executed and pending
php bin/console doctrine:migrations:list          # every migration and its state
php bin/console doctrine:migrations:migrate       # run all pending migrations
php bin/console doctrine:migrations:migrate --dry-run
php bin/console doctrine:migrations:migrate prev  # go back one version
php bin/console doctrine:migrations:execute 'DoctrineMigrations\Version20250301093000' --down

The bundle stores executed versions in a table (doctrine_migration_versions by default) so each migration runs exactly once per database. migrate runs pending versions in order, --dry-run prints the SQL without executing, and in scripts you add --no-interaction (and --allow-no-migration if "nothing to do" should not be an error). Roll-back runs the down() method, so a down() that is empty or wrong makes rollback a lie; test it at least once locally.

config/packages/doctrine_migrations.yaml configures where migrations live (migrations_paths, mapping the DoctrineMigrations namespace to the migrations/ folder) and the version table name. In dev you can, and in CI you should, run the whole chain on an empty database to prove it builds from zero.

The first stand-in is a miniature of this machinery: a version table, a list of migrations with up and down, and a runner that applies only what is pending.

PHP A migration runner with a version table (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

How the diff works, and schema validation

make:migration is the diff idea made practical: read the desired schema from entity metadata, read the actual schema from the database, and emit the SQL that closes the gap. The second stand-in reduces it to its essence for adding columns, using SQLite's PRAGMA table_info.

PHP Generating a migration from a schema diff (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice the comment line for the leftover column. A real diff tool will happily generate a DROP COLUMN, and that is why you must read every migration before running it. To check, without generating anything, whether mapping and database agree, run:

Terminal
php bin/console doctrine:schema:validate

It verifies that the mapping is valid and that the database schema is in sync. Run it in CI after migrating a fresh database: if it complains, an entity changed without a migration. Do not use doctrine:schema:update --force outside throw-away experiments: it applies a diff directly, leaves no history and cannot be rolled back or reviewed.

Safe migrations in production

Running DDL against a live database is where migrations get dangerous. A few habits prevent most incidents:

  • Back up first, and rehearse the migration on a copy of production data to learn how long it takes. Adding an index to a table with 50 million rows can lock it for minutes on some engines.
  • Make changes backward compatible (expand and contract). The old code is still running while the new code deploys. To rename fullname to name: first add name and write to both, then backfill, then switch reads, and only in a later release drop fullname. Never rename or drop a column in the same release that stops using it.
  • Add columns nullable (or with a default), backfill in batches, and add NOT NULL afterwards. A NOT NULL column without a default breaks every INSERT from old code.
  • Split schema changes from data changes. A huge UPDATE inside the schema migration holds locks. Backfill with a console command or a Messenger job in small batches.
  • Know your engine's transaction rules. PostgreSQL and SQLite wrap DDL in a transaction, so a failed migration rolls back cleanly. MySQL commits implicitly after each DDL statement, so a migration that fails halfway stays half-applied. Keep MySQL migrations small, with one logical change each. A migration can opt out of the wrapping transaction by overriding isTransactional() and returning false, needed for statements such as CREATE INDEX CONCURRENTLY on PostgreSQL.
  • Never edit a migration that has run on a shared database; write a new one. Changing history makes environments diverge silently.
  • Run migrations once per deploy, from one place, not from every web server at boot (see Performance and Deployment).

Data fixes belong in migrations only when they are tiny and essential, for example $this->addSql("UPDATE product SET status = 'draft' WHERE status IS NULL"), so that the schema and its required data move together. Sample data for development belongs in fixtures, covered in Fixtures and Factories.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does php bin/console make:migration compare to produce its SQL?

    It diffs desired schema (from entity metadata) against the real database schema, so the database should be at the previous state when you run it.
  2. 2. How does Doctrine make sure a migration runs only once per database?

    The bundle keeps a table of executed versions (doctrine_migration_versions by default) and runs only pending ones.
  3. 3. Why is doctrine:schema:update --force discouraged on shared and production databases?

    Migrations are reviewed, versioned and repeatable. schema:update leaves no trace and cannot be replayed on other environments.
  4. 4. You want to rename a column on a live site with zero downtime. What is the safest approach?

    Expand and contract keeps old and new code working during the deploy. The destructive step comes only after nothing uses the old column.
  5. 5. A MySQL migration fails halfway. Why might it stay half-applied?

    MySQL has no transactional DDL. Keep MySQL migrations small so a failure leaves an easily fixed state.

Summary

  • Migrations are versioned scripts (up() and down()) that evolve the schema the same way on every environment; commit them with your code.
  • make:migration diffs entities against the database; always review the generated SQL, especially renames and drops.
  • doctrine:migrations:migrate runs pending versions (once each, tracked in a version table); prev, execute --down and --dry-run help you step back and preview.
  • doctrine:schema:validate checks that mapping and database agree; avoid schema:update --force outside experiments.
  • In production, back up, rehearse, make changes backward compatible (expand and contract), split schema from data changes and never edit executed migrations.

Next up: Repositories and Queries.