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:

  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_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:

  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_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().

 
 

Drupal is a registered trademark of Dries Buytaert.