You are here

function field_weight_update_7101 in Field display weights (per node) 7.2

Add the vid field. Change the primary key.

File

./field_weight.install, line 49
Field weight module install file.

Code

function field_weight_update_7101() {
  $field_weight = drupal_get_schema_unprocessed('field_weight', 'field_weight');
  $vid_spec = $field_weight['fields']['vid'];
  $vid_spec['not null'] = FALSE;

  // Temporary to avoid error
  if (!db_field_exists('field_weight', 'vid')) {
    db_add_field('field_weight', 'vid', $vid_spec);
  }

  // Make the primary key complex. We do this before filling vid with
  // values because we'll get a duplicate key error otherwise.
  db_drop_primary_key('field_weight');
  db_add_primary_key('field_weight', array(
    'nid',
    'vid',
  ));

  // Populate vid with real default values.
  $existing_nids = db_query("select nid, type, field_weights from {field_weight}");
  foreach ($existing_nids as $row) {
    $vid = db_query("select vid from {node} where nid = :nid", array(
      ':nid' => $row->nid,
    ))
      ->fetchField();
    db_update('field_weight')
      ->condition('nid', $row->nid)
      ->fields(array(
      'vid' => $vid,
    ))
      ->execute();

    // And make copies of the row for all other revisions
    $other_revisions = db_query("select vid from {node_revision} where nid = :nid and vid != :vid", array(
      ':nid' => $row->nid,
      ':vid' => $vid,
    ));
    foreach ($other_revisions as $vid_row) {
      $row->vid = $vid_row->vid;
      db_insert('field_weight')
        ->fields((array) $row)
        ->execute();
    }
  }

  // Change vid to be not-not null.
  $vid_spec['not null'] = TRUE;
  db_change_field('field_weight', 'vid', 'vid', $vid_spec);
}