Declarative schema in Magento modules: what it does and when you need it
When a custom module has to change database tables across releases, the question is how those changes get described and applied on every environment the same way. In Magento Open Source, declarative schema answers that question: you describe the target table layout in a db_schema.xml file inside the module, and the platform works out the changes needed to reach that layout from its current state. You do not write the ALTER TABLE statements yourself. The approach is documented in Adobe's developer documentation for modules, which sits alongside the module structure guidance in the Adobe Commerce PHP development overview, and the implementation lives in the core code of the magento/magento2 repository.
The difference from older install and upgrade scripts is where the logic lives. An install or upgrade script is imperative code that runs once per version step, so every change must be written as a sequence of steps and the order of those steps becomes your responsibility. Declarative schema records the end state instead, which keeps the module's intent visible in one file and reduces the chance of a missed step on a fresh install versus an upgraded site. Teams usually need it for new custom tables, for column additions or type changes on custom tables, and for any module that will be upgraded through several patch cycles. Before you adopt it, confirm with your developers whether the module already ships an InstallSchema or UpgradeSchema script, because converting those is a separate piece of work covered in the conversion section.
Declarative schema does not cover everything a module needs. XML describes structure, so it cannot express a data transformation, such as populating a new column from existing rows, reindexing a value, or seeding configuration. For that work Magento uses data patches and schema patches, which are PHP classes that the platform runs once and records as applied. Schema patches handle changes that the XML cannot express, while data patches handle the content side. Both sit beside db_schema.xml, and the order in which they run relative to declarative schema changes is a design decision that your developers must plan and test, not assume.
When you scope work with a partner or review an internal module, ask for three things. First, the list of tables and columns the module owns and where each is declared. Second, every data or schema patch, with a note on whether it is safe to run twice and whether it depends on another module's tables. Third, the test evidence from an upgrade run on a copy of production data, not only a clean install. Confirm the exact Magento Open Source release line your store runs, because supported versions and their requirements are set by Adobe's lifecycle and system requirement pages and change over time. Tying the schema work to that release line from the start prevents the common situation where a module works on a fresh install but fails when upgraded on a live store.
Which database change mechanism fits each job
This table compares declarative schema, data patches, schema patches and legacy upgrade scripts by what each changes, when it fits and its main trade-off. Read it by matching your job to a row, then check the trade-off before writing code. The main takeaway is that declarative schema should be the default for new tables, while data changes and older modules need a different mechanism.
| Mechanism | What it changes and when it fits | Main trade-off |
|---|---|---|
| Declarative schema (db_schema.xml) | Declares tables, columns, indexes and foreign keys; Magento computes the difference from the current database. Fits new tables and most column changes. | You cannot express arbitrary data transforms or ordering logic, so those need a patch alongside it. |
| Data patch | Runs PHP code once to insert, update or transform rows, such as seeding configuration or converting values. Fits data changes that must run exactly once. | Patches run once per database, so a bad patch needs a new patch to correct it, not a rerun. |
| Schema patch | Runs PHP code for structural changes that declarative schema cannot express, such as renaming data during a column move. Fits rare, complex structural work. | Custom PHP alters the database directly, so review and testing carry more of the risk. |
| Legacy InstallSchema and UpgradeSchema scripts | Procedural install and upgrade classes that alter tables in version steps. Fits modules that already run them and must keep their history. | Each version step must be maintained, and mixing these with declarative schema can cause ordering errors. |
| Converting an older module | Moves InstallSchema and UpgradeSchema logic into db_schema.xml plus patches, keeping the existing version history intact. Fits modules that must stay upgradable. | Conversion must be tested against a copy of a live database, because the diff against existing tables may differ from what the old script did. |
| Seed or reference data | Loads fixed lookup values, such as status codes or country-specific rows, through a data patch. Fits static data needed at install and upgrade. | Reference data that changes often belongs in admin or import tooling, not in patches, or each change needs a new patch. |
How a declarative schema file is structured
A declarative schema file describes the end state of a module's database objects, and Magento compares it with the live database during setup. The parts below are what a developer writes in the module's etc directory, and each one affects how safely the module installs, upgrades and removes data later.
Module declaration and location
The etc/module.xml file registers the module name and setup version, and the etc/db_schema.xml file sits beside it in the same etc directory. The module's PSR-4 namespace and directory layout determine where Magento finds these files, so a misplaced file is silently ignored. Check the file location and module name against the current developer documentation for your target 2.4.x line before building on them.
Declared module scope
The schema file is scoped to a database connection, and Magento Open Source uses a default connection that most modules should target. Declaring the wrong scope can place tables in a connection your module does not read from. Confirm the current scope names and their defaults in the developer documentation before you write the first table.
Tables and table options
Each table element names a table and carries options such as its engine and comment. Naming follows the Magento conventions your team agrees on, because other modules and reports will query these names directly. Confirm which table options are supported and how they are applied for your database engine and version.
Column definitions and types
Each column element declares a name, a type, nullability and identity or default behavior. Type names and their attributes are specific to Magento's schema parser, so a type that works in plain MySQL may not be accepted. Confirm the supported type list and attribute names against the current documentation and test the install on a clean database.
Constraints and primary keys
Primary keys, unique keys and foreign keys are declared as constraint elements that reference columns in the same table or in another module's table. A foreign key to a core table ties your module to that table's lifecycle, so note every cross-module reference. Confirm constraint types and reference syntax in the current documentation before relying on them.
Indexes for query paths
Index elements define how the module's queries reach its rows, and they are the first thing to review when a list page or report slows down. Each index should match a query your team has written down, not a guess. Confirm index attribute names and the handling of composite indexes against the developer documentation for your release.
Converting a module that still uses upgrade scripts
Converting an older module means replacing its procedural history with a declared target state, and the first step is an inventory of what the module has already done to live databases. Magento 2 modules written before declarative schema often contain an InstallSchema class that creates tables on first install and an UpgradeSchema class that runs a chain of versioned steps, each gated by the setup_version value recorded in the module's setup_module row. Before writing anything new, list every upgrade step in order, note which ones add, alter or drop tables and columns, and record which ones move data. Then confirm with your team which versions were actually shipped to customers, since those are the versions your upgrade tests must cover.
The risk is mixing the two systems in one module. Declarative schema compares the target state in etc/db_schema.xml with the live database and generates the difference, so an old UpgradeSchema step that already altered the same column can produce a second change, a duplicate index or a failed install on a database that is partly upgraded. Move the end state of the old steps into db_schema.xml, remove the schema-changing code from the upgrade classes, and keep any data transformation in data patches under Setup/Patch/Data. Check the official magento/magento2 repository for the patch base classes your Magento version expects, because the interfaces differ between releases.
Test the conversion against every version your customers ran, not only the current code. Restore a database snapshot from each shipped version, run bin/magento setup:upgrade, then compare the resulting schema with a fresh install. Treat each unexpected diff as a defect in the conversion. Effort depends mostly on the customizations that touched the module's tables and on the coding practices of the original authors, which matches what Adobe's upgrade guide names as the main drivers of upgrade work. Ask any partner to quote this inventory and version-matrix testing as separate line items, so you can see which part is the one-time conversion and which part recurs with each new release.
How to add or convert a module schema safely
This sequence takes a module from its current database state to declarative schema that installs cleanly on a fresh store and upgrades cleanly from the previous module version. Each step closes with a check so problems surface in staging rather than production.
Confirm the target release and PHP version
The developer confirms which Magento Open Source 2.4.x release and PHP version the module must support, using Adobe's system requirements for that release. Only the listed combinations are supported, so the target stack is written down before any schema is touched. Done means a short compatibility note exists that names the release, PHP version, MySQL or MariaDB version and the supported module versions. Check the note against the requirements page once more before moving on.
Inventory current tables, columns and patches
The developer lists every table the module creates or alters, every column it adds, and every existing install and upgrade script or data patch that touches the database. Scripts that only change data, or that run arbitrary SQL, are marked for later conversion. Done means an inventory exists that a reviewer can compare against the final db_schema.xml. The check is a diff of the live schema from a staging copy against the inventory, with no unexplained differences.
Write db_schema.xml and the whitelist
The developer declares each table, column, index, constraint and foreign key in the module's etc/db_schema.xml, using the schema notation from Adobe's developer documentation. The developer then generates db_schema_whitelist.json so the framework records which declared elements it already manages. Done means the file validates and the whitelist lists every declared table and column. The check is running the schema tooling in a staging copy and confirming it reports no pending changes for the declared elements.
Add patches for non-declarative work
Anything declarative schema cannot express, such as data migrations, backfills or configuration changes, moves into data patches or schema patches in the module's Setup/Patch directory. Each patch implements the framework's patch interfaces and declares its dependencies on other patches. Done means every legacy upgrade step that is not a structural change has a named patch class. The check is that each patch runs once on staging and that a second run is a no-op.
Verify the upgrade path on staging
The developer runs the setup upgrade command against a staging copy of the store, then runs the schema check command to confirm the database matches the declarations. Any remaining drift is resolved in the XML rather than by editing tables by hand. Done means the upgrade completes without errors and the schema check reports no differences. Record the output and the commands used so the result is repeatable in another environment.
Test fresh install and upgrade from the previous version
The team runs two test paths: a fresh installation with the new module enabled, and an upgrade from the previous module version with real or representative data. Both paths are checked for installed tables, populated columns, patch execution and the absence of orphaned objects left by the old scripts. Done means both paths pass with the same final schema. The check is a comparison of the two resulting databases, plus a smoke test of the features that depend on the changed tables.
Gate the change in CI
The schema files, whitelist and patches are reviewed in a merge request, and a pipeline job repeats the fresh install and upgrade tests on each change. The pipeline should fail when declarations and whitelist disagree or when a patch is not idempotent. Done means the job runs on every change to the module and blocks merges on failure. Confirm the job runs against the target release and PHP version recorded in the first step.
How setup:upgrade applies declarative and patch changes
The run starts when bin/magento setup:upgrade reads module code and each module's db_schema.xml, then compares the declared state with the whitelist and the live database. Schema changes come next, followed by data patches and schema patches in their declared order. The final check confirms the database matches what the code declares, so the reader should look at the whitelist and the patch status after each run.
Order in which setup:upgrade reads, applies and verifies database changes.
Security and operational risks in schema changes
Schema changes touch live data, so the risks below are operational as well as technical. Each one has a control you can put in place before the first production run, and most of them depend on a maintenance window and a verified backup taken before the change starts.
Destructive column drops
Removing a column in the db_schema.xml file deletes its data when the change runs in production. A declarative schema diff can show a drop that a developer did not intend, for example after a renamed field was treated as a removal. Before release, review the generated diff, confirm that no column carrying customer, order or payment data is dropped without a migration step that copies the values first, and keep the old column in place for at least one release cycle where the business allows it.
Table locks during upgrades
Adding an index or changing a column type on a large table can lock writes for long periods on MySQL or MariaDB, which stops checkout and admin saves while the change runs. Measure row counts for every table the module touches, test the same statements on a copy of production data sized close to the live store, and schedule the setup upgrade inside a maintenance window with a rollback plan that names who makes the call to stop.
Backups taken before schema work
A schema change that fails halfway can leave the database in a state that the code does not expect. Take a full database backup immediately before running bin/magento setup:upgrade, confirm that it restores to a separate host, and record the Magento code version and module list alongside it. A backup that has never been restored is not evidence that recovery will work.
Credentials in patch scripts
Data patches and schema patches are PHP classes that are committed to version control and shipped with the code. Database passwords, API keys or customer export paths pasted into a patch become readable by everyone with repository access and remain in Git history after removal. Read credentials from the environment or env.php at runtime, keep patches free of hard-coded hosts and secrets, and scan the repository for secrets as part of the review.
Whitelist drift between environments
The declarative schema whitelist in db_schema_whitelist.json records which columns Magento has already applied. When a developer edits a table on a staging server by hand, or a second branch adds a column with a different definition, the whitelist and the live schema disagree and later deployments fail or silently skip changes. Compare the schema on each environment with the committed files before each release, and do not make manual schema changes outside the module.
Patch releases and PCI DSS scope
Adobe's upgrade guide recommends upgrading every patch cycle to stay secure and PCI compliant. A schema change shipped together with a security patch changes two things at once, so test the combined release and record which patch level is running in production, since assessors will ask about it. Confirm the target version against Adobe's released versions page and your own compliance requirements before scheduling.
Upgrade guide overviewQuestions buyers ask before changing module database code
How much effort does converting upgrade scripts to declarative schema take?
Effort rises with the number of legacy scripts, how much custom code touches those tables, and how many other extensions read or write them. Adobe's upgrade guide names customizations, extension count, third-party integrations and coding practices as the main drivers of upgrade effort, and the same factors shape a conversion. Start by listing every install and upgrade class for schema and data, then list every table the module touches. Separate the tables your module owns from those owned by core or another vendor. Each table you own needs a db_schema.xml definition that matches the live database, and each script that changes data needs a data patch.
Can our own developers convert a module without outside help?
Yes, if they understand Magento's module lifecycle, can read the existing install and upgrade classes, and can test against a copy of production data. The work is mostly careful reading and verification, so a team with strong Magento experience and a staging environment can often do it internally. Outside help is more useful when the module has many legacy scripts, shares tables with core or other extensions, or runs in a store that cannot tolerate a failed schema change. Ask who will review the generated db_schema_whitelist.json, who approves the release, and whether the team has completed a schema conversion before. Adobe's Upgrade Compatibility Tool can flag compatibility issues in code, which helps an internal team scope the work.
What do we need to provide for a schema conversion?
The engagement depends on access, data and decisions from your side. Plan to provide:
- Access to the current module code, including every install and upgrade script and the version history.
- A staging copy of production data, refreshed close to cutover, running the same Magento and PHP versions as production.
- A named owner for each table the module writes, plus the people who approve schema changes.
- Written rules for existing data when a column changes type, is renamed or is removed.
Ask the provider to confirm which of these are their responsibility and which are yours before work starts, and ask how test data will be created if the staging copy cannot contain real customer records.
How long does a schema conversion take, and what sets the duration?
No duration applies to every module, so the answer depends on your code. Duration follows the number of legacy scripts, the number of tables, whether existing data must be transformed, and how many environments and stores depend on the module. Test data preparation often takes as long as the code change itself. Ask for a plan that separates inventory, conversion, testing and release, and confirm which milestones a quote covers. Timing also depends on your Magento release line. Adobe lists end of regular support for 2.4.9 on May 31, 2029, so a conversion completed on a supported line leaves more runway before the next upgrade is required.
Does a new module need declarative schema or can it use upgrade scripts?
A new module should define its tables and columns in etc/db_schema.xml, which describes the desired database state. The framework compares that file with the database during setup and applies the changes. Upgrade scripts remain useful for data work, such as backfilling a column or moving values between tables, and that work belongs in data patch classes. Keeping schema in XML and data changes in patch classes makes the module easier to review and lets the framework apply changes in a predictable order. Ask your engineers to confirm the file layout and patch interfaces against the Magento version you run, since details can change between releases.
How do we test a rollback for a schema change?
Treat rollback as a separate test, because redeploying older module code does not reverse a schema change that already ran. Before release, take a database backup immediately before the change. Restore it into a clean environment, run setup with the new module version, and check that the schema and data match expectations. Then run the previous module code against the restored database and confirm that the storefront, admin and cron jobs work. Where a change drops a column, export or copy the data first and test that the copy can be restored. Record the exact commands, how long a restore takes, and who approves the decision to roll back.
Does changing module tables affect our PCI DSS scope?
It can. If a module stores, processes or transmits cardholder data, or changes where that data lives, the change may alter the evidence your assessor reviews. Confirm with your Qualified Security Assessor whether a schema change touches systems in scope, and document the change in your change management record. Check whether the conversion moves data into new tables, changes column types that hold sensitive values, or adds logging of those values. Keep the database backup and restore steps in the same record, and confirm that access to the staging copy is controlled, because a copy of production data can contain the same sensitive fields as production.
Official Adobe and repository sources
Before you write a declarative schema file, read the source it lives beside. The magento/magento2 repository on GitHub is the upstream codebase for Magento Open Source, and the core modules under its app/code/Magento tree are the best working examples of a db_schema.xml file, its matching db_schema_whitelist.json, and the data and schema patch classes that sit in each module's Setup/Patch folder. Compare a core module that has changed over several releases with your own module, and check that your table names, column types and foreign keys follow the same conventions. The repository is also where you can trace how a given release handles schema generation, so keep a copy of the version you are targeting in front of you.
Adobe's developer documentation is the authoritative second read. The Adobe Commerce PHP development overview explains the component types Magento uses to extend the platform, including modules, themes and language packages, and describes the PSR-4 structure that modules follow. Use it to confirm where the etc directory, the registration.php file and the Setup classes belong, and to check which entry points your database change depends on before you commit to a layout. Where the overview and the repository disagree with the behavior you see on a test install, treat the difference as a question for Adobe support or your own engineers rather than a settled fact.
Confirm two things before you rely on these sources for a project. First, match the documentation version to the Magento Open Source release line your store runs, since the 2.4.x lines carry different system requirements and support windows. Second, record which sources your team used when it approved a schema change, so a later reviewer can see why a column was added or a patch was written. That record matters most when a schema change has to be reviewed by an outside developer or by your own security team.
How DeployOpen scopes and delivers module schema work
DeployOpen plans and builds Magento Open Source modules inside the client's own infrastructure, including the declarative schema, data patches and conversion of older upgrade scripts. Each engagement starts with a written scope, then moves through build, testing, handover and optional ongoing support.
How we scope
- Inventory every module that declares tables, columns or indexes, and record which ones still rely on InstallSchema or UpgradeSchema scripts.
- Agree in writing which tables, foreign keys and data migrations the engagement covers, and which existing data must be preserved.
- Confirm the Magento Open Source version, PHP version and database engine in the target environment before any schema work starts.
How we build
- Write db_schema.xml declarations, whitelist entries and data or schema patches under the module's PSR-4 structure, reviewed against the coding standards agreed in scope.
- Run schema and data changes on staging copies of production data, checking install and upgrade paths from the previous module version.
- Convert legacy upgrade scripts to declarative schema where the scope calls for it, and test that existing installations produce the same database state.
How we hand over
- Deliver the module source, patch classes, test results and a short runbook covering setup:upgrade, rollback limits and data backup steps.
- Document every table, column and index the module adds or changes, with the reason for each and any Magento-generated names the team must keep.
- Walk the client's developers through the upgrade procedure on their own environment so the next release does not depend on DeployOpen.
How we support
- Engagements are fixed-scope, so the cost of schema work is set by the written scope before development begins, and changes go through a written change request.
- Ongoing support, upgrades and continuous testing are available as a retainer, covering schema changes made in later Magento releases.
- Confirm with DeployOpen during scoping how support terms, response expectations and handover of test suites will be written into the agreement.

