[CDBI] Addition of store method

David Steinbrunner <[email protected]>
Newsgroups gmane.comp.lang.perl.modules.class-dbi
Message-ID <C1F9DEAF.B64E%[email protected]>
Hello all,

Mr. Schwern's recent warning/threat has put an end to my procrastination on
posting about feature request.

Toward the end of last year I found myself needing a method to insert or
update a record depending on if that record already existed.  I thought I
had seen such a method called store in other systems such as Class::DBI so I
searched around trying to find if someone had talked about this type of
thing for Class::DBI before.

I ended up finding that Adam Kennedy had the same need/want/wish.

http://cpanratings.perl.org/dist/Class-DBI

"Most other systems I've seen have some sort of ->store method which does
either ->insert or ->update depending on whether the object is new or not"

Adam's comment validated my own thoughts.  Most people will say to move to
Rose::Object::DBI or the like but I do not have that option.  For those
working in existing Class::DBI systems it would still be nice to have this
type of feature available.

I ended up putting the code to do this out side of Class::DBI but I imagine
that could be moved into the Class::DBI code.  He is what I'm thinking could
be used within Class::DBI, which happens to be a derivative of the code I'm
using now:

sub store {
    my $self = shift;
    my $recData = shift;

    my ($rec) = $self->retrieve( $recData->{$self->primary_column} );
    
    if ($rec) {
        foreach my $key ( keys %{$recData} ) {
            my $value = $recData->{$key};
            $rec->$key($value);
        }
        $rec->update;
        return 1;
    }
    else {
        $self->create($recData);
        return 0;
    }
}

Note the above has not been tested and likely does not address many issues
like multiple primary keys.

Any thoughts on the likely hood of this feature being considered for
addition?

Thanks,

--
David Steinbrunner
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.