As part of a system data migration to Drupal 7, we have been using the Redirect module to handle redirects from old urls to the new.
This works fine, but as part of our fine tuning of the import process we clean out some of the content and then reimport. A node_delete does not remove the redirect so later when the redirect is added, the system returns a PDO Exception.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ‘bqE28udxgWSfKTpH2U8SDvptZ7T_dRP6dEpCPPDGJuU’ for key ‘hash’

Unfortunately there is no documentation for the redirect module, but after looking through the code, I was able to come up with a modification to the import script that deletes out the relevant redirects.

Below is a generic version of the relevant code. It does depend on knowing either the old or new url. In this from alias we know the new.

$deletedCount = 0;
$nodeTypes = array('type1', 'type2');

$nodeList = "'" . implode("','", $nodeTypes) . "'";
//fetch the nodes we want to delete
$query = "SELECT nid, type FROM {node} WHERE type IN($nodeList)";

$result = db_query($query);
foreach ($result as $row) {
	// Need to delete any redirects attached to a node otherwise duplicate key issues when try and save later
	$node = node_load($row->nid);
	// We need either redirect from or to for delete. We can get the to based on alias.
	$alias = drupal_lookup_path('alias', 'node/' . $node->nid);
	if ($alias) {
	// Now we can delete the actual content
	$deletedCount += 1;