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