Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 42 ยท Data and the Database

Data Patches and Schema Patches

Learn how Magento data patches and schema patches run once per class, how dependencies and the patch_list table work, and how to write safe, revertable patches.

Declarative schema tells Magento what your tables look like, but a store needs more than empty tables. You may need default CMS blocks, a new customer group, a product attribute, a configuration value or a data fix for existing rows. Those changes are written as patches: small PHP classes that Magento runs once, during bin/magento setup:upgrade, and then remembers.

This lesson covers the two kinds of patch (data and schema), how dependencies decide the order, how Magento records what has already run, why a patch should still be written defensively, and what revert() is for. The real Magento classes are read-only. The runnable stand-in is a patch runner on SQLite with a patch_list table, dependency sorting and a revert, so you can watch the rules in action.

Why patches replaced version numbers

In old modules every change was a block inside UpgradeData::upgrade() guarded by a module version:

PHP
// legacy style, shown only so you can recognise it (read-only)
if (version_compare($context->getVersion(), '1.0.3', '<')) {
    // do something once
}

That ties changes to a version number in module.xml, makes ordering between modules hard and puts unrelated work in one growing method. Patches turn each change into its own class. Magento does not look at a version at all: it asks "has a patch with this class name run yet?" If not, it runs it and writes its name into the database.

flowchart TD
    U["bin/magento setup:upgrade"] --> S["Declarative schema diff"]
    S --> L["Collect all patch classes<br/>of all modules"]
    L --> O["Order by getDependencies()"]
    O --> Q{"In the patch_list table?"}
    Q -->|"yes"| K["Skip"]
    Q -->|"no"| A["Run apply()"]
    A --> W["Insert class name into patch_list"]

Patches run after the schema is in place, in dependency order, and each runs once.

A data patch

A data patch lives in Setup/Patch/Data/ of your module and implements DataPatchInterface. This one creates a customer group. It is read-only, shortened real code.

PHP
<?php
// Acme/Note/Setup/Patch/Data/AddVipNoteCategory.php (read-only)
declare(strict_types=1);

namespace Acme\Note\Setup\Patch\Data;

use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\Patch\PatchRevertableInterface;

class AddVipNoteCategory implements DataPatchInterface, PatchRevertableInterface
{
    public function __construct(
        private readonly ModuleDataSetupInterface $moduleDataSetup
    ) {
    }

    public function apply(): self
    {
        $this->moduleDataSetup->getConnection()->startSetup();

        $this->moduleDataSetup->getConnection()->insertOnDuplicate(
            $this->moduleDataSetup->getTable('acme_note_category'),
            [['category_id' => 1, 'label' => 'VIP']],
            ['label']
        );

        $this->moduleDataSetup->getConnection()->endSetup();

        return $this;
    }

    public function revert(): void
    {
        $this->moduleDataSetup->getConnection()->delete(
            $this->moduleDataSetup->getTable('acme_note_category'),
            ['category_id = ?' => 1]
        );
    }

    public static function getDependencies(): array
    {
        return [];
    }

    public function getAliases(): array
    {
        return [];
    }
}

The four methods you must provide are:

  • apply() does the work and returns the patch object ($this).
  • getDependencies() is a static method returning the class names of patches that must run first. They can belong to your module or to another one. If your patch needs the catalog_product entity type to exist, it should depend on the core patch that creates it, or your module must at least be sequenced after the module that owns it (see Module Sequence and Dependencies).
  • getAliases() returns older class names this patch replaces. If you rename or move a patch class, list the old name here, otherwise Magento sees a brand-new patch and runs it again.
  • revert() comes from the optional PatchRevertableInterface. It undoes the patch. It is used when the module is uninstalled with data removal, not on every upgrade, so many projects do not implement it. Implement it when removing your data cleanly matters.

Notice startSetup() and endSetup(), which switch off some connection checks (for example foreign key checks) while the patch runs.

A schema patch

A schema patch lives in Setup/Patch/Schema/ and implements SchemaPatchInterface. It has the same four methods but is meant for structural work that the XML cannot express, such as a one-off change to a table you do not own, or a step that must run between schema and data. Most structure belongs in db_schema.xml, so you will write far fewer schema patches than data patches.

