--- /dev/null
+/**
+ * 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('mytable1', '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(myprimarykey) FROM {mytable1}')->fetchField() - 1;
+ }
+
+ // Update in chunks of 20.
+ $records = Database::getConnection()->select('mytable1', 'm')
+ ->fields('m', ['myprimarykey', 'otherfield'])
+ ->condition('myprimarykey', $sandbox['current_pk'], '>')
+ ->range(0, 20)
+ ->orderBy('myprimarykey', '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('mytable1')
+ ->fields(['otherfield' => $record->otherfield . '-suffix'])
+ ->condition('myprimarykey', $record->myprimarykey)
+ ->execute();
+
+ $sandbox['progress']++;
+ $sandbox['current_pk'] = $record->myprimarykey;
+ }
+
+ $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');
+}