Updating tables: hook_update_N() functions
As in previous versions of Drupal, you can update database tables for new versions using a hook_update_N() function.
Adding a new column
Suppose that mymodule adds a new column called 'newcol' to mytable1 in version 6.x-1.5. Prior to Schema API, you would:
- Add newcol to the CREATE TABLE statements in mymodule_install().
- Create a mymodule_update_N() function to add newcol to existing mytable1 tables with ALTER TABLE statements.
Using Schema API, you perform the same two steps:
- Add newcol to the table definition array in mymodule_schema() in mymodule.install.
- Create a mymodule_update_N() function to add newcol to existing mytable1 tables with the Schema API function db_add_field():
<?php
function mymodule_update_6100() {
$ret = array();
db_add_field($ret, 'mytable1', 'newcol', array('type' => 'int', 'not null' => TRUE));
return $ret;
}
?>
Adding a new table
Similarly, suppose that for version 6.x-1.6 mymodule now needs a completely new table called mytable2. You perform the same two steps:
- Add the new table to mymodule_schema() in mymodule.install.
- Create a mymodule_update_N() function to create mytable 2 with the Schema API function db_create_table():
<?php
function mymodule_update_6101() {
$schema['mytable2'] = array(
// table definition array goes here
);
$ret = array();
db_create_table($ret, 'mytable2', $schema['mytable2']);
return $ret;
}
?>
Adding keys
And as for adding a unique, or a primary key, one can now use dedicated API functions:
<?php
function mymodule_update_6102() {
$ret = array();
db_add_unique_key($ret, 'mytable2', 'mykey', array('field1', 'field2'));
return $ret;
}
?>Important note: You may be tempted to pass a table definition from your own hook_schema function directly to db_create_table(). Please read why you cannot use hook_schema from within hook_update_N().
