Using Magento Declarative Schema to Manage Database Changes Safely
Learn how Magento’s declarative schema lets you define database changes in XML, letting setup:upgrade generate the needed ALTER scripts automatically.
03 Jul 2025, 10:04 UTC

Problem: Manual upgrade scripts are error‑prone and hard to track
Traditional InstallSchema and UpgradeSchema classes require writing PHP code for every column change, index, or foreign key. Mistakes in the scripts can break deployments, and tracking the exact state of the database across environments becomes tedious.
Thesis: Declarative schema lets you declare the desired database state in XML and let Magento generate the needed ALTER statements.
How Declarative Schema Works
Magento compares the XML declarations in etc/db_schema.xml of all active modules with the current database schema. Differences are translated into the appropriate ALTER TABLE statements and executed during bin/magento setup:upgrade. If nothing differs, the command reports “Nothing to upgrade” and finishes quickly.
Defining a New Table with db_schema.xml
<?xml version='1.0'?>
Place this file in app/code/Vendor/Module/etc/db_schema.xml.
Running setup:upgrade and Verifying the Change
- Log in to the server as a user that can execute the Magento CLI (typically the web‑server user).
- Run
bin/magento setup:upgrade. - Watch the output; Magento will compare the declared schema with the current database and emit ALTER statements for any differences.
- After the command finishes, open a MySQL client and verify:
SHOW TABLES LIKE 'mymodule_product_rating';
DESCRIBE mymodule_product_rating;
You should see the table with the columns defined above.
Check that the module’s version is recorded:
SELECT module_name, schema_version FROM setup_module WHERE module_name = 'Vendor_Module';
The schema_version should match the version declared in composer.json for the module.
Trade‑off: Compatibility and Mixing Approaches
- If you declare a column that already exists with a different type or size,
setup:upgradewill abort with an error such as 'Column specification mismatch'. You must either adjust the declaration to match the existing column or create a data patch to migrate the data. - Magento discourages mixing declarative schema with the old InstallSchema/UpgradeSchema classes in the same module. Doing so can lead to unpredictable states because the two systems may try to apply conflicting changes.
Actionable Closing
Start by moving simple, static tables (like lookup tables or custom entity tables) to declarative schema. Keep data changes in data patches, and run bin/magento setup:upgrade in a staging environment first to confirm no errors appear. Once the declarative files are in place and the upgrade runs cleanly, you’ll have a version‑controlled, repeatable way to evolve your Magento database without hand‑crafted upgrade scripts.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.