Create and update database fields by using hook_update_N

How do you add additional fields to a database table?

Db_add_field() can be used in hook_update_N() to add fields to a database table. Always remember to add the field to hook_schema() to allow entities to properly read the table. Also, this is needed to properly install the module in other projects or to reinstall the module in the current project, mostly in the development fase.

How to alter fields in a DB table?

Use db_change_field() to alter existing fields in the database table. Again, remember to add the changes to the hook_schema().



/**
 * Implements hook_schema().
 */
function MYMODULE_schema() {
  $schema = array();

  $schema['MYTABLE'] = array(
    'description' => 'The base table for MYMODULE.',
      'fields' => array(
        'id' => array(
          'description' => 'Primary key.',
          'type' => 'serial',
          'unsigned' => TRUE,
          'not null' => TRUE,
        ),
        'fixed_description' => array(
          'description' => 'Fixed description field',
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
          'default' => '',
        ),
        'item_description' => array(
          'description' => 'item description',
          'type' => 'text',
          'not null' => TRUE,
          'default' => 0,
          'size' => 'big',
        ),
      ),
    'primary key' => array('id'),
  );

  return $schema;
}

/**
 * Add fixed description and update item description field.
 * It is important that all changes made in hook_update_N 
 * are copied into hook_schema.
 */
function MYMODULE_update_7100() {
  $fixed_description = array(
    'description' => 'Fixed description field',
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'default' => '',
  );
  db_add_field( 'MYTABLE', 'fixed_description', $fixed_description);
  
  db_change_field('MYTABLE', 'item_description', 'item_description', 
    array(
      'description' => 'Item description field',
      'type' => 'text',
      'not null' => FALSE,
      'size' => 'big',
    )
  );
}

You can see how to create a table in the article Create table by using hook_schema.

What does the N mean in hook_update_N?

For example MYMODULE_update_7109:
7 = Drupal version
1 = Major module version, in this case module version 7.x-1.0
09 = Update sequence number, this is the 9th update for MYMODULE

Why sequence numbers?

Sequence numbers are stored in the system table. You can find the latest update number in the schema_version field. An update equal or lower than the number in schema_veriosn will never be available when running update.php or drush updatedb.

Hook_update_N is part of the Drupal system API.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.