[DBIx-Class-Devel] Optimized update_or_create

fREW Schmidt frioux at gmail.com
Fri Jul 12 19:52:10 GMT 2013


Currently create_or_update uses exactly two queries; one to load the
row, another to update it if it is found or insert it if it is not
found.

For properly written DBD's (one would hope that is most, but I
wouldn't assume it :) this can be rewritten to just be a single
update, like this:

   sub update_or_create {
     my $self = shift;
     my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
     # begin handwaving (we need to correctly find the UC or PK)
     my $cond = ref $_[0] eq 'HASH' ? shift : {@_};

     # can't use unless because 0e0 is returned on error
     $self->create($cond) if $self->search($search)->update($cond) == 0;

     return
   }

This breaks backcompat in two serious ways: first it uses the
resultset update instead of the row update, and second it doesn't
return the created/updated row.

I'll probably make a helper that will do this, but I was wondering
what people though of for names?  Something like
update_or_insert since you don't get the object back?  I don't like
update_or_create_fast, but it kinda makes sense.

Ideas?

--
fREW Schmidt
http://blog.afoolishmanifesto.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
Url : http://lists.scsys.co.uk/pipermail/dbix-class-devel/attachments/20130712/f734d5e3/attachment.pgp


More information about the DBIx-Class-Devel mailing list