Updating tables #1: hook_update_N() functions
Updating your database tables for new versions works just as it has since Drupal 4.7, using a hook_update_N() function. Suppose that mymodule adds a new column called 'newcol' to mytable1. 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_1() {
$ret = array();
db_add_field($ret, 'mytable1', 'newcol', array('type' => 'int', 'not null' => TRUE));
return $ret;
?>
Similarly, suppose that 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_2() {
$schema['mytable2'] = array(
// table definition array goes here
);
$ret = array();
db_create_table($ret, 'mytable2', $schema['mytable2']);
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().
