简体   繁体   中英

How to identify whether record was found or created: class::dbi find_or_create

I'm still learning Perl and CLASS::DBI. I have a script that does a bunch of lookups and I only want to insert the new items that are found by the lookups. I created a composite key for username,created_at and I'm using the following code to insert that in to the table.

Everything works, but I would like to know whether the record was found or whether it created the record. I suspect there's an easy way to do this, but apparently I don't know the right terminology to search for.

Please help.

Thanks!

eval {
    FEED::COLLECTION->find_or_create({
        username => $user->{username},
        created_at => $status->{created_at},
        status => $status->{text}
    });
};
if ($@) {
    warn $@;
}

Class::DBI doesn't remember by what route the object was instantiated, and I think that wanting to know suggests that one is asking the wrong question and needs to rephrase the problem one is trying to solve.

If you really feel you need to know, though, don't use find_or_create . It doesn't do anything particularly clever; it's just a convenience routine. So reimplement it and annotate the object as having been found:

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM