You are here

function data_policy_update_8002 in Data Policy 8

Makes the 'data_policy_revision_id' field multiple and migrate its data.

File

./data_policy.install, line 62
Install, update and uninstall functions for the data_policy module.

Code

function data_policy_update_8002() {

  // To update the field schema we need to have no field data in the storage,
  // thus we retrieve it, delete it from storage, and write it back to the
  // storage after updating the schema.
  $database = \Drupal::database();

  // Retrieve existing field data.
  $data = $database
    ->select('user_consent', 'uc')
    ->fields('uc', [
    'id',
    'data_policy_revision_id',
  ])
    ->execute()
    ->fetchAllKeyed();

  // Remove data from the storage.
  $database
    ->update('user_consent')
    ->fields([
    'data_policy_revision_id' => NULL,
  ])
    ->execute();

  // Update definitions and schema.
  $manager = \Drupal::entityDefinitionUpdateManager();
  $storage_definition = $manager
    ->getFieldStorageDefinition('data_policy_revision_id', 'user_consent');
  $storage_definition
    ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
  $manager
    ->updateFieldStorageDefinition($storage_definition);

  // Restore entity data in the new schema.
  $insert_query = $database
    ->insert('user_consent__data_policy_revision_id')
    ->fields([
    'bundle',
    'deleted',
    'entity_id',
    'revision_id',
    'langcode',
    'delta',
    'data_policy_revision_id_value',
  ]);
  foreach ($data as $id => $data_policy_revision_id) {
    $insert_query
      ->values([
      'user_consent',
      0,
      $id,
      $id,
      'en',
      0,
      $data_policy_revision_id,
    ]);
  }
  $insert_query
    ->execute();
}