What does hook_update_n really do

Problem : How does hook_update_n work in Drupal.

Why we use it: We want to perform a change on a website that is already live. We cannot uninstall and re-enable the module. So we add a hook_update_n

Solution

Well Idealy its all about the naming of the hook SO it goes like this

mymodulename_update_7002
what is 7002?

  • 7 = core compatibilyty, so in this case it is compatible with Drupal 7
  • 0 = you module major release version, in this case its relaease 0
  • 02 = two digits for sequential counting. so this is the second change you are adding in the 0 release of your module

 

Where to put this:

  1. IN the mymodule.install file
  2. In your <active-profile>.install file

 

HOW TO RUN: basically going to update.php will do. Or else from the command line run drush updb

WHAT HAPPENS:
All the magic happens in includes/update.inc . This file collectively has a list of functions that will

  1. lookup the system table
  2. Get the latest schema_version for any installed module (Ex: 7001). 
  3. Then call all the hook_update_n implementations in sequence 02, 03, 04 .... 99

 

On the database you are using you can check what the latest scema_version is by running the following query

SELECT schema_version FROM `system` WHERE name = 'mymodulename'