Database Upgrade Scripts in Magento 2- Paul Meștereagă
Magento 2

Database Upgrade Scripts in Magento 2

In this post we'll learn how to create database upgrade scripts in Magento 2. These scripts are used to upgrade our custom database and insert data into it.

author

Paul Mestereaga

December 14, 2017

Let’s continue our series with a tutorial about database upgrade scripts in Magento 2. You can check my previous posts about Magento 2.

In this post we will learn how to create UpgradeSchema and UpgradeData scripts. These scripts are used to update our custom database that we need for our module and upgrade data into it.

UpgradeSchema script

We already have the Setup folder in the root directory of our module. Here we create the file UpgradeSchema.php where we define the UpgradeSchema class which implements UpgradeSchemaInterface.

An empty skeleton of the file would look like this:

<?php
namespace Mesteru\FirstModule\Setup;
 
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;
 
class UpgradeSchema implements UpgradeSchemaInterface
{
     /**
     * {@inheritdoc}
     */
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
 
        // code to manipulate the database goes here
 
        $setup->endSetup();
    }
}
?>

Between the calling of startSetup() and endSetup() methods we would put our code to manipulate the database. The code sample below will alter the table mesteru_sample_item to add one column. We add column description of type text.

What do we notice here is the version_compare() function. In our example, our current module is at version 0.0.1 and we want to upgrade to 0.0.2. So we read the condition as follows: “If the current version is lower than 0.0.2 then the script should run”. If the version of our module is 0.0.2 it means the script was probably executed and we don’t run it again. When we want to add another upgrate, we just add another if condition bellow with the new version.

<?php
if (version_compare($context->getVersion(), '0.0.2', '<')) {
    $setup->getConnection()->addColumn(
        $setup->getTable('mesteru_sample_item'),
        'description',
        [
            'type' => Table::TYPE_TEXT,
            'nullable' => true,
            'comment' => 'Item Description'
        ]
    );
}
?>

UpgradeData script

Now that we have the code to alter the table, if we need to add some data when we upgrade our module we use an update data script. In the Setup folder we create the file UpdateData.php in which we define the UpdateData class which implements UpdateDataInterface.

Content of the file looks like this:

<?php
namespace Mesteru\FirstModule\Setup;
 
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;
 
class UpgradeData implements UpgradeDataInterface
{
    /**
     * {@inheritdoc}
     */
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
       $setup->startSetup();
 
        if (version_compare($context->getVersion(), '0.0.2', '<')) {
            $setup->getConnection()>update(
                $setup->getTable('mesteru_sample_item'),
                [
                    'description' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dignissim maximus lacus, id aliquet tortor dignissim vitae. Mauris nec aliquam est.'
                ],
                $setup->getConnection()->quoteInto('id = ?', 1)
            );
        }
 
        $setup->endSetup();
    }
}
?>

As you can see the code between startSetup and endSetup updates the description column where we just inserted a dummy Lorem Ipsum text for the sake of the tutorial, that would be a default descriptio as it would update all the rows.

Run the scripts

We have now everything ready except that we have to change the module version to 0.0.2 in our etc/module.xml file. After doing that run the command:

php bin/magento setup:upgrade

This is just a simple example but give you the starting point. You can adapt it to your needs.

Get the code

You can get the complete code on my github profile here.

Magento 2 from Zero to Beginner Free Online Course

In 10 hours you will have all the basic knowledge so that you could develop your modules without wandering around how to implement stuff.

Related Posts

Magento checkout optimization

15 Dec 2022

|

Paul Mestereaga

Optimizing the checkout process on your Magento eCommerce website is essential for increasing conversions and improving customer satisfaction. A seamless checkout experience can make all the difference in the success of your online store.

3 Things That Kill Your Magento Store’s Conversion Rate

10 Dec 2021

|

Paul Mestereaga

The store receives a lot of traffic, and you market to the right audience. The brand is actively promoted on social media and succeeds in SEO, so the marketing efforts appear to be working.
But what if it doesn’t lead to many sales?

optimize-magento-preview

FREE!

Magento 2
Optimization guide

Wondered how you can make your Magento load faster? Wonder no more. Here is a step by step guide that helps you.