Grails GORM and MYSQL cascade delete problem - mysql

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.

Related

Issue with multiple cascade paths

I have designed an diagram in sql server 2008.
as you can see in the photo:
Now in Value table I set the cascading delete ON for Feature and ProductDetail but I see the error below:
'Feature' table saved successfully 'ProductDetail' table saved
successfully 'Value' table
- Unable to create relationship 'ValueFeature'. Introducing FOREIGN KEY constraint 'ValueFeature' on table 'Value' may cause cycles or
multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO
ACTION, or modify other FOREIGN KEY constraints. Could not create
constraint. See previous errors.
What is it wrong with my design?
I think I have faced the same problem some years ago, in SQL server 2005. I suppose that nothing is wrong with your design. If you delete a Feature you want all the Value records to be deleted. Nothing wrong with that. If you don't have other cascades, the automatic delete will not propagate further. However, it seems that SQL Server is not clever enough to understand that, and does not allow you to have such a relationship, just because you have foreign keys that form a circle. I think that if you remove a foreign key (just for testing) and break the circle (for example delete the FK between the ProductDetail and Product) there would be no error.
Check this stackoverflow question too..
Hope I helped!

Laravel4 Entrust - Installation issue with foreign key constraint

I am installing the laravel 4 package Entrust.
I create the migration file.
When i try to run the migration i get an error regarding the foreign key constraint.
Is this an issue pretty regarding some PhpMyAdmin settings?
I copy under the error directly from powershell:
PS C:\wamp\www\lab\x_pat> php artisan entrust:migration
Tables: roles, assigned_roles, permissions, permission_role
An migration that creates 'roles', 'assigned_roles', 'permissions', 'permission_role' tables will be created in app/data
base/migrations directory
Proceed with the migration creation? [Yes|no]yes
Creating migration...
Migration successfully created!
PS C:\wamp\www\lab\x_pat> php artisan migrate
Migration table created successfully.
[Exception]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table assigned_roles add const
raint assigned_roles_user_id_foreign foreign key (user_id) references users (id)) (Bindings: array (
))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
migrate [--bench[="..."]] [--database[="..."]] [--path[="..."]] [--package[="..."]] [--pretend] [--seed]
Foreign key constraints are not enforced by phpMyAdmin (which is a web interface) but by the MySQL server.
There are many possibilities for this error; it might be because the tables' structure do not permit it (missing indexes for example), or because of the existing data itself that does not respect the constraint you want to add.
The error is due to the missing reference on adding the foreign key (user_id) references users (id). Please ensure that the user table is exist prior to running the entrust migration.
I had to ensure my users table had its 'id' column attribute set to 'unsigned'. This matches the user_id column attribute in the entrust assigned_roles table. That allowed the migration to proceed for me.
SOLVED:
In PhpMyAdmin in had just to go in the table that contains the foreign key and press on INDEX button. In this way an index is created on that foreign key and then in RELATION VIEW is possible to assign the foreign key to the proper id of the proper table.
I think was just that the solution.
The root problem is in the file EntrustSetupTables in the migration folder, in this lines :
$table->foreign('user_id')->references('id')->on('')
->onUpdate('cascade')->onDelete('cascade');
Just put the name of the table users after the .on() and the problem will be solved.

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

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.