How to drop a column from the table using the db.schema.xml file in Magento 2 – We all know from Magento 2.3 that Declarative Schema (db.schema.xml) was introduced to create the database tables in Magento 2. After creating a table and developing the custom extension you may feel free to drop/remove unwantedly created columns. To drop a column you can do it using the same db.schema.xml file.
I have noticed a question related to this topic in AD0-E717 Adobe Commerce
Developer with Cloud Add-on Professional exam.
Question – What should be done to allow the removal of columns from the database when deleting them from db.schema.xml?
- A. The removable columns should be defined in db_schema_whitelist.json.
- B. The columns should have “removable” attribute set to “true” in the db.schema.xml.
- C. The removable columns should be defined in db.schema_blacklist.json.
So to check the answer practically I tried, What I found was to remove a column using db.schema.xml, and add disabled=true to the relevant column. After that need to update the db_schema_whitelist.json file.
For example, let’s say you have added a column like this
1 |
<column name="answer" nullable="true" xsi:type="text" comment="answer"/> |
You need to update this column line below
1 |
<column name="answer" nullable="true" xsi:type="text" comment="answer" disable="true"/> |
After this need to update the db_schema_whitelist.json as follows and generate the db_schema_whitelist.json file.
1 2 3 4 5 6 7 8 9 10 |
{ "ayakil_faq_faq": { "column": { "answer": true, }, "constraint": { "PRIMARY": true } } } |
To generate the db_schema_whitelist.json file. you need to run the below command.
1 |
bin/magento setup:db-declaration:generate-whitelist --module-name=YourModule_Name |
After updating the codes you need to run setup:upgrade command. After clear:cache command you can see the field is removed from the table.
So for the above question, I choose Answer A.