function hook_update_N

Perform a single update.

For each change that requires one or more actions to be performed when updating a site, add a new hook_update_N(), which will be called by update.php. The documentation block preceding this function is stripped of newlines and used as the description for the update on the pending updates task list. Schema updates should adhere to the Schema API.

Implementations of hook_update_N() are named (module name)_update_(number). The numbers are composed of three parts:

  • 1 digit for Drupal core compatibility.
  • 1 digit for your module's major release version (e.g., is this the 8.x-1.* (1) or 8.x-2.* (2) series of your module?). This digit should be 0 for initial porting of your module to a new Drupal core API.
  • 2 digits for sequential counting, starting with 00.

Examples:

  • mymodule_update_8000(): This is the required update for mymodule to run with Drupal core API 8.x when upgrading from Drupal core API 7.x.
  • mymodule_update_8100(): This is the first update to get the database ready to run mymodule 8.x-1.*.
  • mymodule_update_8200(): This is the first update to get the database ready to run mymodule 8.x-2.*. Users can directly update from 7.x-2.* to 8.x-2.* and they get all 80xx and 82xx updates, but not 81xx updates, because those reside in the 8.x-1.x branch only.

A good rule of thumb is to remove updates older than two major releases of Drupal. See hook_update_last_removed() to notify Drupal about the removals. For further information about releases and release numbers see: Maintaining a drupal.org project with Git

Never renumber update functions.

Implementations of this hook should be placed in a mymodule.install file in the same directory as mymodule.module. Drupal core's updates are implemented using the system module as a name and stored in database/updates.inc.

Not all module functions are available from within a hook_update_N() function. In order to call a function from your mymodule.module or an include file, you need to explicitly load that file first.

During database updates the schema of any module could be out of date. For this reason, caution is needed when using any API function within an update function - particularly CRUD functions, functions that depend on the schema (for example by using drupal_write_record()), and any functions that invoke hooks. See Update versions of API functions for details.

If your update task is potentially time-consuming, you'll need to implement a multipass update to avoid PHP timeouts. Multipass updates use the $sandbox parameter provided by the batch API (normally, $context['sandbox']) to store information between successive calls, and the $sandbox['#finished'] value to provide feedback regarding completion level.

See the batch operations page for more information on how to use the Batch API.

Parameters

$sandbox: Stores information for multipass updates. See above for more information.

Return value

Optionally, update hooks may return a translated string that will be displayed to the user after the update has completed. If no message is returned, no message will be presented to the user.

Throws

Drupal\Core\Utility\UpdateException, PDOException In case of error, update hooks should throw an instance of Drupal\Core\Utility\UpdateException with a meaningful message for the user. If a database query fails for whatever reason, it will throw a PDOException.

See also

Batch operations

Schema API

Update versions of API functions

hook_update_last_removed()

update_get_update_list()

Related topics

241 functions implement hook_update_N()

Note: this list is generated by pattern matching, so it may include some functions that are not actually implementations of this hook.

aggregator_update_8000 in drupal/core/modules/aggregator/aggregator.install
Moves aggregator settings from variables to config.
aggregator_update_8001 in drupal/core/modules/aggregator/aggregator.install
Adds the langcode field to {aggregator_item} and {aggregator_feed}.
block_update_8000 in drupal/core/modules/block/block.install
Block cache is always enabled in 8.x.
block_update_8001 in drupal/core/modules/block/block.install
Creates table {block_language} for language visibility settings per block.
block_update_8002 in drupal/core/modules/block/block.install
Replace serial role IDs with machine name strings.

... See full list

File

drupal/core/modules/system/system.api.php, line 2674
Hooks provided by Drupal core and the System module.

Code

function hook_update_N(&$sandbox) {

  // For non-multipass updates, the signature can simply be;
  // function hook_update_N() {
  // For most updates, the following is sufficient.
  db_add_field('mytable1', 'newcol', array(
    'type' => 'int',
    'not null' => TRUE,
    'description' => 'My new integer column.',
  ));

  // However, for more complex operations that may take a long time,
  // you may hook into Batch API as in the following example.
  // Update 3 users at a time to have an exclamation point after their names.
  // (They're really happy that we can do batch API in this hook!)
  if (!isset($sandbox['progress'])) {
    $sandbox['progress'] = 0;
    $sandbox['current_uid'] = 0;

    // We'll -1 to disregard the uid 0...
    $sandbox['max'] = db_query('SELECT COUNT(DISTINCT uid) FROM {users}')
      ->fetchField() - 1;
  }
  $users = db_select('users', 'u')
    ->fields('u', array(
    'uid',
    'name',
  ))
    ->condition('uid', $sandbox['current_uid'], '>')
    ->range(0, 3)
    ->orderBy('uid', 'ASC')
    ->execute();
  foreach ($users as $user) {
    $user->name .= '!';
    db_update('users')
      ->fields(array(
      'name' => $user->name,
    ))
      ->condition('uid', $user->uid)
      ->execute();
    $sandbox['progress']++;
    $sandbox['current_uid'] = $user->uid;
  }
  $sandbox['#finished'] = empty($sandbox['max']) ? 1 : $sandbox['progress'] / $sandbox['max'];

  // To display a message to the user when the update is completed, return it.
  // If you do not want to display a completion message, simply return nothing.
  return t('The update did what it was supposed to do.');

  // In case of an error, simply throw an exception with an error message.
  throw new UpdateException('Something went wrong; here is what you should do.');
}