bulkInsert causes DB exception when inserting entity references using target_id_string

Created on 20 February 2025, 2 days ago

Problem/Motivation

After upgrading to 8.x-2.0-beta18 from 8.x-2.0-beta17, the Drush command no longer works for us. It throws the following error when trying to insert entity usage for paragraphs using a reference entity that doesn't use a target_id, but only with a target_id_string

Drupal\Core\Database\IntegrityConstraintViolationException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'target_id' cannot be null

If I run it using the GUI, a similar warning can be seen

Warning: Undefined array key "target_id" in Drupal\Core\Database\Query\Insert->values() (line 108 of /code/web/core/lib/Drupal/Core/Database/Query/InsertTrait.php)

Steps to reproduce

Create a paragraph type with multiple entity reference fields referencing custom entities with and without an integer target_id. Then run the Drush entity-usage:recreate. Below is an example snapshot of the inserts data when EntityUsage->bulkInsert() is called for us.

$this->inserts = [
  '1custom_form22paragraphen26' => [
    'target_id' => '1',
    'target_type' => 'custom_form',
    'source_id' => '22',
    'source_type' => 'paragraph',
    'source_langcode' => 'en',
    'source_vid' => '26',
    'method' => 'entity_reference',
    'field_name' => 'form_reference_field',
    'count' => 1,
  ],
  'cardscustom_style23paragraphen34' => [
    'target_id_string' => 'cards',
    'target_type' => 'custom_style',
    'source_id' => '23',
    'source_type' => 'paragraph',
    'source_langcode' => 'en',
    'source_vid' => '34',
    'method' => 'entity_reference',
    'field_name' => 'style_reference_field',
    'count' => 1,
  ],
];

The code array_key_first($this->inserts) only takes the keys of the first item and uses them as the fields params so it will cause a mismatch when trying to insert values of the second item, which doesn't contain a target_id.

Proposed resolution

Support both the target_id and target_id_string use case in the bulkInsert method.

πŸ› Bug report
Status

Active

Version

2.0

Component

Code

Created by

πŸ‡ΉπŸ‡ΌTaiwan peterwcm

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

Merge Requests

Comments & Activities

Production build 0.71.5 2024