X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=lib%2FDBIx%2FClass%2FRow.pm;h=7d81682efec2446323672c2c6872b375d015b559;hb=fde05eb90a90e55dad8ebf270a0377d5ba4b5b77;hp=7a6f68e16d5228057f7e3bfbed49d345b5bd3dbf;hpb=a2531bf2e3a4b4f6a3abd69d79605be33593deed;p=dbsrgits%2FDBIx-Class.git diff --git a/lib/DBIx/Class/Row.pm b/lib/DBIx/Class/Row.pm index 7a6f68e..7d81682 100644 --- a/lib/DBIx/Class/Row.pm +++ b/lib/DBIx/Class/Row.pm @@ -4,9 +4,22 @@ use strict; use warnings; use base qw/DBIx::Class/; -use Carp::Clan qw/^DBIx::Class/; -use Scalar::Util (); -use Scope::Guard; + +use DBIx::Class::Exception; +use Scalar::Util 'blessed'; +use Try::Tiny; +use namespace::clean; + +### +### Internal method +### Do not use +### +BEGIN { + *MULTICREATE_DEBUG = + $ENV{DBIC_MULTICREATE_DEBUG} + ? sub () { 1 } + : sub () { 0 }; +} __PACKAGE__->mk_group_accessors('simple' => qw/_source_handle/); @@ -22,8 +35,13 @@ This class is responsible for defining and doing basic operations on rows derived from L objects. Row objects are returned from Ls using the -L, L, -L and L methods. +L, L, +L and L methods, +as well as invocations of 'single' ( +L, +L or +L) +relationship accessors of L objects. =head1 METHODS @@ -61,6 +79,23 @@ passed objects. For a more involved explanation, see L. +Please note that if a value is not passed to new, no value will be sent +in the SQL INSERT call, and the column will therefore assume whatever +default value was specified in your database. While DBIC will retrieve the +value of autoincrement columns, it will never make an explicit database +trip to retrieve default values assigned by the RDBMS. You can explicitly +request that all values be fetched back from the database by calling +L, or you can supply an explicit C to columns +with NULL as the default, and save yourself a SELECT. + + CAVEAT: + + The behavior described above will backfire if you use a foreign key column + with a database-defined default. If you call the relationship accessor on + an object that doesn't have a set value for the FK column, DBIC will throw + an exception, as it has no way of knowing the PK of the related object (if + there is one). + =cut ## It needs to store the new objects somewhere, and call insert on that list later when insert is called on this object. We may need an accessor for these so the user can retrieve them, if just doing ->new(). @@ -72,23 +107,43 @@ For a more involved explanation, see L. sub __new_related_find_or_new_helper { my ($self, $relname, $data) = @_; - if ($self->__their_pk_needs_us($relname, $data)) { - return $self->result_source - ->related_source($relname) - ->resultset - ->new_result($data); + + my $rsrc = $self->result_source; + + # create a mock-object so all new/set_column component overrides will run: + my $rel_rs = $rsrc->related_source($relname)->resultset; + my $new_rel_obj = $rel_rs->new_result($data); + my $proc_data = { $new_rel_obj->get_columns }; + + if ($self->__their_pk_needs_us($relname)) { + MULTICREATE_DEBUG and warn "MC $self constructing $relname via new_result"; + return $new_rel_obj; + } + elsif ($rsrc->_pk_depends_on($relname, $proc_data )) { + if (! keys %$proc_data) { + # there is nothing to search for - blind create + MULTICREATE_DEBUG and warn "MC $self constructing default-insert $relname"; + } + else { + MULTICREATE_DEBUG and warn "MC $self constructing $relname via find_or_new"; + # this is not *really* find or new, as we don't want to double-new the + # data (thus potentially double encoding or whatever) + my $exists = $rel_rs->find ($proc_data); + return $exists if $exists; + } + return $new_rel_obj; } - if ($self->result_source->pk_depends_on($relname, $data)) { - return $self->result_source - ->related_source($relname) - ->resultset - ->find_or_create($data); + else { + my $us = $rsrc->source_name; + $self->throw_exception ( + "Unable to determine relationship '$relname' direction from '$us', " + . "possibly due to a missing reverse-relationship on '$relname' to '$us'." + ); } - return $self->find_or_new_related($relname, $data); } sub __their_pk_needs_us { # this should maybe be in resultsource. - my ($self, $relname, $data) = @_; + my ($self, $relname) = @_; my $source = $self->result_source; my $reverse = $source->reverse_relationship_info($relname); my $rel_source = $source->related_source($relname); @@ -96,7 +151,7 @@ sub __their_pk_needs_us { # this should maybe be in resultsource. foreach my $key (keys %$reverse) { # if their primary key depends on us, then we have to # just create a result and we'll fill it out afterwards - return 1 if $rel_source->pk_depends_on($key, $us); + return 1 if $rel_source->_pk_depends_on($key, $us); } return 0; } @@ -119,55 +174,72 @@ sub new { $new->result_source($source); } + if (my $related = delete $attrs->{-cols_from_relations}) { + @{$new->{_ignore_at_insert}={}}{@$related} = (); + } + if ($attrs) { $new->throw_exception("attrs must be a hashref") unless ref($attrs) eq 'HASH'; - + my ($related,$inflated); - ## Pretend all the rels are actual objects, unset below if not, for insert() to fix - $new->{_rel_in_storage} = 1; foreach my $key (keys %$attrs) { if (ref $attrs->{$key}) { ## Can we extract this lot to use with update(_or .. ) ? - confess "Can't do multi-create without result source" unless $source; + $new->throw_exception("Can't do multi-create without result source") + unless $source; my $info = $source->relationship_info($key); - if ($info && $info->{attrs}{accessor} - && $info->{attrs}{accessor} eq 'single') - { + my $acc_type = $info->{attrs}{accessor} || ''; + if ($acc_type eq 'single') { my $rel_obj = delete $attrs->{$key}; - if(!Scalar::Util::blessed($rel_obj)) { + if(!blessed $rel_obj) { $rel_obj = $new->__new_related_find_or_new_helper($key, $rel_obj); } - $new->{_rel_in_storage} = 0 unless ($rel_obj->in_storage); + if ($rel_obj->in_storage) { + $new->{_rel_in_storage}{$key} = 1; + $new->set_from_related($key, $rel_obj); + } else { + MULTICREATE_DEBUG and warn "MC $new uninserted $key $rel_obj\n"; + } - $new->set_from_related($key, $rel_obj) if $rel_obj->in_storage; $related->{$key} = $rel_obj; next; - } elsif ($info && $info->{attrs}{accessor} - && $info->{attrs}{accessor} eq 'multi' - && ref $attrs->{$key} eq 'ARRAY') { + } + elsif ($acc_type eq 'multi' && ref $attrs->{$key} eq 'ARRAY' ) { my $others = delete $attrs->{$key}; - foreach my $rel_obj (@$others) { - if(!Scalar::Util::blessed($rel_obj)) { + my $total = @$others; + my @objects; + foreach my $idx (0 .. $#$others) { + my $rel_obj = $others->[$idx]; + if(!blessed $rel_obj) { $rel_obj = $new->__new_related_find_or_new_helper($key, $rel_obj); } - $new->{_rel_in_storage} = 0 unless ($rel_obj->in_storage); - $new->set_from_related($key, $rel_obj) if $rel_obj->in_storage; + if ($rel_obj->in_storage) { + $rel_obj->throw_exception ('A multi relationship can not be pre-existing when doing multicreate. Something went wrong'); + } else { + MULTICREATE_DEBUG and + warn "MC $new uninserted $key $rel_obj (${\($idx+1)} of $total)\n"; + } + push(@objects, $rel_obj); } - $related->{$key} = $others; + $related->{$key} = \@objects; next; - } elsif ($info && $info->{attrs}{accessor} - && $info->{attrs}{accessor} eq 'filter') - { + } + elsif ($acc_type eq 'filter') { ## 'filter' should disappear and get merged in with 'single' above! my $rel_obj = delete $attrs->{$key}; - if(!Scalar::Util::blessed($rel_obj)) { + if(!blessed $rel_obj) { $rel_obj = $new->__new_related_find_or_new_helper($key, $rel_obj); } - $new->{_rel_in_storage} = 0 unless ($rel_obj->in_storage); + if ($rel_obj->in_storage) { + $new->{_rel_in_storage}{$key} = 1; + } + else { + MULTICREATE_DEBUG and warn "MC $new uninserted $key $rel_obj"; + } $inflated->{$key} = $rel_obj; next; } elsif ($class->has_column($key) @@ -178,7 +250,7 @@ sub new { } $new->throw_exception("No such column $key on $class") unless $class->has_column($key); - $new->store_column($key => $attrs->{$key}); + $new->store_column($key => $attrs->{$key}); } $new->{_relationship_data} = $related if $related; @@ -226,91 +298,136 @@ sub insert { my $rollback_guard; # Check if we stored uninserted relobjs here in new() - my %related_stuff = (%{$self->{_relationship_data} || {}}, + my %related_stuff = (%{$self->{_relationship_data} || {}}, %{$self->{_inflated_column} || {}}); - if(!$self->{_rel_in_storage}) { + # insert what needs to be inserted before us + my %pre_insert; + for my $relname (keys %related_stuff) { + my $rel_obj = $related_stuff{$relname}; - # The guard will save us if we blow out of this scope via die - $rollback_guard = $source->storage->txn_scope_guard; + if (! $self->{_rel_in_storage}{$relname}) { + next unless (blessed $rel_obj && $rel_obj->isa('DBIx::Class::Row')); - ## Should all be in relationship_data, but we need to get rid of the - ## 'filter' reltype.. - ## These are the FK rels, need their IDs for the insert. + next unless $source->_pk_depends_on( + $relname, { $rel_obj->get_columns } + ); - my @pri = $self->primary_columns; + # The guard will save us if we blow out of this scope via die + $rollback_guard ||= $source->storage->txn_scope_guard; - REL: foreach my $relname (keys %related_stuff) { + MULTICREATE_DEBUG and warn "MC $self pre-reconstructing $relname $rel_obj\n"; - my $rel_obj = $related_stuff{$relname}; + my $them = { %{$rel_obj->{_relationship_data} || {} }, $rel_obj->get_columns }; + my $existing; - next REL unless (Scalar::Util::blessed($rel_obj) - && $rel_obj->isa('DBIx::Class::Row')); - - next REL unless $source->pk_depends_on( - $relname, { $rel_obj->get_columns } - ); + # if there are no keys - nothing to search for + if (keys %$them and $existing = $self->result_source + ->related_source($relname) + ->resultset + ->find($them) + ) { + %{$rel_obj} = %{$existing}; + } + else { + $rel_obj->insert; + } - $rel_obj->insert(); - $self->set_from_related($relname, $rel_obj); - delete $related_stuff{$relname}; + $self->{_rel_in_storage}{$relname} = 1; } + + $self->set_from_related($relname, $rel_obj); + delete $related_stuff{$relname}; } - my $updated_cols = $source->storage->insert($source, { $self->get_columns }); - $self->set_columns($updated_cols); + # start a transaction here if not started yet and there is more stuff + # to insert after us + if (keys %related_stuff) { + $rollback_guard ||= $source->storage->txn_scope_guard + } ## PK::Auto - my @auto_pri = grep { - !defined $self->get_column($_) || - ref($self->get_column($_)) eq 'SCALAR' - } $self->primary_columns; + my %auto_pri; + my $auto_idx = 0; + for ($self->primary_columns) { + if ( + not defined $self->get_column($_) + || + (ref($self->get_column($_)) eq 'SCALAR') + ) { + my $col_info = $source->column_info($_); + $auto_pri{$_} = $auto_idx++ unless $col_info->{auto_nextval}; # auto_nextval's are pre-fetched in the storage + } + } - if (@auto_pri) { - #$self->throw_exception( "More than one possible key found for auto-inc on ".ref $self ) - # if defined $too_many; + MULTICREATE_DEBUG and do { + no warnings 'uninitialized'; + warn "MC $self inserting (".join(', ', $self->get_columns).")\n"; + }; + my $updated_cols = $source->storage->insert( + $source, + { $self->get_columns }, + (keys %auto_pri) && $source->storage->_use_insert_returning + ? { returning => [ sort { $auto_pri{$a} <=> $auto_pri{$b} } keys %auto_pri ] } + : () + , + ); + + foreach my $col (keys %$updated_cols) { + $self->store_column($col, $updated_cols->{$col}); + delete $auto_pri{$col}; + } + if (keys %auto_pri) { + my @missing = sort { $auto_pri{$a} <=> $auto_pri{$b} } keys %auto_pri; + MULTICREATE_DEBUG and warn "MC $self fetching missing PKs ".join(', ', @missing )."\n"; my $storage = $self->result_source->storage; $self->throw_exception( "Missing primary key but Storage doesn't support last_insert_id" ) unless $storage->can('last_insert_id'); - my @ids = $storage->last_insert_id($self->result_source,@auto_pri); + my @ids = $storage->last_insert_id($self->result_source, @missing); $self->throw_exception( "Can't get last insert id" ) - unless (@ids == @auto_pri); - $self->store_column($auto_pri[$_] => $ids[$_]) for 0 .. $#ids; + unless (@ids == @missing); + $self->store_column($missing[$_] => $ids[$_]) for 0 .. $#missing; } $self->{_dirty_columns} = {}; $self->{related_resultsets} = {}; - if(!$self->{_rel_in_storage}) { - ## Now do the has_many rels, that need $selfs ID. - foreach my $relname (keys %related_stuff) { - my $rel_obj = $related_stuff{$relname}; - my @cands; - if (Scalar::Util::blessed($rel_obj) - && $rel_obj->isa('DBIx::Class::Row')) { - @cands = ($rel_obj); - } elsif (ref $rel_obj eq 'ARRAY') { - @cands = @$rel_obj; - } - if (@cands) { - my $reverse = $source->reverse_relationship_info($relname); - foreach my $obj (@cands) { - $obj->set_from_related($_, $self) for keys %$reverse; - my $them = { $obj->get_inflated_columns }; - if ($self->__their_pk_needs_us($relname, $them)) { - $obj = $self->find_or_create_related($relname, $them); - } else { - $obj->insert(); + foreach my $relname (keys %related_stuff) { + next unless $source->has_relationship ($relname); + + my @cands = ref $related_stuff{$relname} eq 'ARRAY' + ? @{$related_stuff{$relname}} + : $related_stuff{$relname} + ; + + if (@cands && blessed $cands[0] && $cands[0]->isa('DBIx::Class::Row') + ) { + my $reverse = $source->reverse_relationship_info($relname); + foreach my $obj (@cands) { + $obj->set_from_related($_, $self) for keys %$reverse; + if ($self->__their_pk_needs_us($relname)) { + if (exists $self->{_ignore_at_insert}{$relname}) { + MULTICREATE_DEBUG and warn "MC $self skipping post-insert on $relname"; + } + else { + MULTICREATE_DEBUG and warn "MC $self inserting $relname $obj"; + $obj->insert; } + } else { + MULTICREATE_DEBUG and warn "MC $self post-inserting $obj"; + $obj->insert(); } } } - $rollback_guard->commit; } $self->in_storage(1); - undef $self->{_orig_ident}; + delete $self->{_orig_ident}; + delete $self->{_orig_ident_failreason}; + delete $self->{_ignore_at_insert}; + $rollback_guard->commit if $rollback_guard; + return $self; } @@ -330,7 +447,7 @@ sub insert { Indicates whether the object exists as a row in the database or not. This is set to true when L, L or L -are used. +are used. Creating a row object using L, or calling L on one, sets it to false. @@ -340,7 +457,7 @@ L on one, sets it to false. sub in_storage { my ($self, $val) = @_; $self->{_in_storage} = $val if @_ > 1; - return $self->{_in_storage}; + return $self->{_in_storage} ? 1 : 0; } =head2 update @@ -359,9 +476,13 @@ Throws an exception if the row object is not yet in the database, according to L. This method issues an SQL UPDATE query to commit any changes to the -object to the database if required. +object to the database if required (see L). +It throws an exception if a proper WHERE clause uniquely identifying +the database row can not be constructed (see +L +for more details). -Also takes an optional hashref of C<< column_name => value> >> pairs +Also takes an optional hashref of C<< column_name => value >> pairs to update on the object first. Be aware that the hashref will be passed to C, which might edit it in place, so don't rely on it being the same after a call to C. If you @@ -369,7 +490,7 @@ need to preserve the hashref, it is sufficient to pass a shallow copy to C, e.g. ( { %{ $href } } ) If the values passed or any of the column values set on the object -contain scalar references, eg: +contain scalar references, e.g.: $row->last_modified(\'NOW()'); # OR @@ -395,18 +516,21 @@ this method. sub update { my ($self, $upd) = @_; - $self->throw_exception( "Not in database" ) unless $self->in_storage; - my $ident_cond = $self->ident_condition; - $self->throw_exception("Cannot safely update a row in a PK-less table") - if ! keys %$ident_cond; + + my $ident_cond = $self->{_orig_ident} || $self->ident_condition; $self->set_inflated_columns($upd) if $upd; my %to_update = $self->get_dirty_columns; return $self unless keys %to_update; + + $self->throw_exception( "Not in database" ) unless $self->in_storage; + + $self->throw_exception($self->{_orig_ident_failreason}) + if ! keys %$ident_cond; + my $rows = $self->result_source->storage->update( - $self->result_source, \%to_update, - $self->{_orig_ident} || $ident_cond - ); + $self->result_source, \%to_update, $ident_cond + ); if ($rows == 0) { $self->throw_exception( "Can't update ${self}: row not found" ); } elsif ($rows > 1) { @@ -414,7 +538,7 @@ sub update { } $self->{_dirty_columns} = {}; $self->{related_resultsets} = {}; - undef $self->{_orig_ident}; + delete $self->{_orig_ident}; return $self; } @@ -431,19 +555,31 @@ sub update { =back Throws an exception if the object is not in the database according to -L. Runs an SQL DELETE statement using the primary key -values to locate the row. +L. Also throws an exception if a proper WHERE clause +uniquely identifying the database row can not be constructed (see +L +for more details). The object is still perfectly usable, but L will -now return 0 and the object must reinserted using L -before it can be used to L the row again. +now return 0 and the object must be reinserted using L +before it can be used to L the row again. If you delete an object in a class with a C relationship, an attempt is made to delete all the related objects as well. To turn this behaviour off, pass C<< cascade_delete => 0 >> in the C<$attr> hashref of the relationship, see L. Any database-level cascade or restrict will take precedence over a -DBIx-Class-based cascading delete. +DBIx-Class-based cascading delete, since DBIx-Class B and only then attempts to delete any remaining related +rows. + +If you delete an object within a txn_do() (see L) +and the transaction subsequently fails, the row object will remain marked as +not being in storage. If you know for a fact that the object is still in +storage (i.e. by inspecting the cause of the transaction's failure), you can +use C<< $obj->in_storage(1) >> to restore consistency between the object and +the database. This would allow a subsequent C<< $obj->delete >> to work +as expected. See also L. @@ -453,17 +589,19 @@ sub delete { my $self = shift; if (ref $self) { $self->throw_exception( "Not in database" ) unless $self->in_storage; + my $ident_cond = $self->{_orig_ident} || $self->ident_condition; - $self->throw_exception("Cannot safely delete a row in a PK-less table") + $self->throw_exception($self->{_orig_ident_failreason}) if ! keys %$ident_cond; - foreach my $column (keys %$ident_cond) { - $self->throw_exception("Can't delete the object unless it has loaded the primary keys") - unless exists $self->{_column_data}{$column}; - } + $self->result_source->storage->delete( - $self->result_source, $ident_cond); + $self->result_source, $ident_cond + ); + + delete $self->{_orig_ident}; # no longer identifiable $self->in_storage(undef); - } else { + } + else { $self->throw_exception("Can't do class delete without a ResultSource instance") unless $self->can('result_source_instance'); my $attrs = @_ > 1 && ref $_[$#_] eq 'HASH' ? { %{pop(@_)} } : {}; @@ -494,6 +632,11 @@ been fetched from the database or set by an accessor. If an L has been set, it will be deflated and returned. +Note that if you used the C or the C