Inappropriate error when updating a field schema with existing data

Created on 28 January 2025, about 1 month ago

Problem/Motivation

When attempting to update a field's cardinality programmatically using the `EntityDefinitionUpdateManager`, an error occurs if the field is stored as a property in the entity table, but the update attempts to move the field to a dedicated field table.

The error message is as follows:

<strong>TypeError: array_intersect_key(): Argument #1 ($array) must be of type array, null given in array_intersect_key()</strong> (line 2479 of /core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php)

Steps to reproduce

  1. Install a fresh Drupal core with the Node module enabled.
  2. Create content using the "Node" entity type, and ensure the "Title" field has data stored as a property in the entity table.
  3. Create a custom module with the following hook or equivalent programmatic update (the code below)
  4. Run the update or execute the programmatic code to update the field storage definition.
  5. Observe the error.
  <?php

   use Drupal\Core\Field\FieldStorageDefinitionInterface;

   /**
    * Implements hook_update_N().
    */
   function mymodule_update_9001() {
     // Update definitions and schema.
     /** @var \Drupal\Core\Entity\EntityDefinitionUpdateManager $manager */
     $manager = \Drupal::entityDefinitionUpdateManager();

     /** @var \Drupal\Core\Field\BaseFieldDefinition $definition */
     $definition = $manager->getFieldStorageDefinition('title', 'node');
     // Change cardinality to trigger the schema transition.
     $definition->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
     $manager->updateFieldStorageDefinition($definition);
   }

Proposed resolution

  1. Add a check in `SqlContentEntityStorageSchema::hasColumnChanges()` to identify schema transitions where a field moves from being stored as a property in the entity table to a dedicated field table.
    This check will correctly detect schema transitions and allow the system to throw a meaningful exception instead of a generic error.
  2. Ensure that when such a schema transition is detected, the system throws a `FieldStorageDefinitionUpdateForbiddenException` with a clear message, such as:
    The SQL storage cannot change the schema for an existing field (title in node entity) with data.

Remaining tasks

User interface changes

Introduced terminology

API changes

Data model changes

Release notes snippet

πŸ› Bug report
Status

Needs review

Version

10.3 ✨

Component

entity system

Created by

πŸ‡ΊπŸ‡¦Ukraine UsingSession

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

Comments & Activities

Production build 0.71.5 2024