Skip to content

Auto-generate foreign key constraint names when not provided#1041

Open
dereuromark wants to merge 4 commits into5.xfrom
fix-auto-generate-fk-constraint-name
Open

Auto-generate foreign key constraint names when not provided#1041
dereuromark wants to merge 4 commits into5.xfrom
fix-auto-generate-fk-constraint-name

Conversation

@dereuromark
Copy link
Member

Summary

  • Auto-generate foreign key constraint names when not provided in addForeignKey()
  • MySQL and SQLite adapters now use the pattern {table}_{columns} (matching PostgresAdapter and SqlserverAdapter behavior)

This fixes an issue where unnamed constraints could cause problems with CakePHP's ConnectionHelper::dropTables() which expects string constraint names. When no name was provided, MySQL would auto-generate one, but the schema reflection could store it with integer array keys, causing TypeError in TableSchema::getConstraint().

Fixes #1040

@dereuromark dereuromark added the bug label Mar 8, 2026
@dereuromark dereuromark force-pushed the fix-auto-generate-fk-constraint-name branch 2 times, most recently from c582b85 to 809abc9 Compare March 8, 2026 20:35
When a foreign key is added without an explicit name, the MysqlAdapter
and SqliteAdapter now generate a name following the pattern
'tablename_columnname' (e.g., 'articles_user_id' for a FK on the
user_id column in the articles table).

This matches the behavior of PostgresAdapter and SqlserverAdapter,
which already auto-generate FK names. This ensures constraint names
are always strings and prevents issues with constraint lookup methods
that expect string names.
Update the expected FK names in comparison files and schema dumps
to match the new auto-generated naming pattern (tablename_columnname).
@dereuromark dereuromark force-pushed the fix-auto-generate-fk-constraint-name branch from ed2b2d3 to 629c85e Compare March 8, 2026 21:02
The FK constraint name change from auto-generated (ibfk_N) to
explicit (table_column) also affects the implicit index MySQL
creates for FKs. Update comparison files to reflect the index
rename from user_id to articles_user_id.
With the FK naming changes, both the lock file and database have
the index named articles_user_id, so no diff is needed for this
index. Remove the index rename operations that were incorrectly
added.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

addForeignkey() without a constraint/name creates a constraint, which has a integer name

1 participant