Declarative schema is the new feature in Magento to do database operations of creating and updating database tables. This is one of the major changes introduced by the Magento team in 2.3 and it replaces the old approach of creating InstallSchema & UpgradeSchema scripts.
Why Declarative Schema?
Before declarative schema, developers need to write different schema scripts in each version of a module. And when a customer upgrades Magento to a version several releases ahead of the installed version, the upgrade scripts between those two versions will still be executed. This increases the complexity to track changes with every upgrade script. And new declarative schema approach allows developers to declare the final desired state of the database and has the system adjust to it automatically.
What is the use of db_schema.xml?
Before Magento 2.3, whatever database operations developers were writing in InstallSchema & UpgradeSchema scripts are replaced by the db_schema.xml file. So now, the below operations will be done using db_schema:
- Create or drop tables in the database.
- Alter table columns.
- Add new constraints or indexes to the tables.
Let’s see an example of how to create a custom table in a module. Create a new db_schema.xml file inside the VendorName/ModuleName/etc/ folder of a custom module.
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
<table name="declarative_table">
<column xsi:type="int" name="id_column" padding="10" unsigned="true" nullable="false" comment="Entity Id"/>
<column xsi:type="int" name="severity" padding="10" unsigned="true" nullable="false" comment="Severity code"/>
<column xsi:type="varchar" name="title" nullable="false" length="255" comment="Title"/>
<column xsi:type="timestamp" name="time_occurred" padding="10" comment="Time of event"/>
<constraint xsi:type="primary" referenceId="PRIMARY">
<column name="id_column"/>
</constraint>
</table>
</schema>
To apply changes in the Magento, you need to run the upgrade command as below:
php bin/magento setup:upgrade
For all other database operations please follow the link.
What is the db_schema_whitelist.json file? What is it used?
All operations performed in the system should be backward compatible. Because of this declarative schema doesn’t drop tables or columns or keys which are not available in db_schema.xml.
Comments
Post a Comment