Deleting nodes with drush

http://www.seamless3d.com/tut/build_av/delete_node.png

By creating a php file named ~/.drush/content.drush.inc containing

/**
 * @file
 */

/**
 * Implementation of hook_drush_command().
 */
function content_drush_command() {
  $items = array();

  $items['content-list'] = array(
    'description' => "List content by type.",
    'arguments' => array(
      'type' => 'Content type to list.',
    ),
    'examples' => array(
      'drush content-list' => 'List count by type.',
      'drush content-list page' => 'List all page nodes.',
    ),
    'aliases' => array('cl'),
    );
  
  $items['content-delete'] = array(
    'description' => "Delete content by type.",
    'arguments' => array(
      'type' => 'Content type to delete.',
    ),
    'examples' => array(
      'drush content-delete page' => 'Delete all page nodes.',
    ),
  );

  
  return $items;
}

/**
 * Implementation of hook_drush_help().
 */
function content_drush_help($section) {
  switch ($section) {
    case 'drush:content-list':
      return dt("A node list tool");
  }
}

function drush_content_list($type = '') {
  if (empty($type)) {
    _drush_content_list_types();
  }
  else {
    _drush_content_list_nodes($type);
  }
}

function drush_content_delete($type) {
  _drush_content_delete_nodes($type);
}

function _drush_content_list_types() {
  $sql = 'SELECT DISTINCT type, count(*) as "count" FROM {node} GROUP BY type';
  $result = db_query($sql);
  
  $table = array();
  while ($row = db_fetch_array($result)) {
    $table[] = (array) $row;
  }
  drush_print_table($table);
}

function _drush_content_list_nodes($type) {
  $sql = "SELECT nid, title FROM {node} WHERE type = '" . $type . "'";
  $result = db_query($sql);
  $table = array();
  while ($row = db_fetch_array($result)) {
    $table[] = $row;
  }
  drush_print_table($table);
}

function _drush_content_delete_nodes($type) {
  global $user;
  $user = user_load(array('uid' => 1));
  
  $sql = "SELECT nid, title FROM {node} WHERE type = '" . $type . "'";
  $result = db_query($sql);
  $deleted = 0;
  while ($row = db_fetch_object($result)) {
    drush_print('Deleting ('. ++$deleted . ') ' . $row->title);
    //node_delete($row->nid);
    _drush_content_delete($row->nid);
  }
  cache_clear_all();

  drush_print("Deleted $deleted nodes.");
  return $deleted;

}

function _drush_content_delete($nid) {
  $node = node_load($nid, NULL, TRUE);
  db_query('DELETE FROM {node} WHERE nid = %d', $nid);
  db_query('DELETE FROM {node_revisions} WHERE nid = %d', $nid);
  node_invoke($node, 'delete');
  node_invoke_nodeapi($node, 'delete');
  if (function_exists('search_wipe')) {
    search_wipe($node->nid, 'node');
  }
}

it is possible to delete nodes before deleting content types.

Refs:
- http://drupal.org/project/delete_all
- http://drupal.org/node/1005480