-
Notifications
You must be signed in to change notification settings - Fork 351
Description
Duplicate FOREIGN KEY constraint error on setup:upgrade due to nullable columns in Optimizer db_schema.xml
When running bin/magento setup:upgrade, Magento repeatedly tries to re-apply foreign key constraints defined in the module Smile_ElasticsuiteOptimizer.
This leads to a fatal SQL error:
SQLSTATE[HY000]: General error: 1826 Duplicate FOREIGN KEY constraint name 'magento/FK_DECB3B36711079998CA4D3DB38F2E0EB'
The issue occurs even on a clean Magento installation, with no previous ElasticSuite data or schema.
Preconditions
Install the module and run the setup:upgrade at least twice. The first run is successful, but from the second run onwards it returns an error.
Magento Version: Both Magento Opensource and Adobe Commerce and Mage-OS tested error in versions
- 2.4.6-p12
- 2.4.8
- 2.4.8-p1
- 2.4.8-p2
ElasticSuite Version: 2.11.15 and 2.11.15.1
Environment: Both production mode and developer mode
Third party modules: none, clean Magento installation
Steps to reproduce
- Start from a clean Magento installation (no existing database).
- Install ElasticSuite following the official documentation.
- Run:
bin/magento setup:upgrade→ the setup completes successfully. - Run the same command again:
bin/magento setup:upgrade→ the command fails with:
SQLSTATE[HY000]: General error: 1826 Duplicate FOREIGN KEY constraint name 'magento/FK_DECB3B36711079998CA4D3DB38F2E0EB'
Expected result
setup:upgrade should complete successfully on subsequent executions with no schema differences detected.
Actual result
setup:upgrade always tries to re-apply the same foreign key constraints, causing a MySQL duplicate FK error.
Proposed fix:
This error occurs because Magento first creates columns as "nullable = true" and then sets the foreign key, causing MySQL to change the column to "nullable = false". From the second setup upgrade, Magento sees a discrepancy between the db_schema and what is set in the database and tries to reapply the constraint, generating the duplicate key error.
Change both columns to "nullable = false" in db_schema.xml:
<column name="category_id" xsi:type="int" unsigned="true" nullable="false" comment="Category ID"/>
<column name="query_id" xsi:type="int" unsigned="true" nullable="false" comment="Query ID"/>
This makes the declarative schema idempotent and eliminates the recurring foreign key re-creation.
Additional notes:
After applying this change, repeated executions of bin/magento setup:upgrade succeed without error on all tested Magento versions.