Skip to content

Commit

Permalink
Fix deadlocks on concurrent package items replacement
Browse files Browse the repository at this point in the history
- Resolve shipperhq#28 Deadlock for 2 simple insert queries on shipperhq_quote_package_items table
  • Loading branch information
sshymko committed Oct 12, 2017
1 parent 214dd5e commit 732f0e9
Showing 1 changed file with 21 additions and 50 deletions.
71 changes: 21 additions & 50 deletions src/Model/ResourceModel/Quote/Packages.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,6 @@

class Packages extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
/**
* @var \ShipperHQ\Shipper\Helper\LogAssist
*/
private $shipperLogger;

public function __construct(
\ShipperHQ\Shipper\Helper\LogAssist $shipperLogger,
\Magento\Framework\Model\ResourceModel\Db\Context $context
) {
$this->shipperLogger = $shipperLogger;
parent::__construct($context);
}


/**
* Define main table
*
Expand Down Expand Up @@ -120,44 +106,29 @@ protected function _afterSave(\Magento\Framework\Model\AbstractModel $object)
parent::_afterSave($object);

$connection = $this->getConnection();
$itemArray = [];

$success = false;
$retries = 3;

while(!$success && $retries > 0) {
try {
// now save the package items
$connection->beginTransaction();

$connection->delete($this->getTable('shipperhq_quote_package_items'), ['package_id = ?' => $object->getId()]);

foreach ((array)$object->getData('items') as $item) {
$itemArray[] = [
'package_id' => $object->getId(),
'sku' => $item->sku,
'weight_packed' => $item->weightPacked,
'qty_packed' => $item->qtyPacked
];
}

if (count($itemArray) > 0) {
$connection->insertMultiple($this->getTable('shipperhq_quote_package_items'), $itemArray);
}

$connection->commit();
$success = true;
} catch (\Exception $e) {
$retries--;

$this->shipperLogger->postWarning(
'Shipperhq_Shipper',
'ShipperHQ save quote package error. Retrying '.$retries.' more times',
$e->getMessage());
$itemsTable = $this->getTable('shipperhq_quote_package_items');
$packageId = $object->getId();

// Delete existing package items, if any
$select = $connection->select()
->from($itemsTable, 'COUNT(*)')
->where('package_id = ?', $packageId);
$itemCount = (int)$connection->fetchOne($select);
if ($itemCount) {
$connection->delete($itemsTable, ['package_id = ?' => $packageId]);
}

$connection->rollBack();
}
// Add new package items
$items = [];
foreach ((array)$object->getData('items') as $item) {
$items[] = [
'package_id' => $packageId,
'sku' => $item->sku,
'weight_packed' => $item->weightPacked,
'qty_packed' => $item->qtyPacked
];
}
$connection->insertMultiple($itemsTable, $items);

return $this;
}
Expand Down

0 comments on commit 732f0e9

Please sign in to comment.