Search code examples
symfonydatabase-migrationphp-deployer

How can you check if there are migrations while running a deploy using deployer


I'm using Deployer to deploy my Symfony application to production. All is working fine, however, my deploy.php file has the command for database migrations:

/**
* Run a diff to generate migrations, 
*/
task('database:diff', function () {

run('{{bin/php}} {{release_path}}/' . trim(get('bin_dir'), '/') . '/console doctrine:migrations:diff --env={{env}} --no-debug --no-interaction');

})->desc('Generate migrations database');

...

after('deploy:symlink','database:diff');
after('database:diff','database:migrate');

But if there are no changes to the database then this step causes an error.

Error message:

[RuntimeException]                                                                                                                                                                                      

[Doctrine\DBAL\Migrations\MigrationException]                                                                                                                                                         
Could not find any migrations to execute.

I'm looking for some code that can check for any database change and only conditionally run the migrations tasks if there are changes.


Solution

  • Well, this is strange approach to automate migrations and database versioning.

    That's how we do that:

    Every developer generates their migrations;

    1. Add/remove fields in your entity (or create a new entity)
    2. Run $ php app/console doctrine:migrations:diff migration is created locally.
    3. Developer then opens that migration to ensure everything is fine, or adds their additional migration queries/migrations etc.
    4. Then they commit/push that migration to repository, so that all migrations are versioned by git.
    5. Other developers pull these migrations and run them on their local machines if necessary.

    During deployment, there is no need to run diff, because all diffs are in git repository, so you just run database:migrate to update you prod database to a latest version.

    Hint: When generating migrations, it is good practice to generate one migration per entity/database table, as if some sql queries would fail in your big migration, it would be difficult to rollback these who have been executed already.