
Magento 2.3x – Configure declarative schema
Before Magento 2.3, every developer needs to write PHP scripts like InstallData / UpgradeData / Recurring, to interact with database, which is sometimes a bit annoying, and have nonsense to run every single script. ie: You might have a situation where you are standing on 1.4 version, a change is added on version 1.0 and removed on version 1.2.
This is not needed anymore, and you will have an schema made for all versions.
- To start working with that, we are going to proceed with the steps to create a new database table:
First of all, create db_schema.xml file inside app/Offset101/Helloworld/etc and write the following code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version="1.0"?> <!-- /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ --> <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="offset101_helloworld" resource="default" engine="innodb" comment="Offset101 Helloworld"> <column xsi:type="smallint" name="id" padding="6" unsigned="false" nullable="false" identity="true" comment="ID"/> <column xsi:type="varchar" name="author_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="Descrition"/> <constraint xsi:type="primary" referenceId="PRIMARY"> <column name="id"/> </constraint> </table> </schema> |
Before running the upgrade command you need to add your schema to db_whitelist_schema.json file by running the following command :
1 |
php bin/magento setup:db-declaration:generate-whitelist --module-name=Offset101_Helloworld |
Now, there is db_whitelist_schema.json file will be create in app/Offset101/Helloworld/etc folder.
You will now be able to run a
1 |
php bin/magento setup:upgrade |
and new database table should be created.
- To rename an existing column, you need to set below line in your db_schema.xml at the appropriate column :
1<column xsi:type="varchar" name="customer_email" onCreate="migrateDataFrom(email)" on_update="false" nullable="false" default="" comment="Customer Email"/>
where, name = “new column name” and onCreate=”migrateDataFrom()” = “old column name” - If you want to drop a table, then you can remove entire table node from xml file or you can set disabled attribute to true as like below line in your db_schema.xml like this:
123<table name="offset101_helloworld" resource="default" engine="innodb" comment="RH Helloworld" disabled="true">..</table>
Sources:
https://devdocs.magento.com/guides/v2.3/extension-dev-guide/declarative-schema/db-schema.html
https://magento.stackexchange.com/questions/251884/magento-2-3-how-to-implement-declarative-schema-in-custom-module