Handling migration history

Hello everybody,

Quick presentation; I’m Tom, a dev from Antwerp, Belgium. Been a PHP developer for almost 10 years now, worked with a range of frameworks (CI, Zend, Symfony…) and did a lot of Drupal. Some C# and Angular experience as well.

So now my issue…

I have been working on an existing Yii2 application for a couple of months. The current application is installed on premise or remote for each client. Now I want to make this application multi-client, for this I want to split up the application database into a application database and a client database for each different client.

This means that everytime an administrator creates a new client or entity as I called it, a new database gets created and the necessary migrations should be run. Because this is a rather large application I would like to reuse all existing migrations that were created in the past.

I started working on a PoC this week and after some tinkering I have got it working, sort of.

Client database gets created through a prepared statement, with a name based on uid stored in the application db’s entity table. No problem there.

Then I run the needed migrations like this:




$this::setDb(

  new \yii\db\Connection([

    'dsn' => 'mysql:host=localhost;dbname=' . $this->_entity->dbname,

    'username' => 'the_username',

    'password' => 'the_password',

  ]);

);

$migration = new \yii\console\controllers\MigrateController('migrate', Yii::$app);

$migration->runAction('up', ['migrationPath' => '@app/modules/topology/datamigrations', 'interactive' => false]);



The tables & stuff get created in the newly created client database. But the migration history gets written to the migration table in the application database, which means that when the next client gets created these migrations will not run.

Preferably I would like the migration history on the database it gets run on. Is there a way to do this?

Other ideas to make this setup work?

Hope to hear your thoughts,

Cheers,

Tom

MigrateController has $db property it uses by default. It is used to write migration history so I’d try launching it like that:




$db = new \yii\db\Connection([

    'dsn' => 'mysql:host=localhost;dbname=' . $this->_entity->dbname,

    'username' => 'the_username',

    'password' => 'the_password',

]);


$this::setDb($db);

$migration = new \yii\console\controllers\MigrateController('migrate', Yii::$app, ['db' => $db]);

$migration->runAction('up', ['migrationPath' => '@app/modules/topology/datamigrations', 'interactive' => false]);



1 Like

Thanks Sam!

That’s exactly what I needed, now the migration gets done on the correct db and the migration history gets stored in this same db. Nice, now I can rap up this PoC before the end of the week.

1 Like