Jojodae Ganesh Sivaji
May 23, 2013
Often times it is needed to create module-specific custom tables to store persistent data. Drupal offers a set of hooks in connection to this. Most commonly used among these are hook_schema() and hook_update_N(). The first hook, hook_schema() holds the structure of the table in the form of a PHP array. And since Drupal 7 drupal_install_schema()/drupal_uninstall_schema() are no longer needed to be called explicitly in hook_install()/hook_uninstall(). When the module is enabled for the first time, the structure of the table defined in hook_schema is parsed and the needed table(s) are created for the intended use.
However, the real-time use case at times requires adding the column to a table (or altering the table) after the module has been enabled. In such cases hook_update_N() comes into play.
Let's take the below code for instance,
function my_module_update_7001(&$sandbox) {
$spec = array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
);
db_add_field('my_table', 'my_column', $spec);
}
/**
* Implements hook_schema().
*/
function my_module_schema() {
$schema = array();
$schema['my_module_node_properties'] = array(
'fields' => array(
'nid' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
'vid' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
'my_column' => array(
'type' => 'int',
'size' => 'tiny',
'unsigned' => TRUE,
'not null' => TRUE,
),
'new_column1' => array(
'type' => 'int',
'size' => 'tiny',
),
'new_column2' => array(
'type' => 'int',
),
),
'primary key' => array('vid'),
'indexes' => array('table_id' => array('vid', 'nid')),
);
return $schema;
}
/**
* Add column1 and column2 fields to table {my_module_node_properties}
*/
function my_module_update_7004() {
$table = 'my_module_node_properties';
$schema = drupal_get_schema_unprocessed('my_module', $table);
foreach (array('new_column1', 'new_column2') as $field) {
db_add_field($table, $field, $schema['fields'][$field]);
}
}
Just like how your fellow techies do.
We'd love to talk about how we can work together
Take control of your AWS cloud costs that enables you to grow!