How to create a new table using Declarative Schema( db_schema.xml) in Magento2

We all know about PHP script like InstallSchema.php (old way to create new table) to create new table but magento has introduced Declarative schema to create or maintain the tables using declarative schema xml.

Advantage of this db_schema.xml is to avoid the unnecessary version checking for create new columns or delete column for each table change. Let’s create one table

<?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 following command to tell magento that we have created new table and also for backward compatibility with php script.

It will not directly delete any column or table if you dont have entry in whitelist because there might be upgrade schema available for the same so that it is important to generate 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 setup upgrade command then it will delete the module table directly if you want to avoid that situation.

Please ran command using setup:upgrade --safe-mode=1 in order 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!

Leave a Reply

Your email address will not be published.