cakephp / migrations

CakePHP database migrations plugin
Other
137 stars 116 forks source link

Improving foreign key API #770

Open markstory opened 1 week ago

markstory commented 1 week ago

Building foreign keys through the addForeignKey method requires remembering 4 positional arguments, and the ordering. While it is decent to use when writing migrations it is more reads with more difficulty.

        $this->table('constraint_users')
            ->addForeignKey(
                'role_id',
                'constraint_roles',
                'id',
                [
                    'update' => 'NO_ACTION',
                    'delete' => 'NO_ACTION',
                    'constraint' => 'role_id_0_fk'
                ]
            )
            ->update();

Is the current API. We've used up a really good method name with addForeignKey and the alternative names I could come up with clunky. What we could do with relative ease though is widen the type on the first parameter of addForeignKey to include a new builder object:

        $this->table('constraint_users')
            ->addForeignKey(
                $this->foreignKey('role_id')
                    ->references('constraint_roles', 'id')
                    // Could also be an enum
                    ->updateAction('NO_ACTION')
                    ->deleteAction('NO_ACTION')
                    ->name('role_id_0_fk')
            )
            ->update();

While this is more verbose, it is more clear about what is going on, and the API can be well-typed.

dereuromark commented 1 week ago

How do we handle (unique) indexes? Similar?

markstory commented 1 week ago

How do we handle (unique) indexes? Similar?

Yeah I could see a fluent builder object for indexes as well. I'd love to add support for conditional indexes in the future and having a builder would help with that.

dereuromark commented 1 week ago

Also refs https://github.com/cakephp/phinx/pull/2322