Creating entity in Rules causes PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry My application based on CRM-Core.
I am using several rules which launch on the event "After saving a new crm core contact" and each has a crm_core_activity entity created as the rule's action.

Is it possible that the rules happen simultaneously which causes SQL error - trying to set same activity_id (which is primary key)?

Here is the error:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '879' for key 'PRIMARY': INSERT INTO {crm_core_activity} (activity_id, revision_id, uid, type, title, created, changed, uuid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7); Array ( [:db_insert_placeholder_0] =&gt; 879 [:db_insert_placeholder_1] =&gt; 1552 [:db_insert_placeholder_2] =&gt; 0 [:db_insert_placeholder_3] =&gt; email [:db_insert_placeholder_4] =&gt; תודה שפנית אלינו! [:db_insert_placeholder_5] =&gt; 1465830228 [:db_insert_placeholder_6] =&gt; 1465830228 [:db_insert_placeholder_7] =&gt; 4e87b796-fc8d-49f4-85f4-9ac944563576 ) in drupal_write_record() (line 7316 of /home/roi/sites/staging/0108-ormil/drupal-7.38/includes/common.inc).


The error happens randomly which makes me think this is a timing issue between multiple rules on the same trigger.
Have a look at issue # 430274, which explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module  works ...).

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg after only a few secs or mins later on ... if your cron job runs frequent enough, if not it'll be next time cron runs). This compromise will ensure that at the time the Rules Component is executed, the entity is for sure saved ... (so that can't be the reason anymore then why things don't work as expected ...).

Note: it's tough (virtually impossible) to pinpoint what exactly is causing your issue without knowing what exactly those rules look like. Adding a copy of your exported rules to the question may possibly help, but still. However, I'd recommend you to do some Rules debugging, using any of the techniques I described in my answer to How can I display the value of a variable inside a condition?