php - Duplicate rows using multiple Doctrine instances -


i have following piece of code import posts database. checks if post exists. if not case, create new one.

this script running in cron job. however, has ran manually well. can happen 2 instances of script running simultaniously. when happens, duplicate records made. cannot see why possible.

foreach ($posts $post) {     $entity = new post();     $entity         ->setname($post->name)         ->setgender($post->gender())         ->setdate(new \datetime())     ;      $em = $this->getcontainer()->get('doctrine')->getmanager();     $checkentity = $em->getrepository('samplebundle:post')->findoneby(array(         'name' => $post->name     ));      if (!$checkentity) {         $em = $this->getcontainer()->get('doctrine')->getmanager();         $em->persist($entity);         $em->flush();     } } 

could shed little light on issue?

1) simplest solution prevents same command runs simultaneously. use https://github.com/ffreitas-br/command-lock-bundle

2) can catch exception in foreach:

$em->persist($entity);  try {     $em->flush(); } catch(uniqueconstraintviolationexception $e) {     // detach object prevent exception same entity on next flush() call.     $em->detach($entity); } 

if need save 1 entity instance:

$em->persist($entity);  try {     $em->flush($entity); } catch(uniqueconstraintviolationexception $e) {     // nothing. } 

3) if want performance benefits of running 2 commands parallel think message queue. https://github.com/videlalvaro/rabbitmqbundle

producer:

foreach ($users $user) {      $producer->produce(new message($user['name'])); } 

consumer:

$name = $message->getname();  $entity = new post(); $entity     ->setname($name) ;  $em = $this->getcontainer()->get('doctrine')->getmanager(); $em->persist($entity); $em->flush(); 

Comments

Popular posts from this blog

Load Balancing in Bluemix using custom domain and DNS SRV records -

oracle - pls-00402 alias required in select list of cursor to avoid duplicate column names -

python - Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] error -