You are here

static function MultiversionManager::fixPrimaryKeys in Multiversion 8.2

File

src/MultiversionManager.php, line 494

Class

MultiversionManager

Namespace

Drupal\multiversion

Code

static function fixPrimaryKeys($entity_type_id, EntityTypeManagerInterface $entity_type_manager, Connection $connection) {
  $storage = $entity_type_manager
    ->getStorage($entity_type_id);
  $entity_type = $storage
    ->getEntityType();

  // Make sure that 'id', 'revision' and 'langcode' are primary keys.
  $schema = $connection
    ->schema();

  // Fix primary key in the base table.
  $base_table = $storage
    ->getBaseTable();
  try {
    $id_key = $entity_type
      ->getKey('id');
    $schema
      ->dropPrimaryKey($base_table);
    $connection
      ->query('ALTER TABLE {' . $base_table . '} MODIFY COLUMN ' . $id_key . ' INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY');
  } catch (\Exception $e) {

    // Do nothing, the index already exists.
  }

  // Fix primary key in the revision table.
  if ($revision_table = $storage
    ->getRevisionTable()) {
    try {
      $revision_key = $entity_type
        ->getKey('revision');
      $schema
        ->dropPrimaryKey($revision_table);
      $connection
        ->query('ALTER TABLE {' . $revision_table . '} MODIFY COLUMN ' . $revision_key . ' INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY');
    } catch (\Exception $e) {

      // Do nothing, the index already exists.
    }
  }

  // Fix primary key in the data table.
  if ($entity_type
    ->isTranslatable() && ($data_table = $storage
    ->getDataTable())) {
    try {
      $schema
        ->dropPrimaryKey($data_table);
      $schema
        ->addPrimaryKey($data_table, [
        $entity_type
          ->getKey('id'),
        $entity_type
          ->getKey('langcode'),
      ]);
    } catch (\Exception $e) {

      // Do nothing, the index already exists.
    }
  }

  // Fix primary key in the revision data table.
  if ($entity_type
    ->isTranslatable() && ($revision_data_table = $storage
    ->getRevisionDataTable())) {
    try {
      $schema
        ->dropPrimaryKey($revision_data_table);
      $schema
        ->addPrimaryKey($revision_data_table, [
        $entity_type
          ->getKey('revision'),
        $entity_type
          ->getKey('langcode'),
      ]);
    } catch (\Exception $e) {

      // Do nothing, the index already exists.
    }
  }
}