phinx icon indicating copy to clipboard operation
phinx copied to clipboard

Adding foreign key fails.

Open dereuromark opened this issue 6 years ago • 1 comments

This looks familiar to https://github.com/cakephp/phinx/issues/1805

        $this->table('districts')
            ->addForeignKey('city_id', 'cities', ['id'], ['delete' => 'SET_NULL'])
            ->update();

The table schema is nullable for that field as per docs

        $this->table('districts')
            ->addColumn('city_id', 'integer', [
                'default' => null,
                'limit' => 10,
                'null' => true,
                'signed' => false,
            ])

and exists already for quite some time in the DB as such. All fields are still null of value. So no "invalid cities.id" could be the cause either.

But running the migration above to add the foreign key fails with:

PDOException: SQLSTATE[HY000]: General error: 1005 Can't create table de_local.#sql-3153_65e4 (errno: 150 "Foreign key constraint is incorrectly formed"

MySQL: 10.0.38-MariaDB-0ubuntu0.16.04.1 - Ubuntu 16.04

dereuromark avatar Oct 31 '20 16:10 dereuromark

object(Phinx\Db\Util\AlterInstructions) id:0 { protected alterParts => [ (int) 0 => 'ADD FOREIGN KEY (city_id) REFERENCES cities (id) ON DELETE SET NULL' ] protected postSteps => [] }

Looking at how MariaDB expects this to be, this looked valid I now just stumbled upon https://dba.stackexchange.com/questions/203509/mysql-foreign-key-constraint-is-incorrectly-formed

Both the referencing and referenced columns must be of the same type (and same in this case includes the unsigned attribute).

So I had to also fix up cities.id to be unsigned int. This solves it. One more reason to have default generation fo migrations output proper defaults.

I wonder if we could have a better phinx handling of this, rather then this very hard to spot SQL error.

dereuromark avatar Oct 31 '20 17:10 dereuromark