Magento, Magento 2

Magento 2.3 : Rename a Table using Declarative Schema

Magento 2.3 : Rename a Table using Declarative Schema

In this tutorial, we will learn about how to rename a database table using declarative schema in Magento 2.3. In Magento 2.3, Table renaming is now supported. You can create new table using db_schema.xml file. After, if you need to rename a database table then, you can rename it by db_schema.xml file.

Let’s start steps about how to rename a table using declarative schema :

You may also like this :

1) First of all, Create a db_schema.xml file at app/code/RH/Helloworld/etc/ folder and add this below code :


<?xml version="1.0"?> 
<!--
/**
 * Created By : Rohan Hapani
 */
-->
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="rh_helloworld_new_tbl" onCreate="migrateDataFromAnotherTable(rh_helloworld)" resource="default" engine="innodb" comment="RH 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>

In addition, you can see that there are onCreate attribute added in <table> tag. You can see that there are migrateDataFromAnotherTable() function, You need to pass old table name in as parameter value and need to set new table name in table tag name attribute.


onCreate="migrateDataFromAnotherTable(rh_helloworld)

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


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

Now, there is a db_whitelist_schema.json file that will be created in /RH/Helloworld/etc folder.

In last, after generate db_schema_whitelist.json file successfully. You need to execute setup upgrade command :

In conclusion, You can see the table name is replaced with new table name inside the database. Cheers 🙂

Note : Migrating data from another table and renaming columns at the same time is not supported.

I hope this blog will helpful for easily understand how to rename a table using declarative schema in Magento 2.3.x. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution 🙂

Tagged ,