Declarative Schema is a feature introduced in Magento 2.3 that provides a new way to define database schema changes using XML files. Traditionally, database schema changes in Magento were defined using InstallSchema and UpgradeSchema PHP scripts. However, with Declarative Schema, you can define the database schema changes in XML format, making it more readable and easier to manage.

In Declarative Schema, you describe the structure of your database tables, columns, indexes, and foreign keys in XML files located in the module's etc/db_schema.xml directory. These XML files provide a clear and concise representation of the database schema changes, making it easier to understand and maintain.

Declarative Schema also provides benefits such as improved performance during setup and upgrades, better compatibility with version control systems, and easier collaboration among developers working on database-related tasks.

Overall, Declarative Schema simplifies the process of managing database schema changes in Magento 2, making it more efficient and developer-friendly.

 

Here's a basic template for a Declarative Schema XML file in Magento 2:

 <?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="your_table_name_here" resource="default" engine="innodb" comment="Your Table Comment">
        <column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" comment="Entity ID" identity="true"/>
        <column xsi:type="varchar" name="name" nullable="false" length="255" comment="Name"/>
        <column xsi:type="text" name="description" nullable="true" comment="Description"/>
        <constraint xsi:type="primary" referenceId="PRIMARY">
            <column name="entity_id"/>
        </constraint>
    </table>
</schema>

This template defines a basic schema for a table named your_table_name_here. You should replace your_table_name_here with the actual name of your table. You can then define columns within the <table> element and specify their types, names, and other attributes. Additionally, you can define constraints like primary keys using the <constraint> element.

Make sure to adjust the schema according to your specific requirements, including adding or removing columns and constraints as needed.

 
 
 

The db_schema_whitelist. json file is a way of telling Magento which tables and columns it can safely alter using the db_schema. xml file.

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