How to apply Schema Patch in Magento 2?

How to apply Schema Patch in Magento 2?

A schema patch includes custom schema modification instructions which means you can add, update, or delete a column from the custom table or EAV table. These modifications can be complex.
It is defined in a <Vendor>/<Module_Name>/Setup/Patch/Schema/<Patch_Name>.php file and implements \Magento\Framework\Setup\Patch\SchemaPatchInterface. So in our case, the path should be Magento\Mastering\Setup\Patch\Schema\SchemaPatch.php. The patches can only apply once. A list of applied patches always stores in the patch_list database table. And you can apply unapplied patches by running the setup:upgrade from the Magento CLI.

So if you do not want to create this file manually, I have a better solution for that lets check this out 😉

Go to your terminal and enter below command and Boom….

php bin/magento setup:db-declaration:generate-patch --type=schema Magento_Mastering SchemaPatch

The above command will create a schema patch file with default methods. E.g
getDependencies():  This function contains the class name of dependent patches. This functionality notifies Magento to execute the “patches”.
getAliases(): This function defines aliases for the patch class. In this case, the class name could possibly change, and if it does, we should supply the old class-name here, so that it doesn’t get executed a second time.
apply(): This function is used to define your core logic for installing/upgrading data to the database.
getVersion(): This function can return a version number of the patch. If the version number of the module is higher than the version we specify in our patch, then it will not get executed. If it is equal to or lower than the version here, it will be executed.

So what we are going to do now is we will add a new column to our existing table which I have created in this post.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magento\Mastering\Setup\Patch\Schema;

use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\SchemaPatchInterface;

/**
 * Patch is mechanism, that allows to do atomic upgrade data changes
 */
class SchemaPatch implements SchemaPatchInterface
{
    /**
     * @var ModuleDataSetupInterface $moduleDataSetup
     */
    private $moduleDataSetup;

    /**
     * @param ModuleDataSetupInterface $moduleDataSetup
     */
    public function __construct(ModuleDataSetupInterface $moduleDataSetup)
    {
        $this->moduleDataSetup = $moduleDataSetup;
    }

    /**
     * Do Upgrade
     *
     * @return void
     */
    public function apply()
    {
        $this->moduleDataSetup->startSetup();


        $this->moduleDataSetup->getConnection()->addColumn(
            $this->moduleDataSetup->getTable('declarative_table'),
            'price',
            [
                'type'     => Table::TYPE_TEXT,
                'length'   => 255,
                'nullable' => false,
                'comment'  => ‘Price’
            ]
        );


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

    /**
     * {@inheritdoc}
     */
    public function getAliases()
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public static function getDependencies()
    {
        return [];
    }
}

Run: php bin/magento setup:upgrade

Table View:

apply_schema_patch
Declarative table view

In conclusion, schema patches are much more beneficial than UpgradeSchema. The patch is run only once after each run and each class will operate separately. You can find the patch id and name in the patch_list table. This new way will replace the old way soon.

Refs:
https://devdocs.magento.com/guides/v2.4/extension-dev-guide/declarative-schema/data-patches.html

Leave a Reply

Your email address will not be published. Required fields are marked *