Custom plugin: adding and applying migrations

Hi, I’m trying to develop some custom plugin, and trying to add some columns to the database. I need to create additional column in the existing ‘emails’ table. My code with namespaces below

It seems what I need to change some settings or do something else, because Mautic console doesn’t see my migration at all.

So question is: how to add and apply the migration in the plugin properly? I need to do this without any changes in the core Mautic code.

<?php

declare(strict_types=1);

namespace MauticPlugin\MyPluginBundle\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\SchemaException;
use Mautic\IntegrationsBundle\Migration\AbstractMigration;

class Version_0_0_1 extends AbstractMigration
{
    private $table = 'emails';

    protected function isApplicable(Schema $schema): bool
    {
        try {
            return !$schema->getTable($this->concatPrefix($this->table))->hasColumn('replace_api_key');
        } catch (SchemaException $e) {
            return false;
        }
    }

    protected function up(): void
    {
        $this->addSql("
            ALTER TABLE `{$this->concatPrefix($this->table)}`
            ADD `replace_api_key` varchar(255) NULL
        ");
    }
}

Make sure that plugin version in config/Config.php matches the version in migration file.

Also make sure that plugin with that version is not already in database when you run reload or install (update or delete the entry if itis)

1 Like

Thank you for reply, I tried to remove it from ‘plugins’ table, then cleared the cache and install it again. Version of plugin was ‘0.0.1’, i changed to ‘0.0.2’ and changed the name of the migration to ‘Version_0_0_2’. Then i’ve installed it, it is appeared in the ‘plugins’ table, but migration wasn’t applied and table ‘emails’ wasn’t changed.

Hmm strange, it works in my bundle and I extend the same base class. For the record file is named ‘Version_0_0_2.php’ right and its located in Migrations directory of your bundle right?

As you can see here, mautic core is using dedicated base class to run migrations: mautic/Version20180921144421.php at 8a57278758e2c3e1c1ca987aaf9ebd5f05b3c877 · mautic/mautic · GitHub

You might give it a go, since you are still struggling.

Well, that was my fault, i’m not experienced in Symfony, and didn’t created any Entity class, but it seems required to apply migrations and database changes. I didn’t change the base Email entity class and created new table and simple Entity with two fields (email_id and replace_api_key) instead, changed the migration accordingly, after that all db changed was applied.