Declarative Schema
Declarative Schema in Magento 2.3

Declarative Schema in Magento 2.3

ced-pdf-title-image

Running short of time? Get PDF of the blog in your mail.

sharepost

Magento has introduced a new feature called Declarative Schema which aims to simplify the Magento installation and upgrade processes. This new concept will allow a developer to get away from writing updates for each new version in favour of declaring the final result that the developer wants to achieve.

To achieve the final result developers need to add, rename then change the type of the column in order to get the final result, which was not efficient and also time-consuming.
The new declarative schema approach allows developers to declare the final desired state of the database and has the system adjust to it automatically, without performing redundant operations. Developers are no longer forced to write scripts for each new version. In addition, this approach allows data to be deleted when a module is uninstalled.


How to use Declarative Schema in Magento 2.3

In this blog, we will only discuss file required for a Declarative Schema.

You can check our complete module here and you can also modify it according to your need.
Firstly create a file “db_schema.xml” inside folder “Ced/GraphQl/etc” and write the following code

 

 

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

     xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    
<table name="author_data" resource="default" engine="innodb" comment="Author Table">

     <column xsi:type="smallint" name="id" padding="6" unsigned="false" nullable="false" identity="true" comment="Author ID"/>

          <column xsi:type="varchar" name="author_name" nullable="false" length="255" comment="Author Name"/>

                <column xsi:type="varchar" name="author_email" nullable="false" length="255" comment="Author Email"/>

                      <column xsi:type="varchar" name="affliation" nullable="false" length="255" comment="Affliation"/>

                <column xsi:type="int" name="age" unsigned="true" nullable="true" identity="false" default="" comment="Age"/>

          <constraint xsi:type="primary" name="PRIMARY">

      <column name="id"/>

     </constraint>

</table>
</schema> 

 

Each table node represents a table in the database.

A table node can contain three types of subnodes:

  • Column
  • Constraint
  • Index

 

Column Subnode

The column subnode defines a column in a table. Each column requires its own declaration.

So when you run setup:upgrade command then it will create the table “author_data.”

 

Adding New Column

If you want to add a new column to the existing table then you need to add a new column node in db_schema.xml and on running upgrade command it will add the new column.

Remove Existing Column

Now if you want to remove the existing column then you either need to remove the column node (<column>) inside the table node or you can set disabled attribute to true.  

 

<column xsi:type="int" name="age" unsigned="true" nullable="true" identity="false" default="" comment="Age" disabled=”true” />

 

But before running the upgrade command you need to add your schema to db_whitelist_schema.json file by running the following command-

php bin/magento setup:db-declaration:generate-whitelist --module-name=Ced_GraphQl 

 

Ced_GraphQL is a module name. You need to specify your module name there. 

Now on running setup:upgrade command it will remove the column.

Changing the column type

You can change the column type, changing its type attribute to int, varchar, text etc.

 

Renaming a column

To rename a column you need to first remove the one you don’t want and add another column with your desired name. Now you need to migrate that column data into a newly created one, to do this you need to set an attribute on Create which will migrate data from the old column.
If we want to rename the author_email column to just email,  we will remove the author column and add a new one.

 

<column xsi:type="varchar" name="email" onCreate="migrateDataFrom(author_email)" on_update="false" nullable="false" default="" comment="Author Email"/>


So this will create new column ‘email’ with data from the removed column.

Drop a Table

To drop a table, either remove the entire table node from db_schema.xml or set disabled attribute to true.


Insert Default data to table at the time of installation.


Since in the old method, we used to write scripts in Install Schema or Upgrade schema when a table was created, but now in the new version, this will be done through Patch system.

A data patch is a class that contains data modification instructions. It is defined in a <Namespace>/<Module_Name>/Setup/Patch/Data/<Patch_Name>.php file and implements \Magento\Setup\Model\Patch\DataPatchInterface.

A schema patch contains custom schema modification instructions. These modifications can be complex.

It is defined in a<Vendor>/<Module_Name>/Setup/Patch/Schema/<Patch_Name>.php file and implements \Magento\Setup\Model\Patch\SchemaPatchInterface.


So to add data to the author table create AddData.php file inside folder Ced/GraphQl/Setup/Patch/Data and write the following code

 

<?php

namespace Ced\GraphQl\Setup\Patch\Data;

     use Magento\Framework\Setup\Patch\DataPatchInterface;

         use Magento\Framework\Setup\Patch\PatchVersionInterface;

     use Magento\Framework\Module\Setup\Migration;

use Magento\Framework\Setup\ModuleDataSetupInterface;

/**

 * Class AddData

 * @package Ced\GraphQl\Setup\Patch\Data

 */

class AddData implements DataPatchInterface, PatchVersionInterface

{

/**

* @var \Ced\GraphQl\Model\Author

*/

private $author;

/**

*

* @param \Ced\GraphQl\Model\Author $author

*/

public function __construct(

     \Ced\GraphQl\Model\Author $author

) {
     $this->author = $author;
}


/**

* {@inheritdoc}

* @SuppressWarnings(PHPMD.ExcessiveMethodLength)

*/

public function apply()

{

     $authorData = [];

       $authorData['author_name'] = "Andrew Tye";

         $authorData['author_email'] = "andrew@email.com";

            $authorData['affliation'] = "Andrew Company";

         $authorData['age'] = 32;

       $this->author->addData($authorData);

     $this->author->getResource()->save($this->author);
}


/**

* {@inheritdoc}

*/

public static function getDependencies()

{
     return [];
}


/**

* {@inheritdoc}

*/

public static function getVersion()

{
     return '2.0.0';
}

/**

* {@inheritdoc}
*/

public function getAliases()
{
     return [];
  }
}  


Now on running the upgrade command, it will add data to author_table. Patch is only one-time run and you will find a list of patch in patch_list table. You can use our module to make changes in the declarative schema.

 That’s it for the Declarative Schema from our end. Since official Magento 2.3 version is yet to be released, so whatever we have described to you here is based on Magento 2.3 beta version.

 We have made changes to our GraphQL Module mentioned in our previous blog itself. You can check and implement the changes which we have described here.

 

About The Author

3
Leave a Reply