Schema Patches & Data Patches in Magento 2
What are Patches in Magento 2?
Patches in Magento 2 are used to modify database schema or data during module installation or upgrade.
Magento introduced the patch system to replace the older Install/Upgrade scripts such as InstallSchema.php, UpgradeSchema.php, InstallData.php, and UpgradeData.php.
Patches provide a more modular and trackable way to apply database changes.
Types of Patches in Magento 2
Magento provides two main types of patches.
- Schema Patch → Used to modify database structure.
- Data Patch → Used to insert or update data in database tables.
What is a Schema Patch?
A Schema Patch is used to modify the database structure, such as creating tables, adding columns, or modifying indexes.
Schema patches implement the SchemaPatchInterface.
Example: Create a Schema Patch
Suppose we want to create a custom table in the database.
1. Create Schema Patch File
(File: app/code/VendorName/ModuleName/Setup/Patch/Schema/CreateCustomTable.php)
What is a Data Patch?
A Data Patch is used to insert or update data in the database.
Typical use cases include:
- Adding default configuration values
- Creating CMS pages or blocks
- Inserting default records
- Updating existing data
Data patches implement the DataPatchInterface.
Example: Create a Data Patch
Suppose we want to insert default data into the custom table.
1. Create Data Patch File
(File: app/code/VendorName/ModuleName/Setup/Patch/Data/AddSampleData.php)
How Magento Executes Patches
When the following command is executed:
Magento scans the Setup/Patch directory and executes patches that have not yet been applied.
Executed patches are recorded in the patch_list table in the database.
Difference Between Schema Patch and Data Patch
- Schema Patch modifies database structure.
- Data Patch inserts or updates database data.
- Schema Patch implements SchemaPatchInterface.
- Data Patch implements DataPatchInterface.
Best Practices
- Use Schema Patches only for database structure changes.
- Use Data Patches for inserting or updating data.
- Keep patches small and focused on a single change.
- Avoid modifying existing patches once deployed.