X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=lib%2FDBIx%2FClass%2FRow.pm;h=ba05001e5666c5b1693e046be011cc1da543e8ca;hb=0e80c4ca9995674bcc86bc59780b940ce20c48d2;hp=ceed5a6a3e58d702b6301a544e8a4ab33b9ec452;hpb=04786a4c19fe3964002b69e8a3dbb291524e0610;p=dbsrgits%2FDBIx-Class.git diff --git a/lib/DBIx/Class/Row.pm b/lib/DBIx/Class/Row.pm index ceed5a6..ba05001 100644 --- a/lib/DBIx/Class/Row.pm +++ b/lib/DBIx/Class/Row.pm @@ -5,10 +5,10 @@ use warnings; use base qw/DBIx::Class/; use Carp::Clan qw/^DBIx::Class/; +use Scalar::Util (); +use Scope::Guard; -__PACKAGE__->load_components(qw/AccessorGroup/); - -__PACKAGE__->mk_group_accessors('simple' => 'result_source'); +__PACKAGE__->mk_group_accessors('simple' => qw/_source_handle/); =head1 NAME @@ -21,31 +21,173 @@ DBIx::Class::Row - Basic row methods 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, +as well as invocations of 'single' ( +L, +L or +L) +relationship accessors of L objects. + =head1 METHODS =head2 new - my $obj = My::Class->new($attrs); + my $row = My::Class->new(\%attrs); + + my $row = $schema->resultset('MySource')->new(\%colsandvalues); + +=over + +=item Arguments: \%attrs or \%colsandvalues + +=item Returns: A Row object + +=back + +While you can create a new row object by calling C directly on +this class, you are better off calling it on a +L object. + +When calling it directly, you will not get a complete, usable row +object until you pass or set the C attribute, to a +L instance that is attached to a +L with a valid connection. -Creates a new row object from column => value mappings passed as a hash ref +C<$attrs> is a hashref of column name, value data. It can also contain +some other attributes such as the C. + +Passing an object, or an arrayref of objects as a value will call +L for you. When +passed a hashref or an arrayref of hashrefs as the value, these will +be turned into objects via new_related, and treated as if you had +passed objects. + +For a more involved explanation, see L. =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(). +## This only works because DBIC doesnt yet care to check whether the new_related objects have been passed all their mandatory columns +## When doing the later insert, we need to make sure the PKs are set. +## using _relationship_data in new and funky ways.. +## check Relationship::CascadeActions and Relationship::Accessor for compat +## tests! + +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); + } + if ($self->result_source->pk_depends_on($relname, $data)) { + return $self->result_source + ->related_source($relname) + ->resultset + ->find_or_create($data); + } + return $self->find_or_new_related($relname, $data); +} + +sub __their_pk_needs_us { # this should maybe be in resultsource. + my ($self, $relname, $data) = @_; + my $source = $self->result_source; + my $reverse = $source->reverse_relationship_info($relname); + my $rel_source = $source->related_source($relname); + my $us = { $self->get_columns }; + 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 0; +} + sub new { my ($class, $attrs) = @_; $class = ref $class if ref $class; - my $new = { _column_data => {} }; + my $new = { + _column_data => {}, + }; bless $new, $class; + if (my $handle = delete $attrs->{-source_handle}) { + $new->_source_handle($handle); + } + + my $source; + if ($source = delete $attrs->{-result_source}) { + $new->result_source($source); + } + if ($attrs) { $new->throw_exception("attrs must be a hashref") unless ref($attrs) eq 'HASH'; - foreach my $k (keys %$attrs) { - $new->throw_exception("No such column $k on $class") - unless $class->has_column($k); - $new->store_column($k => $attrs->{$k}); + + 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; + my $info = $source->relationship_info($key); + if ($info && $info->{attrs}{accessor} + && $info->{attrs}{accessor} eq 'single') + { + my $rel_obj = delete $attrs->{$key}; + if(!Scalar::Util::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; + $related->{$key} = $rel_obj; + next; + } elsif ($info && $info->{attrs}{accessor} + && $info->{attrs}{accessor} eq 'multi' + && ref $attrs->{$key} eq 'ARRAY') { + my $others = delete $attrs->{$key}; + foreach my $rel_obj (@$others) { + if(!Scalar::Util::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; + } + $related->{$key} = $others; + next; + } elsif ($info && $info->{attrs}{accessor} + && $info->{attrs}{accessor} eq 'filter') + { + ## 'filter' should disappear and get merged in with 'single' above! + my $rel_obj = delete $attrs->{$key}; + if(!Scalar::Util::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); + $inflated->{$key} = $rel_obj; + next; + } elsif ($class->has_column($key) + && $class->column_info($key)->{_inflate_info}) { + $inflated->{$key} = $attrs->{$key}; + next; + } + } + $new->throw_exception("No such column $key on $class") + unless $class->has_column($key); + $new->store_column($key => $attrs->{$key}); } + + $new->{_relationship_data} = $related if $related; + $new->{_inflated_column} = $inflated if $inflated; } return $new; @@ -53,36 +195,152 @@ sub new { =head2 insert - $obj->insert; + $row->insert; + +=over + +=item Arguments: none + +=item Returns: The Row object -Inserts an object into the database if it isn't already in there. Returns -the object itself. Requires the object's result source to be set, or the -class to have a result_source_instance method. +=back + +Inserts an object previously created by L into the database if +it isn't already in there. Returns the object itself. Requires the +object's result source to be set, or the class to have a +result_source_instance method. To insert an entirely new row into +the database, use C (see L). + +To fetch an uninserted row object, call +L on a resultset. + +This will also insert any uninserted, related objects held inside this +one, see L for more details. =cut sub insert { my ($self) = @_; return $self if $self->in_storage; - $self->{result_source} ||= $self->result_source_instance + my $source = $self->result_source; + $source ||= $self->result_source($self->result_source_instance) if $self->can('result_source_instance'); - my $source = $self->{result_source}; $self->throw_exception("No result_source set on this object; can't insert") unless $source; - #use Data::Dumper; warn Dumper($self); - $source->storage->insert($source->from, { $self->get_columns }); - $self->in_storage(1); + + my $rollback_guard; + + # Check if we stored uninserted relobjs here in new() + my %related_stuff = (%{$self->{_relationship_data} || {}}, + %{$self->{_inflated_column} || {}}); + + if(!$self->{_rel_in_storage}) { + + # The guard will save us if we blow out of this scope via die + $rollback_guard = $source->storage->txn_scope_guard; + + ## 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. + + my @pri = $self->primary_columns; + + REL: foreach my $relname (keys %related_stuff) { + + my $rel_obj = $related_stuff{$relname}; + + 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 } + ); + + $rel_obj->insert(); + $self->set_from_related($relname, $rel_obj); + delete $related_stuff{$relname}; + } + } + + my $updated_cols = $source->storage->insert($source, { $self->get_columns }); + foreach my $col (keys %$updated_cols) { + $self->store_column($col, $updated_cols->{$col}); + } + + ## PK::Auto + my @auto_pri = grep { + !defined $self->get_column($_) || + ref($self->get_column($_)) eq 'SCALAR' + } $self->primary_columns; + + if (@auto_pri) { + #$self->throw_exception( "More than one possible key found for auto-inc on ".ref $self ) + # if defined $too_many; + + 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); + $self->throw_exception( "Can't get last insert id" ) + unless (@ids == @auto_pri); + $self->store_column($auto_pri[$_] => $ids[$_]) for 0 .. $#ids; + } + $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->{_relationship_data} || {} }, $obj->get_inflated_columns }; + if ($self->__their_pk_needs_us($relname, $them)) { + $obj = $self->find_or_create_related($relname, $them); + } else { + $obj->insert(); + } + } + } + } + $rollback_guard->commit; + } + + $self->in_storage(1); + undef $self->{_orig_ident}; return $self; } =head2 in_storage - $obj->in_storage; # Get value - $obj->in_storage(1); # Set value + $row->in_storage; # Get value + $row->in_storage(1); # Set value + +=over + +=item Arguments: none or 1|0 + +=item Returns: 1|0 + +=back -Indicated whether the object exists as a row in the database or not +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. + +Creating a row object using L, or calling +L on one, sets it to false. =cut @@ -94,24 +352,68 @@ sub in_storage { =head2 update - $obj->update; + $row->update(\%columns?) + +=over + +=item Arguments: none or a hashref + +=item Returns: The Row object + +=back + +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. + +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 +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: -Must be run on an object that is already in the database; issues an SQL -UPDATE query to commit any changes to the object to the db if required. + $row->last_modified(\'NOW()'); + # OR + $row->update({ last_modified => \'NOW()' }); + +The update will pass the values verbatim into SQL. (See +L docs). The values in your Row object will NOT change +as a result of the update call, if you want the object to be updated +with the actual values from the database, call L +after the update. + + $row->update()->discard_changes(); + +To determine before calling this method, which column values have +changed and will be updated, call L. + +To check if any columns will be updated, call L. + +To force a column to be updated, call L before +this method. =cut sub update { my ($self, $upd) = @_; $self->throw_exception( "Not in database" ) unless $self->in_storage; - $self->set_columns($upd) if $upd; - my %to_update = $self->get_dirty_columns; - return $self unless keys %to_update; my $ident_cond = $self->ident_condition; $self->throw_exception("Cannot safely update a row in a PK-less table") if ! keys %$ident_cond; + + $self->set_inflated_columns($upd) if $upd; + my %to_update = $self->get_dirty_columns; + return $self unless keys %to_update; my $rows = $self->result_source->storage->update( - $self->result_source->from, \%to_update, $ident_cond); + $self->result_source, \%to_update, + $self->{_orig_ident} || $ident_cond + ); if ($rows == 0) { $self->throw_exception( "Can't update ${self}: row not found" ); } elsif ($rows > 1) { @@ -119,16 +421,46 @@ sub update { } $self->{_dirty_columns} = {}; $self->{related_resultsets} = {}; + undef $self->{_orig_ident}; return $self; } =head2 delete - $obj->delete + $row->delete + +=over + +=item Arguments: none + +=item Returns: The Row object + +=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. + +The object is still perfectly usable, but L will +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. -Deletes the object from the database. The object is still perfectly usable, -but ->in_storage() will now return 0 and the object must re inserted using -->insert() before ->update() can be used on it. +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. =cut @@ -136,7 +468,7 @@ sub delete { my $self = shift; if (ref $self) { $self->throw_exception( "Not in database" ) unless $self->in_storage; - my $ident_cond = $self->ident_condition; + my $ident_cond = $self->{_orig_ident} || $self->ident_condition; $self->throw_exception("Cannot safely delete a row in a PK-less table") if ! keys %$ident_cond; foreach my $column (keys %$ident_cond) { @@ -144,7 +476,7 @@ sub delete { unless exists $self->{_column_data}{$column}; } $self->result_source->storage->delete( - $self->result_source->from, $ident_cond); + $self->result_source, $ident_cond); $self->in_storage(undef); } else { $self->throw_exception("Can't do class delete without a ResultSource instance") @@ -158,11 +490,31 @@ sub delete { =head2 get_column - my $val = $obj->get_column($col); + my $val = $row->get_column($col); + +=over + +=item Arguments: $columnname + +=item Returns: The value of the column + +=back + +Throws an exception if the column name given doesn't exist according +to L. + +Returns a raw column value from the row object, if it has already +been fetched from the database or set by an accessor. + +If an L has been set, it +will be deflated and returned. -Gets a column value from a row object. Currently, does not do -any queries; the column must have already been fetched from -the database and stored in the object. +Note that if you used the C or the C