cakephp / cakephp/phinx

Conditional migration

Open
#1,619 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
Dominant language
PHP
Stars
4.5k
Forks
884
PR merge metrics
No merged PRs in 30d

Description

Hello, is it possible to conditionally execute a migration?

I'm working on a software that communicates with a few databases of different types. Depending on its type, (e.g. X or Y) a migration should or should not be executed
Example:

DB type Migration 1 Migration 2 Migration 3
X
Y

I'm currently doing it this way:

<?php

class Migration2 extends AbstractConditionalMigration
{
    
    public function change()
    {
        if ($this->shouldExecute()) {
            // migration script
        }
    }

    public function isTypeX(): bool
    {
        return false;
    }

    public function isTypeY(): bool
    {
        return true;
    }
}

where "shouldExecute" is a method implemented by AbstractConditionalMigration that verifies the type of the target environment and, based on the returned value of isTypeX() and isTypeY(), whether the migration should be executed.

The AbstractConditionalMigration class:

use Phinx\Migration\AbstractMigration;

abstract class AbstractConditionalMigration extends AbstractMigration
{
    public abstract function isTypeX(): bool;

    public abstract function isTypeY(): bool;

    protected function shouldExecute(): bool
    {
        $env = $this->getEnvironment();

        $shouldExecute = false;

        if ($this->isTypeX() && $this->isEnvTypeX($env)) {
            $shouldExecute = true;
        }

        if ($this->isTypeY() && $this->isEnvTypeY($env)) {
            $shouldExecute = true;
        }
        return $shouldExecute;
    }

   // ...
}

The thing is: for every migration class, I have to copy and paste that condition.
Also, it will generate a row for that migration in the database, even though it was not supposed to be executed.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with Phinx\Migration\AbstractMigration and the example migration's change() method, then trace how migration execution records rows in the database. Compare the current conditional approach with the desired behavior for database types X and Y, including whether a skipped migration should be recorded.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
database
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.