Install or Upgrade a Database Schema

In this blog post we will see how you can easily install or upgrade a database schema in Magento 2. Magento 2 provides you some classes with which you can easily do that. Let's check it in details!

Let's start by creating a basic module under the namespace MageVision. So first step will be to create the following folders:

  • app/code/MageVision
  • app/code/MageVision/Blog12

Then we need to create our module.xml and the registration.php file to register our module. These two file have to look like the below ones.

module.xml

registration.php

As you know already to activate our module in Magento 2 we need to run the two following commands.

  • php bin/magento module:enable MageVision_Blog12
  • php bin/magento setup:upgrade

The php bin/magento setup:upgrade command is the one we need to upgrade our system. If our module had setup scripts, they will be executed and the current module version will be saved in the setup_module table.

So before we run this command let's go an add a setup script to create a new custom database table.

Magento 2 provides us different Setup classes for different actions. The following two classes are the ones responsible for installing or upgrading a database schema in Magento 2.

  • Setup/InstallSchema
  • Setup/UpgradeSchema

Navigate to app/code/Vendor/Module/Setup folder to have a better overview of all Setup classes Magento 2 provides to us.

So let's create an InstallSchema class under app/code/MageVision/Blog12/Setup to create a new custom database table.

Now execute the php bin/magento setup:upgrade command to run the setup script. The InstallSchema class runs only once by module installation. Also if you check now the setup_module table, you will see that the current module's version (2.0.0) is saved.

To upgrade now that table or another one, you have to create an UpgradeSchema class under app/code/MageVision/Blog12/Setup and also increase the setup_version to 2.0.1 in our module.xml. In our example we just upgrade the database table we just created by adding a new column.

Now execute again the php bin/magento setup:upgrade command to run the upgrade setup script. The UpgradeSchema class runs by module installation or upgrade.

Finally, since there are no separate version setup files anymore like in Magento 1, in the UpgradeSchema class you have to handle all your setup versions. 

The full example as extension can be found here.

Feel free to share this post and ask your questions in the comments below.

Till next time!