Updating tables: hook_update_N() functions

Last modified: May 13, 2009 - 18:20

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:

  1. Add newcol to the CREATE TABLE statements in mymodule_install().
  2. 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:

  1. Add newcol to the table definition array in mymodule_schema() in mymodule.install.
  2. 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:

  1. Add the new table to mymodule_schema() in mymodule.install.
  2. 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().

Why not use hook_schema() data?

DamienMcKenna - September 9, 2009 - 03:00

Why duplicate the schema creation in the mymodule_update_6101() function rather than just using the data from the existing schema function? Reduce duplication, reduce chances for errors.

<?php
function mymodule_update_6101() {
 
// Load the schema from hook_schema().
 
$schema = mymodule_schema();
 
$ret = array();
 
db_create_table($ret, 'mytable2', $schema['mytable2']);
  return
$ret;
}
?>

Because hook_schema might

phaul - September 17, 2009 - 18:56

Because hook_schema might change in the future with new versions of the module, with a given _N hook_update_N doesn't change ( should work on the old schema definitions so each outstanding update can be applied in turn)

 
 

Drupal is a registered trademark of Dries Buytaert.