Consider the following situation:
- A Drupal 8 site using native SQL-storage (MySQL)
custom_tableis added to the same MySQL host as Drupal, either as a table in the Drupal system DB or as a table in a separate DB on the same host (Drupal supports either as the basis of a new entity). This table is the
base_tableof a custom content entity (
custom_entity) as declared in
custom_module. The entity is defined by extending \Drupal\Core\Entity\ContentEntityBase.
- Individual columns from
custom_tableare also mapped directly to Drupal fields on
baseFieldDefinitions()method in the entity definition.
custom_tableis not declared in
hook_schema()because it is managed by external tools and may even have CRUD operations on it external to Drupal. The
persistent_cacheis disabled for
custom_entityto account for this.
custom_moduleis installed. The install routines automatically create entity/field storage definitions and related schema definitions as part of the installed state based on the
custom_tablegrows full of data.
- The schema of
custom_tableneeds to be updated (e.g. a new column added and mapped to a new
custom_entityfield, length increase to existing varchar string, etc.)
Because the schema of
custom_table is not managed by Drupal how can Drupal be made aware of the schema updates in a way that is compatible with the native SQL entity and field storage that
EntityDefinitionUpdateManagerInterface seems to serve as a central place to deal with updates of this nature, but it also appears to couple updates to storage/schema definitions with the deployment of changes to actual DB schema. That said, I have had some success with snippets like this after updating the
custom_entity definition appropriately:
$entity_type = \Drupal::entityTypeManager()->getDefinition('custom_entity'); $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager(); $entity_definition_update_manager->installEntityType($entity_type);
However, this method is documented for once-off use (not ongoing re-install use) so this feels like inappropriate use with possible side-effects.
I have also experimented with the entityDefinitionUpdateManager
::updateFieldStorageDefinition methods, as those appear safe to re-run, but they do not seem to update the installed schema definition appropriately.
I also suppose that a custom entity storage definition could be justified to deal with all this, but I assume that would require re-defining or re-wiring quite a few dependencies (notably the low-level SQL management) that otherwise work well with the native entity storage.