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 :


Before running the upgrade command you need to add your schema to db_whitelist_schema.json file by running the following command :


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


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 :

    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:

     

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