/** * Implements hook_update_N(). */ function {{ machine_name }}_update_N(&$sandbox) { // For non-batch updates, the signature can simply be: // function {{ machine_name }}_update_N() { // Example function body for adding a field to a database table, which does // not require a batch operation: $spec = [ 'type' => 'varchar', 'description' => "New Col", 'length' => 20, 'not null' => FALSE, ]; $schema = Database::getConnection()->schema(); $schema->addField('my_table', 'newcol', $spec); // Example of what to do if there is an error during your update. if ($some_error_condition_met) { throw new UpdateException('Something went wrong; here is what you should do.'); } // Example function body for a batch update. In this example, the values in // a database field are updated. if (!isset($sandbox['progress'])) { // This must be the first run. Initialize the sandbox. $sandbox['progress'] = 0; $sandbox['current_pk'] = 0; $sandbox['max'] = Database::getConnection()->query('SELECT COUNT([my_primary_key]) FROM {my_table}')->fetchField(); } // Update in chunks of 20. $records = Database::getConnection()->select('my_table', 'm') ->fields('m', ['my_primary_key', 'other_field']) ->condition('my_primary_key', $sandbox['current_pk'], '>') ->range(0, 20) ->orderBy('my_primary_key', 'ASC') ->execute(); foreach ($records as $record) { // Here, you would make an update something related to this record. In this // example, some text is added to the other field. Database::getConnection()->update('my_table') ->fields(['other_field' => $record->other_field . '-suffix']) ->condition('my_primary_key', $record->my_primary_key) ->execute(); $sandbox['progress']++; $sandbox['current_pk'] = $record->my_primary_key; } $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, return nothing. return t('All foo bars were updated with the new suffix'); }