You are here

function taxonomy_update_8502 in Drupal 8

Copy hierarchy from {taxonomy_term_hierarchy} to {taxonomy_term__parent}.

File

core/modules/taxonomy/taxonomy.install, line 61
Install, update and uninstall functions for the taxonomy module.

Code

function taxonomy_update_8502(&$sandbox) {
  $database = \Drupal::database();
  if (!isset($sandbox['current'])) {

    // Set batch ops sandbox.
    $sandbox['current'] = 0;
    $sandbox['tid'] = -1;
    $sandbox['delta'] = 0;
    $sandbox['limit'] = Settings::get('entity_update_batch_size', 50);

    // Count records using a join, as there might be orphans in the hierarchy
    // table. See https://www.drupal.org/project/drupal/issues/2997982.
    $select = $database
      ->select('taxonomy_term_hierarchy', 'h');
    $select
      ->join('taxonomy_term_data', 'd', 'h.tid = d.tid');
    $sandbox['max'] = $select
      ->countQuery()
      ->execute()
      ->fetchField();
  }

  // Save the hierarchy.
  $select = $database
    ->select('taxonomy_term_hierarchy', 'h');
  $select
    ->join('taxonomy_term_data', 'd', 'h.tid = d.tid');
  $hierarchy = $select
    ->fields('h', [
    'tid',
    'parent',
  ])
    ->fields('d', [
    'vid',
    'langcode',
  ])
    ->range($sandbox['current'], $sandbox['limit'])
    ->orderBy('tid', 'ASC')
    ->orderBy('parent', 'ASC')
    ->execute()
    ->fetchAll();

  // Restore data.
  $insert = $database
    ->insert('taxonomy_term__parent')
    ->fields([
    'bundle',
    'entity_id',
    'revision_id',
    'langcode',
    'delta',
    'parent_target_id',
  ]);
  foreach ($hierarchy as $row) {
    if ($row->tid !== $sandbox['tid']) {
      $sandbox['delta'] = 0;
      $sandbox['tid'] = $row->tid;
    }
    $insert
      ->values([
      'bundle' => $row->vid,
      'entity_id' => $row->tid,
      'revision_id' => $row->tid,
      'langcode' => $row->langcode,
      'delta' => $sandbox['delta'],
      'parent_target_id' => $row->parent,
    ]);
    $sandbox['delta']++;
    $sandbox['current']++;
  }
  $insert
    ->execute();
  $sandbox['#finished'] = empty($sandbox['max']) ? 1 : $sandbox['current'] / $sandbox['max'];
  if ($sandbox['#finished'] >= 1) {

    // Update the entity type because the 'taxonomy_term_hierarchy' table is no
    // longer part of its shared tables schema.
    $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
    $definition_update_manager
      ->updateEntityType($definition_update_manager
      ->getEntityType('taxonomy_term'));

    // \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema::onEntityTypeUpdate()
    // only deletes *known* entity tables (i.e. the base, data and revision
    // tables), so we have to drop it manually.
    $database
      ->schema()
      ->dropTable('taxonomy_term_hierarchy');
    return t('Taxonomy term hierarchy has been converted to default entity reference storage.');
  }
}