[英]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.