You are here

function drush_multifield_convert_field_collection_table in Multifield 7.2

Same name and namespace in other branches
  1. 7 multifield.drush.inc \drush_multifield_convert_field_collection_table()
1 string reference to 'drush_multifield_convert_field_collection_table'
drush_multifield_convert_field_collection in ./multifield.drush.inc

File

./multifield.drush.inc, line 128
Drush integration for the Multifield module.

Code

function drush_multifield_convert_field_collection_table($source_field, $target_field, $subfields, $type, &$context) {
  $source_table = $type == 'data' ? _field_sql_storage_tablename($source_field) : _field_sql_storage_revision_tablename($source_field);
  $target_table = $type == 'data' ? _field_sql_storage_tablename($target_field) : _field_sql_storage_revision_tablename($target_field);
  if (!isset($context['sandbox']['total'])) {
    $context['sandbox']['count'] = 0;
    $context['sandbox']['total'] = db_select($source_table)
      ->countQuery()
      ->execute()
      ->fetchField();
  }
  $query = db_select($source_table, 'old');
  $query
    ->fields('old');
  $query
    ->orderBy('entity_type');
  $query
    ->orderBy('revision_id');
  $query
    ->range($context['sandbox']['count'], 100);
  $records = $query
    ->execute()
    ->fetchAllAssoc($source_field['field_name'] . '_value', PDO::FETCH_ASSOC);

  //var_export($records);
  $context['sandbox']['count'] += count($records);
  foreach ($subfields as $subfield) {
    $columns = array();
    foreach (array_keys($target_field['columns']) as $column_name) {
      if (strpos($column_name, $subfield['field_name']) === 0) {
        $columns[] = $column_name;
      }
    }
    $subtable = $type == 'revision' ? _field_sql_storage_revision_tablename($subfield) : _field_sql_storage_tablename($subfield);
    $subquery = db_select($subtable, 'subfield');
    $subquery
      ->fields('subfield', array_merge($columns, array(
      'entity_id',
    )));
    $subquery
      ->condition('entity_type', 'field_collection_item');
    $subquery
      ->condition('bundle', $source_field['field_name']);
    $subquery
      ->condition('entity_id', array_keys($records), 'IN');
    $subrecords = $subquery
      ->execute()
      ->fetchAllAssoc('entity_id', PDO::FETCH_ASSOC);
    foreach ($subrecords as $id => $subrecord) {
      foreach ($columns as $column_name) {
        $records[$id][$target_field['field_name'] . '_' . $column_name] = $subrecord[$column_name];
      }
    }
  }
  foreach ($records as &$record) {
    $record[$target_field['field_name'] . '_id'] = multifield_get_next_id();
    $record['deleted'] = 0;
    drupal_write_record($target_table, $record);
    entity_get_controller($record['entity_type'])
      ->resetCache(array(
      $record['entity_id'],
    ));
  }
  multifield_update_maximum_id($records);
  $context['finished'] = empty($context['sandbox']['total']) ? 1 : $context['sandbox']['count'] / $context['sandbox']['total'];
}