Include "source_id_string" as primary key for the entity_usage table

Created on 26 November 2019, over 4 years ago
Updated 26 April 2024, 2 months ago

source_id_string isn't attached to primary key in entity_usage database table. This can generate error:

Integrity constraint violation: 1062 Duplicate entry for key PRIMARY

This happens, when one target entity is referenced in two different source entities and source entities id is stored in source_id_string column.

How to update manually?

I've met problems with update similar to these: https://www.drupal.org/node/2981394 โ†’ So decided to use similar strategy.

First option - reinstall the module

  1. Uninstall module
  2. Install module
  3. Re-generate the usage data from the batch generation form

Second option - custom module hook

You can also write hook in your custom module, to do things without reinstall.

Code of hook:

/**
 * Include "source_id_string" also as primary key for the {entity_usage} table.
 * RE-GENERATE USAGE MANUALLY AFTER THIS HOOK WILL BE APPLIED!
 */
function hook_usage_update_N(&$sandbox) {
  $database = \Drupal::database();
  $database->truncate('entity_usage')->execute();
  $database->schema()
    ->changeField('entity_usage', 'source_id_string', 'source_id_string', [
        'description' => 'The source ID, when the entity uses string IDs.',
        'type' => 'varchar_ascii',
        'length' => 128,
        'not null' => TRUE,
        'default' => '',
      ]);

  $database->schema()->dropPrimaryKey('entity_usage');
  $new_primary_keys = [
      'target_id',
      'target_id_string',
      'target_type',
      'source_id',
      'source_id_string',
      'source_type',
      'source_langcode',
      'source_vid',
      'method',
      'field_name',
    ];
  $database->schema()->addPrimaryKey('entity_usage', $new_primary_keys);
}

After update, remember to Re-generate the usage data from the batch generation form, as this hook truncate entity_usage table.

๐Ÿ› Bug report
Status

Active

Version

2.0

Component

Code

Created by

๐Ÿ‡ต๐Ÿ‡ฑPoland gugalamaciek

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.69.0 2024