Chris@0
|
1 /**
|
Chris@0
|
2 * Implements hook_update_N().
|
Chris@0
|
3 */
|
Chris@0
|
4 function {{ machine_name }}_update_N(&$sandbox) {
|
Chris@0
|
5 // For non-batch updates, the signature can simply be:
|
Chris@0
|
6 // function {{ machine_name }}_update_N() {
|
Chris@0
|
7
|
Chris@0
|
8 // Example function body for adding a field to a database table, which does
|
Chris@0
|
9 // not require a batch operation:
|
Chris@0
|
10 $spec = [
|
Chris@0
|
11 'type' => 'varchar',
|
Chris@0
|
12 'description' => "New Col",
|
Chris@0
|
13 'length' => 20,
|
Chris@0
|
14 'not null' => FALSE,
|
Chris@0
|
15 ];
|
Chris@0
|
16 $schema = Database::getConnection()->schema();
|
Chris@0
|
17 $schema->addField('mytable1', 'newcol', $spec);
|
Chris@0
|
18
|
Chris@0
|
19 // Example of what to do if there is an error during your update.
|
Chris@0
|
20 if ($some_error_condition_met) {
|
Chris@0
|
21 throw new UpdateException('Something went wrong; here is what you should do.');
|
Chris@0
|
22 }
|
Chris@0
|
23
|
Chris@0
|
24 // Example function body for a batch update. In this example, the values in
|
Chris@0
|
25 // a database field are updated.
|
Chris@0
|
26 if (!isset($sandbox['progress'])) {
|
Chris@0
|
27 // This must be the first run. Initialize the sandbox.
|
Chris@0
|
28 $sandbox['progress'] = 0;
|
Chris@0
|
29 $sandbox['current_pk'] = 0;
|
Chris@0
|
30 $sandbox['max'] = Database::getConnection()->query('SELECT COUNT(myprimarykey) FROM {mytable1}')->fetchField() - 1;
|
Chris@0
|
31 }
|
Chris@0
|
32
|
Chris@0
|
33 // Update in chunks of 20.
|
Chris@0
|
34 $records = Database::getConnection()->select('mytable1', 'm')
|
Chris@0
|
35 ->fields('m', ['myprimarykey', 'otherfield'])
|
Chris@0
|
36 ->condition('myprimarykey', $sandbox['current_pk'], '>')
|
Chris@0
|
37 ->range(0, 20)
|
Chris@0
|
38 ->orderBy('myprimarykey', 'ASC')
|
Chris@0
|
39 ->execute();
|
Chris@0
|
40 foreach ($records as $record) {
|
Chris@0
|
41 // Here, you would make an update something related to this record. In this
|
Chris@0
|
42 // example, some text is added to the other field.
|
Chris@0
|
43 Database::getConnection()->update('mytable1')
|
Chris@0
|
44 ->fields(['otherfield' => $record->otherfield . '-suffix'])
|
Chris@0
|
45 ->condition('myprimarykey', $record->myprimarykey)
|
Chris@0
|
46 ->execute();
|
Chris@0
|
47
|
Chris@0
|
48 $sandbox['progress']++;
|
Chris@0
|
49 $sandbox['current_pk'] = $record->myprimarykey;
|
Chris@0
|
50 }
|
Chris@0
|
51
|
Chris@0
|
52 $sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);
|
Chris@0
|
53
|
Chris@0
|
54 // To display a message to the user when the update is completed, return it.
|
Chris@0
|
55 // If you do not want to display a completion message, return nothing.
|
Chris@0
|
56 return t('All foo bars were updated with the new suffix');
|
Chris@0
|
57 }
|