Skill: Create a Database Migration

Skill: Create a Database Migration

Steps

1. Generate Migration

php bin/console doctrine:migrations:diff

Or create manually:

php bin/console doctrine:migrations:generate

2. Review and Edit

  • Ensure table names use module prefix: {module}_{entity}
  • Add tenant_id column to every table
  • Add created_at and updated_at timestamps
  • Use UUID type for primary keys
  • Add indexes on foreign keys and tenant_id

3. Migration Template

declare(strict_types=1);

namespace DoctrineMigrations;

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

final class Version{Timestamp} extends AbstractMigration
{
    public function getDescription(): string
    {
        return '{Module}: create {entity} table';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('CREATE TABLE {module}_{entities} (
            id UUID NOT NULL,
            tenant_id UUID NOT NULL,
            -- ... columns
            created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
            updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
            PRIMARY KEY (id)
        )');

        $this->addSql('CREATE INDEX idx_{module}_{entities}_tenant_id ON {module}_{entities} (tenant_id)');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('DROP TABLE {module}_{entities}');
    }
}

4. Test

# Apply migration
php bin/console doctrine:migrations:migrate

# Verify on clean database
make db-reset

5. Rules

  • One migration per logical change
  • Must be reversible (include down())
  • Never modify a deployed migration
  • Always include tenant_id
  • Always include created_at/updated_at