phinx icon indicating copy to clipboard operation
phinx copied to clipboard

Add reversible change methods

Open boenrobot opened this issue 4 years ago • 0 comments

The change() method is a super convenient way to write reversible migrations, but its limited capabilities require going to up()/down() too often, even for seemingly small and easily reversible changes.

I think some of the more frequent use cases can be alleviated by introducing new methods that take an expected current state, and a desired after state. By virtue of being supplied both, the migration can check if the current state is the expected one, and do the expected post one if so. If the current state is not the expected one, the migration should error.

I don't really care about the naming of such methods, as long as it's not something already a keyword in a SQL flavor. I'll use "reversible" as an example.

e.g. changing a column

<?php

use Phinx\Migration\AbstractMigration;

class EnableUsersToUseEmail extends AbstractMigration
{
    public function change()
    {
        $old = [
            'username',
            'string',
            [
                'limit' => 45,
                'comment' => 'Username of user',
            ]
        ];
        $new = [
            'username',
            'string',
            [
                'limit' => 255,
                'comment' => 'Username or email of user',
            ]
        ];
        $this->table('users')->reversibleChangeColumns($old, $new)->update();
    }
}

It's the migration author's responsibility to ensure the two models are compatible when going in either direction. In the example f.e. it would be expected that when going down(), the DB would error if any username is longer than 45 characters. As far as Phinx is concerned, it should still set the limit to 45 if the current limit is 255.

Analogously, there could be "reverisbleForeignKey($old, $new)", "reversibleForeignKeyWithName($old,$new)", "reversibleChangeIndex($old,$new)".

boenrobot avatar May 17 '21 08:05 boenrobot