Magento2
Magento 2.3 :: Duplicating Table Schemas
Posted on .Magento2 has a lot of gems hidden in it’s code-base which sometimes surprises me, why hasn’t this been documented yet !!
Not so recently I needed a way to scan an existing table schema and create a new table using the same table schema structure but with a different name of course.
In case you might be wondering why would you do something like that, well there can be some situation like
- Creating an archive table from any existing table
- Creating temporary tables to generate data and switch the table name afterwards
Finding the solution
Before trying to create my own logic for this implementation which would suck at some point, decided to dig into the Magento code to see if there is some inspiration (any code to copy-paste) I can find
Magento did not disappoint
Started my search at the very own class responsible for creating, modifying tables and doing DDL operations and you might already guessed it right:
\Magento\Framework\DB\Adapter\AdapterInterface
The interface is implemented by:
\Magento\Framework\DB\Adapter\Pdo\Mysql
and the method which does the magic is createTableByDdl
Implementing the functionality
So, here’s how it works, the method takes 2 arguments
$tableName
this would be an existing table name whose schema you would to copy.$newTableName
the name of the new table you would like to create based on the copied schema structure.
Now, the method does not create the new table (don’t let the method name fool you like it fooled me), but will return a table object, \Magento\Framework\DB\Ddl\Table
to be precise, which would then be needed to be passed to the \Magento\Framework\DB\Adapter\AdapterInterface::createTable
method as the argument, which in turn creates the table in your database.
Putting it all together
- Step - 1 : Create the table object for the new table using the existing table
/**
* @var $adapter \Magento\Framework\DB\Adapter\AdapterInterface
* @var $table \Magento\Framework\DB\Ddl\Table
*/
$table = $adapter->createTableByDdl(
$adapter->getTableName($sourceTable),
$adapter->getTableName($archiveTable)
);
- Step - 2 : Use the table object returned to actually create the table in your database.
/**
* @var $adapter \Magento\Framework\DB\Adapter\AdapterInterface
*/
$adapter->createTable($table)
Conclusion
Dig the core codebase of Magento, it will always surprise you.
Atish Goswami
I am a web developer by profession. I like web design development and anything in between