Drupal allows a module developer to easily define a database schema using hook_schema but this won’t work if you need to update the database schema during an update to the module. Fortunately, there is a nice hook in Drupal called hook_update_N that you can place in your module’s .install file. This hook allows you to set updates for different versions of the module so one or more updates can be run depending on the version. This hook is called from /update.php or from drush updatedb.

  

Using hook_update_N is pretty easy but can look a little confusing at first. If your module is named my_module then the hook looks something like this:

 
The numbers ‘7101’ at the end of the function name bear significance. The first digit is the Drupal version (7). The second digit is the plugin major release version(1). The last two numbers are the update number(01). The docblock comment is also important, that’s what is displayed in when a user runs update.php or drush updatedb. In this case the user would be presented with the following message when they are prompted to update: “7101 – Adds Database Fields for an Amazing Update”

  

The $sandbox parameter to the function stores information for multipass and batch updates.

Leave a Reply

Your email address will not be published. Required fields are marked *