Working with Setup Migration Scripts in Magento 2

Aug 16, 2018405Gennadiy Haritonov
Working with Setup Migration Scripts in Magento 2

Magento 2 uses schema/data migrations to provide data persistence and database updates. These migrations contain instructions for:

  • creating the required tables and filling them during the initial installation;
  • transforming the database scheme and information in it for each of the possible versions of the application.

Magento 2 setup scripts are located in the app/code/Vendor/Module/Setup folder.

InstallSchema and InstallData classes are responsible for the first module installation and UpgradeSchema and UpgradeData scripts will be used when upgrading the module’s version.

InstallSchema class

InstallSchema class is used for creating the necessary table module during the primary installation.

InstallData class

InstallData class is used for inserting the data during the initial installation.

UpgradeSchema class

UpgradeSchema class is used for modifying the database schema when updating the module.

UpgradeData class

UpgradeData class is used for modifying the data when updating the module.

Running setup scripts

You can run migration scripts with the following CLI command: $ php bin/magento setup:upgrade

If Magento sees any new module, it will instantiate objects from the Vendor\Module\Setup\InstallSchema and Vendor\Module\Setup\InstallData classes.

If the module’s version has changed, then Vendor\Module\Setup\UpgradeSchema and Vendor\Module\Setup\UpgradeData will be instantiated. After that, the corresponding upgrade methods will be launched.

Versioning

Unlike Magento 1, Magento 2 does not contain built-in tools for migrations versioning and each developer must check the current/required version of the module themselves.

Recurring scripts

Recurring scripts are launched each time you run the setup:upgrade command and don’t depend on the version of the module.

app/code/Vendor/Module/Setup/Recurring.php

Thank you for reading, hope this information was useful. Please leave your comments and questions on the article in the comment section below.



2 Comments

  1. What is the use of Recurring script.. why we need to run migration classes each and every time when Setup:Upgrade…
    Seems unnecessary..?? Is there any reason behind it..?

  2. Hi, Kumar

    Take a look here as an example: Magento\Indexer\Setup\Recurring
    Each time the setup:upgrade is performed, the Magento_Indexer module checks if new indexers have been added and if yes, it adds them to the indexer_state table.

Post a new comment

top
BelVG Newsletter
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
Email *