Multipass hook update N

Public

This snippet shows how to deal with complex and time consuming updates by taking advantage of the Batch API in conjunction with the hook_update_N placed in a module_name.install file in your module.

Get raw version
php
  1. function module_name_update_6001(&$sandbox) {
  2. // Define return array.
  3. $ret = array();
  4. // Set initial variables for the first loop.
  5. if (!isset($sandbox['progress'])) {
  6. // SQL query to get the total number of elements to process.
  7. $sql = "SELECT COUNT(column) FROM {table} WHERE ...";
  8. $result = db_result(db_query($sql));
  9. $sandbox['max'] = $result;
  10. // Initially set progress to 0.
  11. $sandbox['progress'] = 0;
  12. // Define number of elements to be processed in each loop.
  13. $sandbox['elements_per_loop'] = 7;
  14. }
  15.  
  16. // Get the elements of the current loop.
  17. $sql = "SELECT column FROM {table} WHERE ...";
  18. $result = db_query_range($sql,$sandbox['progress'], $sandbox['elements_per_loop']);
  19. while ($row = db_fetch_array($result)) {
  20. // Here goes the complex and time consuming processing.
  21. // Typically a node_save($node) or something similar.
  22. ...
  23. // And finally update the progress for the next loop.
  24. $sandbox['progress']++;
  25. }
  26.  
  27. // Check end loop condition.
  28. $ret['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);
  29. if ($ret['#finished'] === 1) {
  30. $ret[] = array(
  31. 'success' => TRUE,
  32. 'query' => t('Update_6001 was successfully applied')
  33. );
  34. }
  35.  
  36. // We may also want to handle errors in order to notice if something went wrong
  37. // and know exactly what was the cause.
  38. // To achive this, just add the following as many times as errors to be handled,
  39. // and the update will be stopped at this point:
  40. if (<something bad happened>) {
  41. $ret['#abort'] = array(
  42. 'success' => FALSE,
  43. 'query' => t('message explaining what went wrong')
  44. );
  45. }
  46.  
  47. return $ret;
  48. }