4 * Update.php for provisioned sites.
5 * This file is a derivative of the standard drupal update.php,
6 * which has been modified to allow being run from the command
10 use Drush\Log\LogLevel;
13 * Drupal's update.inc has functions that are in previous update_X.inc files
14 * for example, update_check_incompatibility() which can prove useful when
17 require_once DRUSH_DRUPAL_CORE . '/includes/update.inc';
19 use Drupal\Core\Utility\Error;
20 use Drupal\Core\Entity\EntityStorageException;
22 * Perform one update and store the results which will later be displayed on
25 * An update function can force the current and all later updates for this
26 * module to abort by returning a $ret array with an element like:
27 * $ret['#abort'] = array('success' => FALSE, 'query' => 'What went wrong');
28 * The schema version will not be updated in this case, and all the
29 * aborted updates will continue to appear on update.php as updates that
30 * have not yet been run.
33 * The module whose update will be run.
35 * The update number to run.
37 * The batch context array
39 function drush_update_do_one($module, $number, $dependency_map, &$context) {
40 $function = $module . '_update_' . $number;
42 // If this update was aborted in a previous step, or has a dependency that
43 // was aborted in a previous step, go no further.
44 if (!empty($context['results']['#abort']) && array_intersect($context['results']['#abort'], array_merge($dependency_map, array($function)))) {
48 $context['log'] = FALSE;
50 \Drupal::moduleHandler()->loadInclude($module, 'install');
53 if (function_exists($function)) {
55 if ($context['log']) {
56 Database::startLog($function);
59 drush_log("Executing " . $function);
60 $ret['results']['query'] = $function($context['sandbox']);
61 $ret['results']['success'] = TRUE;
63 // @TODO We may want to do different error handling for different exception
64 // types, but for now we'll just print the message.
65 catch (Exception $e) {
66 $ret['#abort'] = array('success' => FALSE, 'query' => $e->getMessage());
67 drush_set_error('DRUPAL_EXCEPTION', $e->getMessage());
70 if ($context['log']) {
71 $ret['queries'] = Database::getLog($function);
75 $ret['#abort'] = array('success' => FALSE);
76 drush_set_error('DRUSH_UPDATE_FUNCTION_NOT_FOUND', dt('Update function @function not found', array('@function' => $function)));
79 if (isset($context['sandbox']['#finished'])) {
80 $context['finished'] = $context['sandbox']['#finished'];
81 unset($context['sandbox']['#finished']);
84 if (!isset($context['results'][$module])) {
85 $context['results'][$module] = array();
87 if (!isset($context['results'][$module][$number])) {
88 $context['results'][$module][$number] = array();
90 $context['results'][$module][$number] = array_merge($context['results'][$module][$number], $ret);
92 if (!empty($ret['#abort'])) {
93 // Record this function in the list of updates that were aborted.
94 $context['results']['#abort'][] = $function;
97 // Record the schema update if it was completed successfully.
98 if ($context['finished'] == 1 && empty($ret['#abort'])) {
99 drupal_set_installed_schema_version($module, $number);
102 $context['message'] = 'Performing ' . $function;
106 * Clears caches and rebuilds the container.
108 * This is called in between regular updates and post updates. Do not use
109 * drush_drupal_cache_clear_all() as the cache clearing and container rebuild
110 * must happen in the same process that the updates are run in.
112 * Drupal core's update.php uses drupal_flush_all_caches() directly without
113 * explicitly rebuilding the container as the container is rebuilt on the next
114 * HTTP request of the batch.
116 * @see drush_drupal_cache_clear_all()
117 * @see \Drupal\system\Controller\DbUpdateController::triggerBatch()
119 function drush_update_cache_rebuild() {
120 drupal_flush_all_caches();
121 \Drupal::service('kernel')->rebuildContainer();
124 function update_main() {
125 // In D8, we expect to be in full bootstrap.
126 drush_bootstrap_to_phase(DRUSH_BOOTSTRAP_DRUPAL_FULL);
128 require_once DRUPAL_ROOT . '/core/includes/install.inc';
129 require_once DRUPAL_ROOT . '/core/includes/update.inc';
130 drupal_load_updates();
131 update_fix_compatibility();
133 // Pending hook_update_N() implementations.
134 $pending = update_get_update_list();
136 // Pending hook_post_update_X() implementations.
137 $post_updates = \Drupal::service('update.post_update_registry')->getPendingUpdateInformation();
141 $change_summary = [];
142 if (drush_get_option('entity-updates', FALSE)) {
143 $change_summary = \Drupal::entityDefinitionUpdateManager()->getChangeSummary();
146 // Print a list of pending updates for this module and get confirmation.
147 if (count($pending) || count($change_summary) || count($post_updates)) {
148 drush_print(dt('The following updates are pending:'));
151 foreach ($change_summary as $entity_type_id => $changes) {
152 drush_print($entity_type_id . ' entity type : ');
153 foreach ($changes as $change) {
154 drush_print(strip_tags($change), 2);
158 foreach (array('update', 'post_update') as $update_type) {
159 $updates = $update_type == 'update' ? $pending : $post_updates;
160 foreach ($updates as $module => $updates) {
161 if (isset($updates['start'])) {
162 drush_print($module . ' module : ');
163 if (!empty($updates['pending'])) {
164 $start += [$module => array()];
166 $start[$module] = array_merge($start[$module], $updates['pending']);
167 foreach ($updates['pending'] as $update) {
168 drush_print(strip_tags($update), 2);
176 if (!drush_confirm(dt('Do you wish to run all pending updates?'))) {
177 return drush_user_abort();
180 drush_update_batch($start);
183 drush_log(dt("No database updates required"), LogLevel::SUCCESS);
186 return count($pending) + count($change_summary) + count($post_updates);
189 function _update_batch_command($id) {
190 // In D8, we expect to be in full bootstrap.
191 drush_bootstrap_to_phase(DRUSH_BOOTSTRAP_DRUPAL_FULL);
193 drush_batch_command($id);
197 * Start the database update batch process.
199 function drush_update_batch() {
200 $start = drush_get_update_list();
201 // Resolve any update dependencies to determine the actual updates that will
202 // be run and the order they will be run in.
203 $updates = update_resolve_dependencies($start);
205 // Store the dependencies for each update function in an array which the
206 // batch API can pass in to the batch operation each time it is called. (We
207 // do not store the entire update dependency array here because it is
208 // potentially very large.)
209 $dependency_map = array();
210 foreach ($updates as $function => $update) {
211 $dependency_map[$function] = !empty($update['reverse_paths']) ? array_keys($update['reverse_paths']) : array();
214 $operations = array();
216 foreach ($updates as $update) {
217 if ($update['allowed']) {
218 // Set the installed version of each module so updates will start at the
219 // correct place. (The updates are already sorted, so we can simply base
220 // this on the first one we come across in the above foreach loop.)
221 if (isset($start[$update['module']])) {
222 drupal_set_installed_schema_version($update['module'], $update['number'] - 1);
223 unset($start[$update['module']]);
225 // Add this update function to the batch.
226 $function = $update['module'] . '_update_' . $update['number'];
227 $operations[] = array('drush_update_do_one', array($update['module'], $update['number'], $dependency_map[$function]));
231 // Apply post update hooks.
232 $post_updates = \Drupal::service('update.post_update_registry')->getPendingUpdateFunctions();
234 $operations[] = ['drush_update_cache_rebuild', []];
235 foreach ($post_updates as $function) {
236 $operations[] = ['update_invoke_post_update', [$function]];
240 // Lastly, perform entity definition updates, which will update storage
241 // schema if needed. If module update functions need to work with specific
242 // entity schema they should call the entity update service for the specific
243 // update themselves.
244 // @see \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface::applyEntityUpdate()
245 // @see \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface::applyFieldUpdate()
246 if (drush_get_option('entity-updates', FALSE) && \Drupal::entityDefinitionUpdateManager()->needsUpdates()) {
247 $operations[] = array('drush_update_entity_definitions', array());
250 $batch['operations'] = $operations;
252 'title' => 'Updating',
253 'init_message' => 'Starting updates',
254 'error_message' => 'An unrecoverable error has occurred. You can find the error message below. It is advised to copy it to the clipboard for reference.',
255 'finished' => 'drush_update_finished',
256 'file' => 'includes/update.inc',
259 \Drupal::service('state')->set('system.maintenance_mode', TRUE);
260 drush_backend_batch_process('updatedb-batch-process');
261 \Drupal::service('state')->set('system.maintenance_mode', FALSE);
265 * Apply entity schema updates.
267 function drush_update_entity_definitions(&$context) {
269 \Drupal::entityDefinitionUpdateManager()->applyUpdates();
271 catch (EntityStorageException $e) {
272 watchdog_exception('update', $e);
273 $variables = Error::decodeException($e);
274 unset($variables['backtrace']);
275 // The exception message is run through
276 // \Drupal\Component\Utility\SafeMarkup::checkPlain() by
277 // \Drupal\Core\Utility\Error::decodeException().
278 $ret['#abort'] = array('success' => FALSE, 'query' => t('%type: !message in %function (line %line of %file).', $variables));
279 $context['results']['core']['update_entity_definitions'] = $ret;
280 $context['results']['#abort'][] = 'update_entity_definitions';
284 // Copy of protected \Drupal\system\Controller\DbUpdateController::getModuleUpdates.
285 function drush_get_update_list() {
287 $updates = update_get_update_list();
288 foreach ($updates as $module => $update) {
289 $return[$module] = $update['start'];
296 * Process and display any returned update output.
298 * @see \Drupal\system\Controller\DbUpdateController::batchFinished()
299 * @see \Drupal\system\Controller\DbUpdateController::results()
301 function drush_update_finished($success, $results, $operations) {
303 if (!drush_get_option('cache-clear', TRUE)) {
304 drush_log(dt("Skipping cache-clear operation due to --cache-clear=0 option."), LogLevel::WARNING);
307 drupal_flush_all_caches();
310 foreach ($results as $module => $updates) {
311 if ($module != '#abort') {
312 foreach ($updates as $number => $queries) {
313 foreach ($queries as $query) {
314 // If there is no message for this update, don't show anything.
315 if (empty($query['query'])) {
319 if ($query['success']) {
320 drush_log(strip_tags($query['query']));
323 drush_set_error(dt('Failed: ') . strip_tags($query['query']));
332 * Return a 2 item array with
333 * - an array where each item is a 3 item associative array describing a pending update.
334 * - an array listing the first update to run, keyed by module.
336 function updatedb_status() {
337 $pending = update_get_update_list();
340 // Ensure system module's updates run first.
341 $start['system'] = array();
343 foreach (\Drupal::entityDefinitionUpdateManager()->getChangeSummary() as $entity_type_id => $changes) {
344 foreach ($changes as $change) {
346 'module' => dt('@type entity type', array('@type' => $entity_type_id)), 'update_id' => '', 'description' => strip_tags($change));
350 // Print a list of pending updates for this module and get confirmation.
351 foreach ($pending as $module => $updates) {
352 if (isset($updates['start'])) {
353 foreach ($updates['pending'] as $update_id => $description) {
354 // Strip cruft from front.
355 $description = str_replace($update_id . ' - ', '', $description);
356 $return[] = array('module' => ucfirst($module), 'update_id' => $update_id, 'description' => $description);
358 if (isset($updates['start'])) {
359 $start[$module] = $updates['start'];
364 return array($return, $start);
368 * Apply pending entity schema updates.
370 function entity_updates_main() {
371 $change_summary = \Drupal::entityDefinitionUpdateManager()->getChangeSummary();
372 if (!empty($change_summary)) {
373 drush_print(dt('The following updates are pending:'));
376 foreach ($change_summary as $entity_type_id => $changes) {
377 drush_print($entity_type_id . ' entity type : ');
378 foreach ($changes as $change) {
379 drush_print(strip_tags($change), 2);
383 if (!drush_confirm(dt('Do you wish to run all pending updates?'))) {
384 return drush_user_abort();
387 $operations[] = array('drush_update_entity_definitions', array());
390 $batch['operations'] = $operations;
392 'title' => 'Updating',
393 'init_message' => 'Starting updates',
394 'error_message' => 'An unrecoverable error has occurred. You can find the error message below. It is advised to copy it to the clipboard for reference.',
395 'finished' => 'drush_update_finished',
396 'file' => 'includes/update.inc',
399 \Drupal::service('state')->set('system.maintenance_mode', TRUE);
400 drush_backend_batch_process('updatedb-batch-process');
401 \Drupal::service('state')->set('system.maintenance_mode', FALSE);
404 drush_log(dt("No entity schema updates required"), LogLevel::SUCCESS);