diff -u b/modules/line_item/commerce_line_item.module b/modules/line_item/commerce_line_item.module --- b/modules/line_item/commerce_line_item.module +++ b/modules/line_item/commerce_line_item.module @@ -95,6 +95,27 @@ return $hooks; } +/** + * Implements hook_cron(). + */ +function commerce_line_item_cron() { + + // Cron operation to prune orphaned line items that were created + // but are no longer are associated with an order. + $query = 'SELECT line_item_id FROM {commerce_line_item} li + LEFT JOIN {field_data_commerce_line_items} fdcli + ON li.line_item_id = fdcli.commerce_line_items_line_item_id + WHERE fdcli.commerce_line_items_line_item_id IS NULL + AND li.created < :timestamp + ORDER BY li.order_id + LIMIT 100'; + + $line_item_ids = db_query($query, array(':timestamp' => strtotime('-1 day')))->fetchAllKeyed(0,0); + + if (!empty($line_item_ids)) { + commerce_line_item_delete_multiple($line_item_ids); + } +} /** * Implements hook_form_alter(). @@ -1600,20 +1621,24 @@ */ function commerce_line_item_commerce_order_update($order) { if (!empty($order->order_id)) { - $order_wrapper = entity_metadata_wrapper('commerce_order', $order); + $line_item_ids = array(); - try { + // Load line item ids of the order to make sure they're excluded. + if (!empty($order->commerce_line_items)) { + $order_wrapper = entity_metadata_wrapper('commerce_order', $order); $line_item_ids = (array) $order_wrapper->commerce_line_items->raw(); - } catch (Exception $ex) { - $ine_item_ids = array(); } + + // Query for line item ids that have a matching order id, but + // do not exist on the order. $orphaned_line_items = db_query('SELECT line_item_id FROM {commerce_line_item} WHERE order_id = :order_id AND line_item_id NOT IN(:line_item_ids)', array( ':order_id' => $order->order_id, ':line_item_ids' => $line_item_ids ))->fetchAllKeyed(0, 0); - foreach ((array) $orphaned_line_items as $orphaned_line_item) { - commerce_line_item_delete($orphaned_line_item); + // Bulk delete any line items that are orphaned. + if (!empty($orphaned_line_items)) { + commerce_line_item_delete_multiple($orphaned_line_items); } } }