Search code examples
doctrine-ormenumsdoctrinedbal

Doctrine 2 - How to update schema with new enum values?


Following Doctrine 2's enum defining a type guide, I have the following class:

class EnumStatusType extends EnumType
{
    protected $name   = 'enumStatusType';
    protected $values = [
        'active',
    ];
}

Now, using vendor/bin/doctrine-module migrations:diff, or vendor/bin/doctrine-module orm:schema-tool:update or whichever you prefer, it successfully creates the column with the enum:

status ENUM(\'active\') COMMENT \'(DC2Type:enumStatusType)\' NOT NULL

Now, I wanted to add a second value, inactive. But after running orm:validate-schema, orm:schema-tool:update migrations:diff, none of them notices there is a new value.

How can I make it so that it detects this type of changes, so that a new migration can be made with migrations:diff?

PS: I'm using ZF2, with the DoctrineORMModule. Not that it should matter though.


Solution

  • You can try adding the enum values list in each field comment option, using the postGenerateSchema event:

    class EnumListener
    {
        public function postGenerateSchema(\Doctrine\ORM\Tools\Event\GenerateSchemaEventArgs $eventArgs)
        {
            $columns = [];
    
            foreach ($eventArgs->getSchema()->getTables() as $table) {
                foreach ($table->getColumns() as $column) {
                    if ($column->getType() instanceof EnumType) {
                        $columns[] = $column;
                    }
                }
            }
    
            /** @var \Doctrine\DBAL\Schema\Column $column */
            foreach ($columns as $column) {
                $column->setComment(trim(sprintf('%s (%s)', $column->getComment(), implode(',', $column->getType()->getEnum()::toArray()))));
            }
        }
    }
    

    Works for the orm:schema-tool:update command, I suppose it's the same for migrations:diff