cakephp / cakephp/phinx

MySQL DropForeignKey only works if the referenced column in same database

Open
#2,069 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

It is possible to have a foreign key that points to a table in a different database (albeit not common?). In this case, the drop foreign key will fail, as the query looks for key usage in "DATABASE()". See snippet below from MysqlAdapter about line 898.

I think, but am not sure, that you could modify the WHERE condition to IS NOT NULL? For context, I have an employees database that is separate from an application database. The application database references employees in that employees DB. The workaround for me would be to create a view. So, I would not consider this a high priority issue, but one you may want to know about. The juice might not be worth the squeeze, so to speak.

foreach ($columns as $column) {
            $rows = $this->fetchAll(sprintf(
                "SELECT
                    CONSTRAINT_NAME
                  FROM information_schema.KEY_COLUMN_USAGE
                  WHERE REFERENCED_TABLE_SCHEMA = DATABASE()
                    AND REFERENCED_TABLE_NAME IS NOT NULL
                    AND TABLE_NAME = '%s'
                    AND COLUMN_NAME = '%s'
                  ORDER BY POSITION_IN_UNIQUE_CONSTRAINT",
                $tableName,
                $column
            ));

            foreach ($rows as $row) {
                $instructions->merge($this->getDropForeignKeyInstructions($tableName, $row['CONSTRAINT_NAME']));
            }
        }

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 in MysqlAdapter around line 898 and inspect the information_schema.KEY_COLUMN_USAGE query used when dropping foreign keys. Reproduce the case where the referenced table is in a different database, then verify the behavior against a same-database foreign key. Done means cross-database foreign keys can be discovered for dropping without breaking existing cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
mysql, php
Domain
databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.