How can I create comment on node insert? I try to create comment on node insert using insert() hook but it collides with INSERT INTO {comment_entity_statistics} sql.

Integrity constraint violation: 1062 Duplicate entry '53-node-field_support' for key 'PRIMARY': INSERT INTO {comment_entity_statistics}


The code:

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function notifications_node_insert(Drupal\Core\Entity\EntityInterface $entity)
{
    $timestamp = mt_rand($entity-&gt;getCreatedTime(), REQUEST_TIME);
    $stub = array(
        'entity_type' =&gt; $entity-&gt;getEntityTypeId(),
        'entity_id' =&gt; $entity-&gt;id(),
        'field_name' =&gt; 'field_support',
        'name' =&gt; 'devel generate',
        'mail' =&gt; 'devel_generate@example.com',
        'timestamp' =&gt; $timestamp,
        'subject' =&gt; $_POST['field_support_message'],
        'uid' =&gt; \Drupal::currentUser()-&gt;id(),
        'langcode' =&gt; $entity-&gt;language()-&gt;getId(),
    );
    $comment = \Drupal\comment\Entity\Comment::create($stub);
    $comment-&gt;save();
}
I guess you're hitting some edge case in \Drupal\comment\CommentStatistics::create(), which is called in comment_entity_insert(). The code assumes that there is no comment yet when that is called. Which is an assumption that you are breaking, probably because your module gets called first.

That's arguably a core bug, you could open a bug report and try to fix it there to do a merge query. That said, as a workaround, make sure that your hook is called later than comment. You will have to implement hook_entity_insert() instead of node as that is apparently called later (by default, hooks are stored by modules by weight, name, so C should be before N).

PS: You should enable verbose error logging and check the full backtrace of that error. That can often help with understanding what's going on.