Duplicate entry on INSERT after DELETE from table

2019-08-30 19:31发布

问题:

I'm looking for any ideas to explain (and prevent) the following:

1) We have a Magento reindex process (price or stock) that is failing from time to time with:

exception 'Zend_Db_Statement_Exception' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '512723-1-1' for key 'PRIMARY'' in /[omitted]/lib/Zend/Db/Statement/Pdo.php:242

Full trace: https://gist.github.com/werdan/5255362

2) Magento reindex is done in transaction, which can be sketched as following:

START TRANSACTION;
DELETE FROM `cataloginventory_stock_status`;
INSERT INTO cataloginventory_stock_status SELECT * FROM cataloginventory_stock_status_idx;
COMMIT;

3) It should be impossible to break consistency of the table between DELETE and INSERT commands, nevertheless it happens.

We have checked that tables cataloginventory_stock_status and cataloginventory_stock_status_idx have identical keys and structure.

What else can be suggested as an explanation and solution?

回答1:

This is what many SQL dump tools do:

LOCK TABLES foo WRITE;
ALTER TABLE foo DISABLE KEYS;

INSERT INTO foo (foo_id, foo_name) VALUES (1, 'One'), 
    (2, 'Two'), 
    (3, 'Three');

ALTER TABLE foo ENABLE KEYS;
UNLOCK TABLES;