[Dbix-class] find_or_create did it find or created?

tirveni yadav yadav.tirveni at gmail.com
Mon Aug 21 09:26:42 GMT 2017


On Mon, Aug 21, 2017 at 6:15 AM, Rajeev Prasad <rp.neuli at yahoo.com> wrote:
> hi Triveni ji,
> I have not encountered the 'race cond.' yet in various scripts. (but) if you
> explain to me how to break find and replace into a transaction. I would
> consider that. I am not very good at DBIx, i just happen to use it.
> Thank you.
> Rajeev
>
>
> On Sunday, August 20, 2017 6:08 AM, tirveni yadav <yadav.tirveni at gmail.com>
> wrote:
>
>
> On Sat, Aug 19, 2017 at 12:07 AM, Thomas Sibley <trsibley at uw.edu> wrote:
>
>> Use find_or_new instead, and then check $id->in_storage.  Make sure to
>> call
>> $id->insert when $id->in_storage is false.
>>
>> This is explained in the documentation for find_or_create, starting with
>> “If
>> you need to know if an existing row was found or a new one created…”.
>>
>>
>> On Aug 18, 2017, at 10:34 , Rajeev Prasad <rp.neuli at yahoo.com> wrote:
>>
>> How do we know wether this function 'found' or created whatever was being
>> asked to 'find_or_create' ???
>>
>> my $id = $schema
>>        ->resultset('Node')
>>        ->find_or_create
>>        (
>>            { nodeName => $node },
>>            { key => 'nodeID' }
>>        );
>> how do we know wether $id was already existing in table?
>
>
>
> I would suggest that you avoid find_or_create, unless you know what
> are you are doing.
> find_or_create is subject to Race condition as well.
>
> Hence, best to do it inside a transaction.
>
> Or keep it simple and do a find and then create inside a transaction.
>

One way to do it:

    my $rs_fruit = $dbic->resultset('Fruit');
    my ($h_search,$h_new,$row_fruit);

    $h_search    = {
         fruitid => 'mango',
        };
    $h_new    = {
           fruitid => 'mango',
           name       => 'Mango',
           binomial => 'Mangifera indica',
          };

    $row_fruit = $rs_fruit->find($h_search);

    if (!defined($row_fruit))
    {
      $dbic->txn_do
               (sub
                  {
                         $row_fruit = $rs_fruit->create($h_new);
                      }
                   );
    }



-- 
Regards,

Tirveni Yadav

www.bael.io

What is this Universe ? From what it arises ? Into what does it go?
In freedom it arises, In freedom it rests and into freedom it melts away.
Upanishads.



More information about the DBIx-Class mailing list