How to avoid race conditions when using the find_or_create DBIx :: Class :: ResultSet method?

From the documentation for find_or_create:

Note. Since find_or_create () reads from the database and then possibly inserts based on the result, this method is subject to race status. Another process may create an entry in the table after the search has completed and before the creation begins. To avoid this problem, use find_or_create () inside the transaction.

Is it simple enough to use find_or_create()inside a transaction in PostgreSQL?

+5
source share
2 answers

, . . , , , - .

, - , . - :

BEGIN;
LOCK TABLE mytbl IN SHARE MODE;

-- do your find_or_create here

COMMIT;

. , ( , ). PostgreSQL , . .

PostgreSQL .

concurrency, . , . , , .

+6

find_or_create , OP:

eval {
    $row = $self->model->create( { ... } );
}
if($@ && $@ =~ /duplicate/i) {
   $row = $self->model->find( { ... } );
} 

find_or_create() .

0

All Articles