Skip to main content

Updating a Drupal Module's Schema

Back-end Development
Drupal

I recently had the need to make updates to a table I am defining using Drupal's schema API.  It's extremely simple to do, though there isn't much in the way of documentation (if there is, let me know in the comments).  The biggest reason to implement a schema update is if you want to make updates to the database, but do not want to lose the data already in the system (otherwise you can just uninstall and reinstall the module to update the schema).

So here's what you do. First you need to modify the hook_schema implementation to include the new fields (or removal of fields). 

For my example I'll be adding a field called 'test_flag' to my custom table.

'test_flag' => array(
  'description' => 'Is this record flagged',
  'type' => 'int',
  'size' => 'tiny',
  'not null' => TRUE,
  'default' => 0,
),

This will ensure that the schema is correct for anyone installing the module for the first time.  But we need to make sure anyone using this module also has the correct schema.  You need to name your function [module name]_update_[version number].  Naming the function this way is important and provides a lot of nice functionality for free.  Your version number should be the version of Drupal times 1000.  So the first update for a module on Drupal 7 should be versioned 7001.  Subsequent versions being 7002, 7003, etc... The comment you place over your function is also important.  This is what will be used as a description to the user updating the module.  

This was an unexpected surprise for me when looking through core. Lastly you need to make the db changes.  Drupal gives us an easy way to do this within a single line of code.  Use db_add_field passing in the name of the schema (table) and the field you are looking to add along with an array of attributes for this field.  The array of attributes uses the same structure other schema definitions.

/**
* Add test_flag fields to the {custom_table} table.
*/
function custom_update_7001() {
  db_add_field(
    'custom_table', 
    'test_flag', 
    array(
      'type' => 'int', 
      'size' => 'tiny', 
      'not null' =>TRUE, 
      'default' => 0,
    )
  );
}

Drupal will automatically recognize that a new version of the module is available and will the run the function code when doing a database update with update.php or drush updb.

Need a fresh perspective on a tough project?

Let’s talk about how RDG can help.

Contact Us