[英]How to increment a column using DBIx::Class?
I'm trying to convert some raw DBI calls to DBIx::Class. 我正在尝试将一些原始DBI调用转换为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? 有没有办法让DBIx :: Class完全执行这种查询? 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.
基本上我只是想知道是否有一种干净的方式使用DBIC来执行此操作,或者我是否应该继续在此处继续使用原始DBI调用。
Use the solution from @ThisSuitIsBlackNot's comment but replace update_all
with update
: 使用@ ThisSuitIsBlackNot注释中的解决方案,但将
update_all
替换为update
:
$rs->search(...)->update({
bar => \'bar + 1',
});
This will result in a single UPDATE statement. 这将导致单个UPDATE语句。 (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.) (解释:
update_all
工作原理是在ResultSet中的每一行上调用update
,包括DBIC触发器之类的东西,因此它必须首先获取行.RatesSet上的update
执行准系统SQL UPDATE。)
Will using DBIx::Class::Storage::TxnScopeGuard help? 将使用DBIx :: Class :: Storage :: TxnScopeGuard帮助吗? You can wrap your block of code in a transaction like this
您可以将代码块包装在这样的事务中
my $guard = $schema->txn_scope_guard;
# your increment
$guard->commit;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.