Press ESC to close

How to Create a New Table Using Declarative Schema (db_schema.xml) in Magento 2

We all know about PHP scripts like InstallSchema.php (the old way to create new tables) to create new tables but Magento has introduced Declarative schema to create or maintain the tables using declarative schema XML.

The advantage of this db_schema.xml is to avoid the unnecessary version checking for creating new columns or deleting columns for each table change. Let’s create one table.

Method to Create a New Table Using Declarative Schema (db_schema.xml) in Magento 2

?xml version="1.0" encoding="UTF-8"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
   <table name="codedecorator_learn" resource="default" engine="innodb" comment="Codedecorator Learn">
      <column xsi:type="int" name="id" padding="10" unsigned="false" nullable="false" identity="true" comment="ID" />
      <column xsi:type="varchar" name="name" nullable="false" length="25" comment="Name" />
      <column xsi:type="varchar" name="email" nullable="false" length="25" comment="Email" />
      <column xsi:type="varchar" name="description" nullable="false" length="255" comment="Description" />
      <column name="created_at" nullable="false" xsi:type="datetime" default="CURRENT_TIMESTAMP" on_update="false"/>
      <column name="updated_at" nullable="true" xsi:type="datetime" default="CURRENT_TIMESTAMP" on_update="true"/>
      <constraint xsi:type="primary" referenceId="PRIMARY">
         <column name="id" />
      </constraint>
   </table>
</schema>

After creating db_schema.xml, we need to run the following command to tell Magento that we have created a new table and also for backward compatibility with the PHP script.

It will not directly delete any column or table if you don’t have an entry in the whitelist because there might be an upgrade schema available for the same so it is important to generate a whitelist.

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

Note: When you disable any module with db schema and you run the setup upgrade command then it will delete the module table directly if you want to avoid that situation.

Please run the command using setup:upgrade –safe-mode=1 to create a database backup and then eventually setup:upgrade --data-restore=1 if you enable the module back and wish to restore from that backup.

Happy coding guys!

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

jhjbhjbhjbhjjjhbj

Share Post

Leave a Reply

Your email address will not be published. Required fields are marked *