Skip to content

Instantly share code, notes, and snippets.

@juampynr
Last active August 29, 2015 14:07
Show Gist options
  • Save juampynr/1942394dac918ae986c2 to your computer and use it in GitHub Desktop.
Save juampynr/1942394dac918ae986c2 to your computer and use it in GitHub Desktop.
Database update with Batch API template
<?php
/**
* @file mymodule.install
* Install hooks for mymodule.
*/
/**
* Description of what the database update does. Do not use "Implements..." since it adds
* zero information and makes reading the list of pending database updates in Drush harder
* to read.
*/
function mymodule_update_7100(&$sandbox) {
// Number of items to process per loop. This may vary depending on the server's
// resources. It is better to keep it to a low number so we never hit a PHP
// memory limit.
$items_per_loop = 10;
// Initial setup.
if (!isset($sandbox['current'])) {
// This piece of code will run on the first loop. Here we will
// set the following:
// 1. $sandbox['current']: defines the current chunk of items to process.
$sandbox['current'] = 0;
// 2. $sandbox['chunks']: contains the list of chunks of ids to process.
$nids = db_query("select nid from {node} where type = 'show'")->fetchCol();
if (empty($nids)) {
watchdog('mymodule', 'There are no items to process.', array(), WATCHDOG_NOTICE);
return;
}
// Split the list in chunks to be processed in each loop.
$sandbox['chunks'] = array_chunk($nids, $items_per_loop);
// 3. $sandbox['total']: contains the total amount of chunks to process.
$sandbox['total'] = count($sandbox['chunks']);
}
// Extract the current chunk of ids.
$nids = $sandbox['chunks'][$sandbox['current']];
// Process the list of ids.
// [Add your code here]
// Update batch status.
$sandbox['current']++;
$sandbox['#finished'] = ($sandbox['current'] >= $sandbox['total']) ? 1 : ($sandbox['current'] / $sandbox['total']);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment