field.purge.inc 6.94 KB
Newer Older
1 2
<?php

3 4
/**
 * @file
webchick's avatar
webchick committed
5
 * Provides support for field data purge after mass deletion.
6 7
 */

8
use Drupal\field\Entity\Field;
9 10
use Drupal\field\FieldException;

11
/**
12 13
 * @defgroup field_purge Field API bulk data deletion
 * @{
14
 * Cleans up after Field API bulk deletion operations.
15 16
 *
 * Field API provides functions for deleting data attached to individual
17
 * entities as well as deleting entire fields or field instances in a single
18 19
 * operation.
 *
webchick's avatar
webchick committed
20 21 22 23 24 25 26 27 28
 * When a single entity is deleted, the Entity storage controller performs the
 * following operations:
 * - Invoking the FieldInterface delete() method for each field on the
 *   entity. A file field type might use this method to delete uploaded files
 *   from the filesystem.
 * - Removing the data from storage.
 * - Invoking the global hook_entity_delete() for all modules that implement it.
 *   Each hook implementation receives the entity being deleted and can operate
 *   on whichever subset of the entity's bundle's fields it chooses to.
29
 *
webchick's avatar
webchick committed
30
 * Similar operations are performed on deletion of a single entity revision.
31 32
 *
 * When a field, bundle, or field instance is deleted, it is not practical to
webchick's avatar
webchick committed
33 34
 * perform those operations immediately on every affected entity in a single
 * page request; there could be thousands or millions of them. Instead, the
35 36 37
 * appropriate field data items, instances, and/or fields are marked as deleted
 * so that subsequent load or query operations will not return them. Later, a
 * separate process cleans up, or "purges", the marked-as-deleted data by going
38 39
 * through the three-step process described above and, finally, removing deleted
 * field and instance records.
40 41
 *
 * Purging field data is made somewhat tricky by the fact that, while
webchick's avatar
webchick committed
42 43
 * $entity->delete() has a complete entity to pass to the various deletion
 * steps, the Field API purge process only has the field data it has previously
44
 * stored. It cannot reconstruct complete original entities to pass to the
webchick's avatar
webchick committed
45 46 47
 * deletion operations. It is even possible that the original entity to which
 * some Field API data was attached has been itself deleted before the field
 * purge operation takes place.
48
 *
webchick's avatar
webchick committed
49 50 51 52 53
 * Field API resolves this problem by using stub entities during purge
 * operations, containing only the information from the original entity that
 * Field API knows about: entity type, ID, revision ID, and bundle. It also
 * contains the field data for whichever field instance is currently being
 * purged.
54
 *
55 56
 * See @link field Field API @endlink for information about the other parts of
 * the Field API.
57 58 59
 */

/**
60
 * Purges a batch of deleted Field API data, instances, or fields.
61
 *
62 63 64 65 66 67
 * This function will purge deleted field data in batches. The batch size
 * is defined as an argument to the function, and once each batch is finished,
 * it continues with the next batch until all have completed. If a deleted field
 * instance with no remaining data records is found, the instance itself will
 * be purged. If a deleted field with no remaining field instances is found, the
 * field itself will be purged.
68 69 70 71 72 73 74
 *
 * @param $batch_size
 *   The maximum number of field data records to purge before returning.
 */
function field_purge_batch($batch_size) {
  // Retrieve all deleted field instances. We cannot use field_info_instances()
  // because that function does not return deleted instances.
75
  $instances = field_read_instances(array('deleted' => TRUE), array('include_deleted' => TRUE));
76
  $factory = Drupal::service('entity.query');
77
  $info = entity_get_info();
78
  foreach ($instances as $instance) {
79
    $entity_type = $instance['entity_type'];
80 81 82 83 84 85 86

    // EntityFieldQuery currently fails on conditions on comment bundle.
    // Remove when http://drupal.org/node/731724 is fixed.
    if ($entity_type == 'comment') {
      continue;
    }

87 88 89 90
    $ids = (object) array(
      'entity_type' => $entity_type,
      'bundle' => $instance['bundle'],
    );
91
    // field_purge_data() will need the field array.
92
    $field = $instance->getField();
93
    // Retrieve some entities.
94
    $query = $factory->get($entity_type)
95
      ->condition('id:' . $field['uuid'] . '.deleted', 1)
96 97 98 99 100 101
      ->range(0, $batch_size);
    // If there's no bundle key, all results will have the same bundle.
    if (!empty($info[$entity_type]['entity_keys']['bundle'])) {
      $query->condition($info[$entity_type]['entity_keys']['bundle'], $ids->bundle);
    }
    $results = $query->execute();
102
    if ($results) {
103 104 105
      foreach ($results as $revision_id => $entity_id) {
        $ids->revision_id = $revision_id;
        $ids->entity_id = $entity_id;
106 107
        $entity = _field_create_entity_from_ids($ids);
        Drupal::entityManager()->getStorageController($entity_type)->onFieldItemsPurge($entity, $instance);
108 109 110 111 112 113 114 115
      }
    }
    else {
      // No field data remains for the instance, so we can remove it.
      field_purge_instance($instance);
    }
  }

116
  // Retrieve all deleted fields. Any that have no instances can be purged.
117 118 119 120
  $deleted_fields = Drupal::state()->get('field.field.deleted') ?: array();
  foreach ($deleted_fields as $field) {
    $field = new Field($field);
    $instances = field_read_instances(array('field_id' => $field['uuid']), array('include_deleted' => 1));
121
    if (empty($instances)) {
122 123 124 125 126 127
      field_purge_field($field);
    }
  }
}

/**
128
 * Purges a field instance record from the database.
129
 *
130
 * This function assumes all data for the instance has already been purged and
131 132 133 134 135 136
 * should only be called by field_purge_batch().
 *
 * @param $instance
 *   The instance record to purge.
 */
function field_purge_instance($instance) {
137 138 139 140 141
  $state = Drupal::state();
  $deleted_instances = $state->get('field.instance.deleted');
  unset($deleted_instances[$instance['uuid']]);
  $state->set('field.instance.deleted', $deleted_instances);

142
  // Clear the cache.
143
  field_info_cache_clear();
144 145

  // Invoke external hooks after the cache is cleared for API consistency.
146
  Drupal::moduleHandler()->invokeAll('field_purge_instance', array($instance));
147 148 149
}

/**
150
 * Purges a field record from the database.
151 152 153 154 155 156 157 158
 *
 * This function assumes all instances for the field has already been purged,
 * and should only be called by field_purge_batch().
 *
 * @param $field
 *   The field record to purge.
 */
function field_purge_field($field) {
159
  $instances = field_read_instances(array('field_id' => $field['uuid']), array('include_deleted' => 1));
160
  if (count($instances) > 0) {
161
    throw new FieldException(t('Attempt to purge a field @field_name that still has instances.', array('@field_name' => $field['field_name'])));
162 163
  }

164 165 166 167
  $state = Drupal::state();
  $deleted_fields = $state->get('field.field.deleted');
  unset($deleted_fields[$field['uuid']]);
  $state->set('field.field.deleted', $deleted_fields);
168

169 170
  // Notify the storage layer.
  Drupal::entityManager()->getStorageController($field->entity_type)->onFieldPurge($field);
171 172

  // Clear the cache.
173
  field_info_cache_clear();
174 175

  // Invoke external hooks after the cache is cleared for API consistency.
176
  Drupal::moduleHandler()->invokeAll('field_purge_field', array($field));
177 178 179 180 181
}

/**
 * @} End of "defgroup field_purge".
 */