Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a column using DBIx::Class?

I'm trying to convert some raw DBI calls to DBIx::Class. I occasionally run across something like:

UPDATE 'foo' SET bar = bar + 1 WHERE ...

Is there way to do have DBIx::Class execute exactly this kind of query? I don't want to do something like:

$row->update({ bar => $row->bar() + 1 });

because there's a race condition there if multiple processes are trying to do the same thing.

I could get around that with some kind of locking at the database level, but that seems worse to me than just using the original query. Basically I just want to know if there's a clean way of using DBIC to do this or if I should just continue to use raw DBI calls here.

like image 754
oalders Avatar asked Nov 07 '14 18:11

oalders


1 Answers

Use the solution from @ThisSuitIsBlackNot's comment but replace update_all with update:

$rs->search(...)->update({
    bar => \'bar + 1',
});

This will result in a single UPDATE statement. (Explanation: update_all works by calling update on every Row in the ResultSet including things like DBIC triggers, so it has to fetch the rows first. update on a ResultSet executes a barebones SQL UPDATE.)

like image 184
nwellnhof Avatar answered Sep 21 '22 18:09

nwellnhof