Magento - Order saving error: SQLSTATE[23000]: Integrity constraint violation - mysql

Sometimes, when we place an order in the backend - with a NEW customer, we get the following error upon submitting it:
Order saving error: SQLSTATE[23000]: Integrity constraint violation: 1452
Cannot add or update a child row: a foreign key constraint fails
`artizara_artizara/enterprise_reward`, CONSTRAINT `FK_REWARD_CUSTOMER_ID`
FOREIGN KEY (`customer_id`) REFERENCES customer_entity` (`entity_id`)
ON DELETE CASCADE ON UPDATE CASCADE)
I've looked up the error log and it says the following:
exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint
violation: 1452 Cannot add or update a child row: a foreign key constraint fails
(`artizara_artizara/enterprise_reward`, CONSTRAINT `FK_REWARD_CUSTOMER_ID`
FOREIGN KEY (`customer_id`) REFERENCES `customer_entity` (`entity_id`) ON DELETE
CASCADE ON UPDATE CASCADE)' in /chroot/home/artizara/artizara.com/html/lib/Zend/Db/Statement/Pdo.php:228
I've researched this in google/Magento forums and some people say it has to do with the table not being InnobDB...
So I went into phpMyAdmin and pulled up the enterprise_reward table. Opened the Operations tab. Next to Storage Engine it says InnoDB so I think I'm set there...
Other people tried making sql statements for their issue by searching for orphan data. I'm not quite sure what this is looking for exactly so I don't know how to put the sql statement together (I'm a bit newer at that anyway).
Will someone please help figure this out (making by searching for the orphan data, etc) and perhaps let me know why this has happened in the first place?
FYI - they can't give me a clear picture as to whether this happens with EVERY new customer (when placing an order in the admin) or just sometimes - so I don't have that info (yet)...
Edit 5/16 # 2:30p:
I've tried looking for orphans with this sql code but no results returned...
SELECT
*
FROM
enterprise_reward
LEFT
JOIN
customer_entity
ON enterprise_reward.customer_id = customer_entity.entity_id
WHERE
customer_entity.entity_id IS NULL

We are indeed experiencing this same issue on enterprise 1.10.0.1. This appears to be a known bug that has been filed with Varien. However - I have not found a solution.
Best thing I could find is this thread: http://www.magentocommerce.com/boards/v/viewthread/234872
The bug report I found is posted below.
BUG ID: 26516
Posted: 2011-09-21 15:22:18
When payment processing fails with an exception, the following error occurs in certain situations:
Zend_Db_Statement_Exception: SQLSTATE[23000]: Integrity constraint
violation: 1452 Cannot add or update a child row: a foreign key
constraint fails (magento_enterprise.enterprise_reward, CONSTRAINT
FK_REWARD_CUSTOMER_ID FOREIGN KEY (customer_id) REFERENCES
customer_entity (entity_id) ON DELETE CASCADE ON UPDATE CASCADE)
./lib/Zend/Db/Statement/Pdo.php:234
./lib/Zend/Db/Statement.php:300
./lib/Zend/Db/Adapter/Abstract.php:479
./lib/Zend/Db/Adapter/Pdo/Abstract.php:238
./lib/Varien/Db/Adapter/Pdo/Mysql.php:333
./lib/Zend/Db/Adapter/Abstract.php:574
./app/code/core/Mage/Core/Model/Mysql4/Abstract.php:414
./app/code/core/Mage/Core/Model/Abstract.php:318
./app/code/core/Enterprise/Reward/Model/Reward.php:202
./app/code/core/Enterprise/Reward/Model/Observer.php:548
./app/code/core/Enterprise/Reward/Model/Observer.php:564
./app/code/core/Mage/Core/Model/App.php:1265
./app/code/core/Mage/Core/Model/App.php:1246
./app/Mage.php:416
./app/code/core/Mage/Sales/Model/Service/Quote.php:187
./app/code/core/Mage/Sales/Model/Service/Quote.php:126
./EnterpriseRewardTest.php:70
Steps to reproduce:
use Magento Enterprise with Enterprise Rewards enabled (or another
module with a similar code, see below)
use a payment module that supports on-line authorization
check out an order as a new customer
trigger a payment error (e.g. by entering an invalid CC no).
I attached a PHPUnit test case that should reproduce the problem reliably.
The culprit is the code in Mage_Sales_Model_Service_Quote::submitOrder that does the following:
start a transaction
build a new order
create a new customer and fill in the order's customerId field
attempt to process the order, which raises an exception
roll back the transaction
dispatch "quote_submit_failure" event using the order as event data. Note that the order's customerId field now contains an invalid value since the transaction has been rolled back.
Now, if a handler for quote_submit_failure proceeds to use order's customerId, it will necessarily trigger the aforementioned "integrity constraint violation" error.
The problem can be reproduced on following versions:
- Magento Enterprise Edition v1.10.0.1
- Magento Community Edition v1.6.0.0 (provided there happens to be a quote_submit_failure handler that expect a valid customerId.

You can also add $this->_stmt->queryString to Zend_Db_Statement_Exception at lib/Zend/Db/Statement/Pdo.php (_execute method) to see what query is throwing the error.
It will be something like..
throw new Zend_Db_Statement_Exception($e->getMessage() . $this->_stmt->queryString, (int) $e->getCode(), $e);
But remember: do not commit core modifications in Magento. It's not cool.
Source: Aftab Naveed's Blog

If using 1.10.0.1 or less, patch this file app/code/core/Enterprise/Reward/Model/Observer.php by adding a check for customer id
protected function _revertRewardPointsForOrder(Mage_Sales_Model_Order $order)
{
// Patch for known 1.10.0.1 bug
if (!$order->getCustomer()->getId()) {
return $this;
}
// End patch
Mage::getModel('enterprise_reward/reward')
->setCustomerId($order->getCustomerId())
->setWebsiteId(Mage::app()->getStore($order->getStoreId())->getWebsiteId())
->setPointsDelta($order->getRewardPointsBalance())
->setAction(Enterprise_Reward_Model_Reward::REWARD_ACTION_REVERT)
->setActionEntity($order)
->updateRewardPoints();
return $this;
}

Related

Where does this IntegrityError comes from on the Django ORM on MySQL?

I have a Django 1.5 site running a MySQL DB on Cent OS, and one of the views that used to worked suddenly started to fail on this snippet :
ipdb> Video.objects.create(owner=usr, category=category, status="processing", title=request.POST.get('title'))
*** IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`project`.`videos_manager_video`, CONSTRAINT `category_id_refs_id_26102a51` FOREIGN KEY (`category_id`) REFERENCES `videos_manager_category (`id`))')
The code hasn't changed, the data base hasn't changed and we ran mysqlcheck (it said all tables were OK), but this still explodes.
Of course we checked category, which is a proper category object, with proper id. Doing this:
Category.objects.get(id=cated.id)
returns the same categ.
We purged the cache, juste in case, but still a no go.
What could cause this ? What would solve this ?

