In Magento 2, You can create a new table using db_schema.xml file. After creating a table you want to rename a table name, You can rename a table using declarative schema.
New Table(mycustom_table) db_schema.xml file,
<?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="mycustom_table" onCreate="migrateDataFromAnotherTable(new_declarative_table)">
<column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" identity="true"
comment="Entity Id"/>
<column xsi:type="varchar" name="fullname" nullable="true" length="50" comment="Full name"/>
<column xsi:type="varchar" name="email" nullable="true" length="255" comment="Email"/>
<column xsi:type="smallint" name="store_id" padding="5" unsigned="true" nullable="true" identity="false"
default="0" comment="Store Id"/>
</table>
</schema>
Now you must have to run generate-whitelist command to generate db_schema_whitelist.json file,
php bin/magento setup:db-declaration:generate-whitelist –module-name=Vendorname_Packagename
Where Vendorname_Packagename is your Vendor and Packagename.
Now you can change the table name using below tag in the XML file,
<table name=”rename_tablename” onCreate=”migrateDataFromAnotherTable(mycustom_table)”>
where rename_tablename is your new table name and mycustom_table is your old table name in the above tag.
The new db_schema.xml file will be,
<?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="rename_tablename" onCreate="migrateDataFromAnotherTable(mycustom_table)">
<column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" identity="true"
comment="Entity Id"/>
<column xsi:type="varchar" name="fullname" nullable="true" length="50" comment="Full name"/>
<column xsi:type="varchar" name="email" nullable="true" length="255" comment="Email"/>
<column xsi:type="smallint" name="store_id" padding="5" unsigned="true" nullable="true" identity="false"
default="0" comment="Store Id"/>
</table>
</schema>
Run command,
php bin/magento setup:upgrade
You can check your table name is replaced with a new name.
