Magento - Integrity constraint viloation: 1452, shopping cart rules - mysql

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.

Related

Foreign Key "breaks" after a while

After several days of application running successfully I suddenly see errors:
Cannot add or update a child row: a foreign key constraint fails
If I run the SQL outside the context of the application sure enough it fails.
The data looks good and the constraints worked previously. Further, if I drop the constraints and add them back as they were everything works again.
I have to go through and drop/add the constraints until everything works again.
Any ideas of what I may be doing wrong here or quick way to recreate all FK's quickly?
Example FK Contraints:
CONSTRAINT `FKC92ACD965FF39405` FOREIGN KEY (`foodItem_id`) REFERENCES `FoodItem` (`id`),
CONSTRAINT `FKC92ACD966C592425` FOREIGN KEY (`meal_id`) REFERENCES `Meal` (`id`)
Example SQL:
into MealItem
(foodItem_id, meal_id, quantity)
values(150, 277, 0.375)
Thanks,
Bruce
I have never heard of a case where InnoDB foreign keys work intermittently and need to be dropped and recreated. And I don't recommend you adopt a habit of running unnecessary ALTER TABLE statements.
The more likely explanation is that you first tried to insert a row to MealItem before the referenced rows in either FoodItem or Meal have been inserted.
You can find more information on the exact foreign key constraint that was violated, by running:
mysql> pager less
mysql> SHOW ENGINE INNODB STATUS;
Look for the subsection something like the following:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
...some information about the transaction and thread context...
insert into MealItem (foodItem_id, meal_id, quantity) values(150, 277, 0.375)
Foreign key constraint fails for table `mydatabase/MealTime`:
CONSTRAINT `FKC92ACD965FF39405` FOREIGN KEY (`foodItem_id`) REFERENCES `FoodItem` (`id`),
Trying to add in child table, in index `foodItem_id` tuple:
DATA TUPLE: 2 fields; ...some binary description of the row you tried to insert... 
But in parent table `mydatabase/FoodItem`, in index `PRIMARY`,the closest match we can find is record:
...some binary description of MySQL's guess at a row near the one that's missing...
I've mocked up this example, and omitted some of the less useful stuff. This diagnostic information is relatively easy to read (compared to some). From this you can discover exactly which constraint had a conflict, and which parent table is missing the needed row.
Re your comment:
You wouldn't happen to be using OS X and MySQL between 5.5.8 and 5.5.12? I found the error you mention in reference to a bug that appeared in a specific version of MySQL, and only on OS X. Details here: http://bugs.mysql.com/bug.php?id=60309
The bug should be fixed if you upgrade to at least 5.5.13, or preferably upgrade to the latest
(5.5.32 as of June 2013).

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.

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

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;
}

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.

SQLSTATE[23000] while adding 3 entities to Doctrine 2 and Symfony 2

I created 3 doctrine entities:
Inquiry (has many Questions),
Question (has many Answers),
Answer.
Everything works well until I try to add ANY "answer", then I get a PDOException:
[PDOException]
SQLSTATE[23000]:
Integrity constraint violation:
1452 Cannot add or update a child row:
a foreign key constraint fails
(`ankieter`.`answer`, CONSTRAINT `FK_DD714F131E27F6BF` FOREIGN KEY (`question_id`) REFERENCES `Question` (`id`))
Fixture code for testing
The error I get
EDIT:
When I export my DB structure with PhpMyAdmin, delete information about foreign keys and import the structure back, everything works well (I am able to add data to "Answer" table).
What could be wrong with the foreign keys?
I think you should try calling flush() each question creation.
Try adding cascade={"persist"} to your answers-definition in Question Entity
#ORM\OneToMany(targetEntity="Answer", mappedBy="question", cascade={"persist"})
as well as to your question-definition in Answer Entity
#ORM\ManyToOne(targetEntity="Question", inversedBy="answers", cascade={"persist"})
Now doctrine should be able to persist all entries in the correct order.