Magento - Integrity constraint viloation: 1452, shopping cart rules

When making a discount/shopping cart rule for a given category or SKU number, it's unable to save and this error is created:
'Zend_Db_Statement_Exception' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`shop1`.`salesrule_product_attribute`, CONSTRAINT `FK_SALESRULE_PRD_ATTR_CSTR_GROUP_ID_CSTR_GROUP_CSTR_GROUP_ID` FOREIGN KEY (`customer_group_id`) REFERENCES `customer_group` (`customer_group_i)' in /var/www/shop1/public_html/lib/Zend/Db/Statement/Pdo.php:234
I've been looking through my DB to find the problem, but without luck. I'm unsure where to start looking now, I found no obvious errors in the customer_group table, but I think it has something to do with a deleted store front, a while ago, maby messing up the customer id's?
Surely the most Obvious reason, was the last one that I checked! - The ´customer_group´ table was set to MyISAM instead of InnoDB, it must be InnoDB.

Mysql cannot add or update child row, Foreign key related failure

Error: cannot add or update a child row: foreign key constraint fails
Following is the code that is creating the error:
ALTER TABLE 'catalog_eav_attribute'
ADD CONSTRAINT 'FK_CATALOG_EAV_ATTRIBUTE_ID'
FOREIGN KEY ('attribute_id') REFERENCES 'eav_attribute' ('attribute_id)'
ON DELETE CASCADE ON UPDATE CASCADE;
I uploaded the Structure of SQL and its has no issue , but when i insert the data i am getting the above related error. I read somewhere and i predict its because of lousy data.What are the other possibilities for the error ? Any suggestions or solution will be great.
"For storage engines other than InnoDB, MySQL Server parses the FOREIGN KEY syntax in CREATE TABLE statements, but does not use or store it."
From: http://dev.mysql.com/doc/refman/5.5/en/ansi-diff-foreign-keys.html
I'm not sure, but if your table is MyISAM and not InnoDB, your syntax might not work.
The error message means whatever number you're trying to put into the attribute_id column doesn't yet exist in the eav_attribute.attribute_id column.
Can you insert a value that does already exist in eav_attribute.attribute_id? (You probably can.)
Can you provoke the same error by trying to insert a value that doesn't exist in eav_attribute.attribute_id?
Reconcile the differences, and you're done. You need to determine which attribute ids don't exist in eav_attribute.attribute_id, and fix that.

MySQL Foreign constraing inconsistencies

We're having weird errors on our production environment.
The error is:
MySQLIntegrityConstraintViolationException:
Cannot add or update a child row:
a foreign key constraint fails
('MSeHA_BARTLETT'.'document_version',
CONSTRAINT 'document_version_ibfk_1'
FOREIGN KEY ('document_id')
REFERENCES 'document' ('id')
ON DELETE CASCADE ON UPDATE CASCADE).
On SQL:
INSERT INTO 'document_version' SET
'document_id'='2002069',
'type_id'='2',
'subtype_id'='119091',
'status_id'='4',
'event_timestamp'='2012-02-08 15:02:00',
'provider_id'='1056'
ON DUPLICATE KEY UPDATE
'id'=LAST_INSERT_ID('id') ,
'type_id'='2',
'subtype_id'='119091',
'status_id'='4',
'provider_id'='1056'
With my knowledge of mysql and foreign keys, i had a few assumptions.
the table was locked. I used the cli to do this manually via locking/unlocking tables mid transaction, however it just waited patiently until the table was unlocked and finished...so no go.
so document_version is referencing document which has to be unique. Maybe 2 transactions at the same time try to insert the same document and mysql would give back different ids. Thsi would mean one would work fine, but the 2nd transaction would try to finish, but document would fail unique key constraints, making the document_id invalid? Thus failing the foreign key? Again, I re-enacted this via cli by starting 2 transactions, and letting them both insert the same row into document. Again mysql waited patiently on transaction #2 until the 1st transaction finished before letting it proceed and errored. Not the problem.
I'm at a loss. Any ideas are appreciated.

Grails GORM and MYSQL cascade delete problem

I have a table User that has many child tables defined in User class under the static hasMany
grails.
I have no problem when doing User.get(3).delete() in grails. It automatically delete that user and all its child table rows.
But when I want to perform the same operation in MySQL workbench. I get Error thrown by MySQL:
ERROR 1451: Cannot delete or update a parent row: a foreign key constraint fails (`test_db`.`search_stat`, CONSTRAINT `FK7A3CFFB6E64DB41` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`))
SQL Statement:
DELETE FROM `test_db`.`user` WHERE `id`='3'
I dont know what is the problem here with MySQL.
Where did you read about the "ON DELETE CASCADE" in the documentation? I haven't found it here. The poster of this post had to manually add this as well to get the desired behaviour.
If grails is really supposed to add this, have you tried deleting the DB and having it re-created by grails (at least in development environment)? Maybe the current schema was generated before you added the belongsTo or something?
Also check out this Blog post about GORM Gotchas regarding hasMany and belongsTo.