You are here

function nodehierarchy_update_7401 in Node Hierarchy 7.4

Move the Node Hierarchy storage over to the new db format.

File

./nodehierarchy.install, line 204
Install file for nodehierarchy module.

Code

function nodehierarchy_update_7401(&$sandbox) {
  $ret = array();
  if (!isset($sandbox['progress'])) {
    $sandbox['progress'] = 0;

    // Total nodes that must be visited.
    $query = db_select('nodehierarchy_menu_links', 'nhml');
    $query
      ->join('menu_links', 'ml', 'ml.mlid = nhml.mlid');
    $query
      ->join('menu_links', 'pl', 'ml.plid = pl.mlid');
    $query
      ->leftJoin('nodehierarchy', 'nh', 'nh.cnid = nhml.nid');
    $query
      ->addExpression('COUNT(ml.mlid)', 'num');
    $query
      ->where('nh.nhid IS NULL');
    $result = $query
      ->execute()
      ->fetchField();
    $sandbox['max'] = $result;
    $sandbox['messages'] = array();
  }
  $limit = 500;

  // Retrieve the next group of nids.
  $query = db_select('nodehierarchy_menu_links', 'nhml');
  $query
    ->join('menu_links', 'ml', 'ml.mlid = nhml.mlid');
  $query
    ->join('menu_links', 'pl', 'ml.plid = pl.mlid');
  $query
    ->leftJoin('nodehierarchy', 'nh', 'nh.cnid = nhml.nid');
  $query
    ->fields('nhml', array(
    'nid',
  ));
  $query
    ->addField('pl', 'link_path', 'parent_path');
  $query
    ->fields('ml');
  $query
    ->where('nh.nhid IS NULL');
  $query
    ->orderBy('ml.depth', 'DESC');
  $query
    ->range(0, $limit);
  $result = $query
    ->execute()
    ->fetchAll();
  foreach ($result as $row) {
    $object = array(
      'cnid' => $row->nid,
      'pnid' => str_replace('node/', '', $row->parent_path),
      'cweight' => $row->weight,
    );
    db_insert('nodehierarchy')
      ->fields($object)
      ->execute();

    // Delete hidden unneeded menu links.
    if ($row->hidden) {

      // Delete if there are no children. This only works because of the reverse sort on depth (meaning leaves are culled first).
      $has_children_query = db_select('menu_links', 'ml')
        ->condition('plid', $row->mlid);
      $has_children_query
        ->addExpression('count(*)');
      $has_children = $has_children_query
        ->execute()
        ->fetchField();
      if (!$has_children) {
        db_delete('menu_links')
          ->condition('mlid', $row->mlid)
          ->execute();
        db_delete('nodehierarchy_menu_links')
          ->condition('mlid', $row->mlid)
          ->execute();
      }
    }

    // Update our progress information.
    $sandbox['progress']++;
  }
  $sandbox['#finished'] = $sandbox['progress'] >= $sandbox['max'] ? TRUE : $sandbox['progress'] / $sandbox['max'];
  return t('Converted !num total Node Hierarchy records.', array(
    '!num' => $sandbox['progress'],
  ));
}