PHP
// Acme/Note/Setup/Patch/Schema/CreateNoteSearchIndex.php (read-only skeleton)
class CreateNoteSearchIndex implements SchemaPatchInterface
{
    public function apply(): self { /* structural work */ return $this; }
    public static function getDependencies(): array { return []; }
    public function getAliases(): array { return []; }
}

Schema patches run before data patches. Think of the whole order as: declarative schema, then schema patches, then data patches.

The patch_list table

Magento keeps its memory in a table named patch_list. Its rows hold the class name of each patch that ran, with an auto-increment ID. Before running a patch, the patch applier checks the table. After a successful apply(), it inserts the class name. Three consequences follow:

  1. Once means once per database. A patch runs again on a fresh database (for example a new developer's install) but not on a database that already recorded it.
  2. The class name is the identity. Rename the class or change its namespace without adding an alias, and the patch runs a second time.
  3. A failed patch is not recorded. If apply() throws, the name is not inserted and the next setup:upgrade tries again. That makes writing patches idempotent important: part of the work may already have happened.

Writing idempotent patches

"It runs only once" is a promise from Magento, not a reason to be careless. A patch can fail halfway and run again, or run against a database where someone has already inserted the row by hand. Defensive habits:

  • Use insertOnDuplicate or check for the row before inserting.
  • Check whether an attribute, group or configuration value exists before creating it. For attributes see EAV: Entity-Attribute-Value.
  • Do not assume the table is empty.
  • Keep each patch small and focused so that a failure leaves a clear state.
  • Never change a patch that has already been released. Released patches have run in production, so editing them changes nothing there. Add a new patch for the new behaviour.

A patch runner you can run

The stand-in below is a miniature of PatchApplier. It keeps a patch_list table in SQLite, sorts patches by their dependencies, skips the ones already recorded, runs the rest and offers a revert. It reproduces the rules above; real Magento also locates patch classes in every module by scanning folders, and loads them through the object manager.

PHP Stand-in: a patch runner with dependencies and patch_list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

CreateCategories ran first although it was never registered directly: it was pulled in by the dependencies of the other two. The second run applies nothing, because every class name is already in patch_list.

Revert and the class-name pitfall

The second stand-in shows two behaviours that surprise people. First, revert() removes the work and its patch_list row, so the patch could run again. Second, an unchanged patch that is renamed looks new, and runs again unless you declare an alias.

PHP Stand-in: revert, rename and aliases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The rename without an alias inserted a second "Welcome" note: exactly the duplicate that an idempotent patch would have avoided. With the alias, the runner recognised the old name and skipped. This is why getAliases() exists, and why a defensive apply() is still worth writing.

Patches in a team

  • One patch, one purpose, named by what it does (AddVipNoteCategory, not Patch1).
  • Order is by dependency, not by file name, so declare dependencies explicitly. Do not rely on alphabetical order.
  • Do not edit released patches. Create a new one.
  • Patches run on every environment, including developers' machines and production. Avoid anything environment-specific, such as hard-coded IDs from your own database or URLs.
  • Keep heavy work out. A patch that processes millions of rows blocks the deployment. Prefer a queue consumer or an indexer for long jobs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does Magento know that a data patch has already run?

    Magento records each applied patch's class name in patch_list and skips any class found there. Version numbers are not used for patches.
  2. 2. You rename a patch class that has already been released. What should you do?

    The class name is the identity. Without an alias the renamed class looks like a new patch and runs again, which can duplicate data.
  3. 3. When is revert() normally used?

    revert() belongs to the optional PatchRevertableInterface and is used for removal on uninstall, not for ordinary upgrades.
  4. 4. Which statement about getDependencies() is correct?

    getDependencies() is a static method returning patch class names, possibly from other modules. Magento orders patches so dependencies run first.
  5. 5. A released patch has a bug. What is the right fix?

    Environments that already ran the old patch will never run the edited one. A new patch corrects both existing and fresh installations.

Summary

  • Patches are classes that run once during setup:upgrade: schema patches (Setup/Patch/Schema) first, then data patches (Setup/Patch/Data).
  • The class name is the patch's identity and is stored in the patch_list table.
  • getDependencies() (static) controls order, getAliases() protects renamed classes, revert() undoes the work on uninstall.
  • A failed patch is not recorded, so write apply() to be safe to run again.
  • Never edit a released patch; add a new one.
  • Structure belongs in db_schema.xml, data belongs in data patches.

Next: Models, Resource Models and Collections