How to create a table without uninstalling and reinstalling the module?
-
16-10-2019 - |
Question
I have a module and an installation file that is used to create a table.
According to my requirement, I need to add an another table in the same install file. I know that by using hook_schema()
we can create n number of tables.
But we need to uninstall and reinstall again to create the tables. If I use this, my existing data will be lost, so I am not supposed to do this.
Is there any way to create a table without uninstalling and reinstalling the module?
Solution
This link answered my question: Updating tables: hook_update_N() functions.
For example:
In Drupal 7:
<?php
/**
* Create new database table {mytable2}.
*/
function mymodule_update_7101() {
$schema['mytable2'] = array(
// table definition array goes here
);
db_create_table('mytable2', $schema['mytable2']);
}
?>
and in Drupal 6:
<?php
/**
* Create new database table {mytable2}.
*/
function mymodule_update_6101() {
$schema['mytable2'] = array(
// table definition array goes here
);
$ret = array();
db_create_table($ret, 'mytable2', $schema['mytable2']);
return $ret;
}
?>
OTHER TIPS
hook_install() is called only when the module is first installed; after that, hook_install()
will be called only if you first uninstall the module.
When you are updating a module, you need to implement hook_update_N(), which runs all times the module is updated. At the same time, the implementation of hook_schema() needs to be updated to include all the schema used from the module, for who installs the module for the first time.