[CDBI] Addition of store method

David Steinbrunner dsteinbrunner at pobox.com
Thu Feb 15 14:55:59 GMT 2007


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





More information about the ClassDBI mailing list