Search code examples
mysqldebuggingforeign-keysphinx

Identify faulty foreign-key in MySQL "Integrity constraint violation" (1022) messages


Is there a way to get better debugging information for foreign key violations in MySQL?

I'm using Phinx for database migration and I'm dealing with multiple constraints in a row and exception messages like these:

Integrity constraint violation: 1022 Can't write; duplicate key in table '#sql-1b8c_4534' in […]

This problem is obscured by a lack of foreign-key name as well as a temporary table name. Is there a way to switch to a more verbose mode or something?

Expanding the stack trace would help also, because now it looks like this, with truncated queries:

Stack trace:
#0 /home/user/work/project/vendor/robmorgan/phinx/src/Phinx/Db/Adapter/PdoAdapter.php(167): PDO->exec('ALTER TABLE `us...')
#1 /home/user/w[…]

Solution

  • You can find out at least in which table the error occurred by running "show engine innodb status" in MySQL as root. It will show something like:

    ------------------------
    LATEST FOREIGN KEY ERROR
    ------------------------
    2018-02-13 11:12:26 0x70000b776000 Error in foreign key constraint of table table/#sql-7fa_247a:
     foreign key (`my_foreing_key`) references `table` (`id`)
       on delete cascade:
    Cannot resolve table name close to:
     (`id`)
       on delete cascade
    

    (the example is from here)