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

Database Install Scripts in Magento 2

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

author

Paul Mestereaga

November 23, 2017

Let’s continue our series with a tutorial about database install scripts in Magento 2. In the previous post we’ve seen how to create an empty module in Magento 2. In this post we will learn how to create InstallSchema and InstallData scripts. These scripts are used to create our custom database that we need for our module and insert data into it.

InstallSchema script

For the start let’s create a Setup folder in the root directory of our module. Here we create the file InstallSchema.php where we define the InstallSchema class which implements InstallSchemaInterface.

An empty skeleton of the file would look like this:

<?php
namespace Mesteru\FirstModule\Setup;
 
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;
 
class InstallSchema implements InstallSchemaInterface
{
    /**
     * {@inheritdoc}
     */
    public function install(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 create a table mesteru_sample_item with two columns. Column id of type integer as primary key and column name as type text.

<?php
$table = $setup->getConnection()->newTable(
$setup->getTable('mesteru_sample_item')
         )->addColumn(
            'id',
            Table::TYPE_INTEGER,
            null,
            ['identity' => true, 'nullable' => false, 'primary' => true],
            'Item ID'
        )->addColumn(
            'name',
            Table::TYPE_TEXT,
            255,
            ['nullable' => false],
            'Item Name'
        )->addIndex(
            $setup->getIdxName('mesteru_sample_item', ['name']),
            ['name']
        )->setComment(
            'Sample Items'
        );
 
$setup->getConnection()->createTable($table);
 
?>

InstallData script

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

Content of the file looks like this:

<?php
namespace Mastering\SampleModule\Setup;
 
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
 
class InstallData implements InstallDataInterface
{
    /**
     * {@inheritdoc}
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
       $setup->startSetup();
 
       $setup->getConnection()->insert(
            $setup->getTable('mastering_sample_item'),
            [
                'name' => 'Item 1'
            ]
        );
 
        $setup->getConnection()->insert(
            $setup->getTable('mastering_sample_item'),
            [
                'name' => 'Item 2'
            ]
        );
 
        $setup->endSetup();
    }
}
?>

As you can see the code between startSetup and endSetup inserts two rows into our table.

Run the scripts

We have now everything ready. The scripts will run the first time when you install the module. To install it run the command:

php bin/magento setup:upgrade

If you already have your module installed, the install schema and data scripts will not run so you have to delete the information from the database by running the query:

DELETE FROM setup_module WHERE module = 'Mesteru_FirstModule'

Now our module can create a table and insert data into it. 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.