![](/img/trans.png)
[英]How to avoid race conditions when using the find_or_create method of DBIx::Class::ResultSet?
[英]How to identify whether record was found or created: class::dbi find_or_create
我仍在学习Perl和CLASS :: DBI。 我有一个执行大量查找的脚本,我只想插入通过查找找到的新项目。 我为用户名created_at创建了一个组合键,并且正在使用以下代码将其插入表中。
一切正常,但是我想知道是找到记录还是创建记录。 我怀疑有一个简单的方法可以执行此操作,但是显然我不知道要搜索的正确术语。
请帮忙。
谢谢!
eval {
FEED::COLLECTION->find_or_create({
username => $user->{username},
created_at => $status->{created_at},
status => $status->{text}
});
};
if ($@) {
warn $@;
}
Class::DBI
不记得实例化对象的方式,我想知道这一点表明一个人提出了错误的问题,需要重新说明一个人试图解决的问题。
但是,如果您确实需要知道,请不要使用find_or_create
。 它没有做任何特别聪明的事情。 这只是一个方便的例程。 因此,重新实现它并注释已找到的对象:
sub my_find_or_create {
my $class = shift;
my $hash = ref $_[0] eq "HASH" ? shift: {@_};
my ($exists) = $class->search($hash);
if (defined $exists) {
$exists->{_I_found_this_in_the_back} = 1; # or whatever means of noting preexistence you favor
return $exists;
} else {
return $class->insert($hash);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.