4 package DBIx
::Class
::ResultSet
::RecursiveUpdate
;
5 # ABSTRACT: like update_or_create - but recursive
7 use base
qw(DBIx::Class::ResultSet);
10 my ( $self, $updates, $fixed_fields ) = @_;
12 DBIx
::Class
::ResultSet
::RecursiveUpdate
::Functions
::recursive_update
(
15 fixed_fields
=> $fixed_fields
19 package DBIx
::Class
::ResultSet
::RecursiveUpdate
::Functions
;
21 use Scalar
::Util
qw( blessed );
22 use List
::MoreUtils qw
/ any /;
24 sub recursive_update
{
26 my ( $self, $updates, $fixed_fields, $object, $resolved,
29 qw
/resultset updates fixed_fields object resolved if_not_submitted/};
32 # warn 'entering: ' . $self->result_source->from();
33 carp
'fixed fields needs to be an array ref'
34 if $fixed_fields && ref($fixed_fields) ne 'ARRAY';
36 %fixed_fields = map { $_ => 1 } @$fixed_fields if $fixed_fields;
37 if ( blessed
($updates) && $updates->isa('DBIx::Class::Row') ) {
40 if ( $updates->{id
} ) {
41 $object = $self->find( $updates->{id
}, { key
=> 'primary' } );
44 grep { !exists $updates->{$_} && !exists $fixed_fields{$_} }
45 $self->result_source->primary_columns;
46 if ( !$object && !scalar @missing ) {
48 # warn 'finding by: ' . Dumper( $updates ); use Data::Dumper;
49 $object = $self->find( $updates, { key
=> 'primary' } );
51 $updates = { %$updates, %$resolved };
53 grep { !exists $resolved->{$_} } @missing;
54 if ( !$object && !scalar @missing ) {
56 # warn 'finding by +resolved: ' . Dumper( $updates ); use Data::Dumper;
57 $object = $self->find( $updates, { key
=> 'primary' } );
59 $object ||= $self->new( {} );
61 # warn Dumper( $updates ); use Data::Dumper;
62 # direct column accessors
65 # relations that that should be done before the row is inserted into the
66 # database like belongs_to
69 # relations that that should be done after the row is inserted into the
70 # database like has_many, might_have and has_one
73 my %columns_by_accessor = _get_columns_by_accessor
($self);
75 # warn 'resolved: ' . Dumper( $resolved );
76 # warn 'updates: ' . Dumper( $updates ); use Data::Dumper;
77 # warn 'columns: ' . Dumper( \%columns_by_accessor );
78 for my $name ( keys %$updates ) {
79 my $source = $self->result_source;
82 if ( exists $columns_by_accessor{$name}
83 && !( $source->has_relationship($name)
84 && ref( $updates->{$name} ) ) )
87 #warn "$name is a column\n";
88 $columns{$name} = $updates->{$name};
93 if ( $source->has_relationship($name) ) {
94 if ( _master_relation_cond
( $self, $name ) ) {
96 #warn "$name is a pre-update rel\n";
97 $pre_updates{$name} = $updates->{$name};
102 #warn "$name is a post-update rel\n";
103 $post_updates{$name} = $updates->{$name};
108 # many-to-many helper accessors
109 if ( is_m2m
( $self, $name ) ) {
111 #warn "$name is a many-to-many helper accessor\n";
112 $other_methods{$name} = $updates->{$name};
117 if ( $object->can($name) && not $source->has_relationship($name) ) {
119 #warn "$name is an accessor";
120 $other_methods{$name} = $updates->{$name};
125 # TODO: don't throw a warning instead of an exception to give users
126 # time to adapt to the new API
127 $self->throw_exception(
128 "No such column, relationship, many-to-many helper accessor or generic accessor '$name'"
132 # warn 'other: ' . Dumper( \%other_methods ); use Data::Dumper;
134 # first update columns and other accessors
135 # so that later related records can be found
136 for my $name ( keys %columns ) {
138 #warn "update col $name\n";
139 $object->$name( $columns{$name} );
141 for my $name ( keys %other_methods ) {
143 #warn "update other $name\n";
144 $object->$name( $updates->{$name} );
146 for my $name ( keys %pre_updates ) {
148 #warn "pre_update $name\n";
149 _update_relation
( $self, $name, $pre_updates{$name}, $object,
153 # $self->_delete_empty_auto_increment($object);
154 # don't allow insert to recurse to related objects
155 # do the recursion ourselves
156 # $object->{_rel_in_storage} = 1;
157 #warn "CHANGED: " . $object->is_changed . "\n":
158 #warn "IN STOR: " . $object->in_storage . "\n";
159 $object->update_or_insert if $object->is_changed;
160 $object->discard_changes;
162 # updating many_to_many
163 for my $name ( keys %$updates ) {
164 next if exists $columns{$name};
165 my $value = $updates->{$name};
167 if ( is_m2m
( $self, $name ) ) {
169 #warn "update m2m $name\n";
170 my ($pk) = _get_pk_for_related
( $self, $name );
172 my $result_source = $object->$name->result_source;
174 if ( !defined $value ) {
177 elsif ( ref $value ) {
178 @updates = @{$value};
183 for my $elem (@updates) {
187 resultset
=> $result_source->resultset,
193 $result_source->resultset->find( { $pk => $elem } );
196 my $set_meth = 'set_' . $name;
197 $object->$set_meth( \
@rows );
200 for my $name ( keys %post_updates ) {
202 #warn "post_update $name\n";
203 _update_relation
( $self, $name, $post_updates{$name}, $object,
209 # returns DBIx::Class::ResultSource::column_info as a hash indexed by column accessor || name
210 sub _get_columns_by_accessor
{
212 my $source = $self->result_source;
214 for my $name ( $source->columns ) {
215 my $info = $source->column_info($name);
216 $info->{name
} = $name;
217 $columns{ $info->{accessor
} || $name } = $info;
222 # Arguments: $rs, $name, $updates, $row, $if_not_submitted
223 sub _update_relation
{
224 my ( $self, $name, $updates, $object, $if_not_submitted ) = @_;
226 # this should never happen because we're checking the paramters passed to
227 # recursive_update, but just to be sure...
228 $object->throw_exception("No such relationship '$name'")
229 unless $object->has_relationship($name);
231 #warn "_update_relation $name: OBJ: " . ref($object) . "\n";
233 my $info = $object->result_source->relationship_info($name);
235 # get a related resultset without a condition
236 my $related_resultset =
237 $self->related_resultset($name)->result_source->resultset;
239 if ( $self->result_source->can('_resolve_condition') ) {
241 $self->result_source->_resolve_condition( $info->{cond
}, $name,
245 $self->throw_exception(
246 "result_source must support _resolve_condition");
249 # warn "$name resolved: " . Dumper( $resolved ); use Data::Dumper;
251 if defined $DBIx::Class
::ResultSource
::UNRESOLVABLE_CONDITION
252 && $DBIx::Class
::ResultSource
::UNRESOLVABLE_CONDITION
255 my @rel_cols = keys %{ $info->{cond
} };
256 map {s/^foreign\.//} @rel_cols;
258 #warn "REL_COLS: " . Dumper(@rel_cols); use Data::Dumper;
259 #my $rel_col_cnt = scalar @rel_cols;
261 # find out if all related columns are nullable
262 my $all_fks_nullable = 1;
263 for my $rel_col (@rel_cols) {
264 $all_fks_nullable = 0
265 unless $related_resultset->result_source->column_info($rel_col)
269 $if_not_submitted = $all_fks_nullable ? 'nullify' : 'delete'
270 unless defined $if_not_submitted;
272 #warn "\tNULLABLE: $all_fks_nullable ACTION: $if_not_submitted\n";
274 #warn "RELINFO for $name: " . Dumper($info); use Data::Dumper;
276 # the only valid datatype for a has_many rels is an arrayref
277 if ( $info->{attrs
}{accessor
} eq 'multi' ) {
279 # handle undef like empty arrayref
281 unless defined $updates;
282 $self->throw_exception(
283 "data for has_many relationship '$name' must be an arrayref")
284 unless ref $updates eq 'ARRAY';
288 #warn "\tupdating has_many rel '$name' ($rel_col_cnt columns cols)\n";
289 for my $sub_updates ( @{$updates} ) {
290 my $sub_object = recursive_update
(
291 resultset
=> $related_resultset,
292 updates
=> $sub_updates,
293 resolved
=> $resolved
296 push @updated_objs, $sub_object;
299 #warn "\tcreated and updated related rows\n";
301 my @related_pks = $related_resultset->result_source->primary_columns;
303 my $rs_rel_delist = $object->$name;
305 # foreign table has a single pk column
306 if ( scalar @related_pks == 1 ) {
307 $rs_rel_delist = $rs_rel_delist->search_rs(
309 { -not_in
=> [ map ( $_->id, @updated_objs ) ] }
314 # foreign table has multiple pk columns
317 for my $obj (@updated_objs) {
319 for my $col (@related_pks) {
320 $cond_for_obj{$col} = $obj->get_column($col);
322 push @cond, \
%cond_for_obj;
325 # only limit resultset if there are related rows left
326 if ( scalar @cond ) {
328 $rs_rel_delist->search_rs( { -not => [@cond] } );
332 #warn "\tCOND: " . Dumper(\%cond);
333 #my $rel_delist_cnt = $rs_rel_delist->count;
334 if ( $if_not_submitted eq 'delete' ) {
336 #warn "\tdeleting related rows: $rel_delist_cnt\n";
337 $rs_rel_delist->delete;
339 elsif ( $if_not_submitted eq 'set_to_null' ) {
341 #warn "\tnullifying related rows: $rel_delist_cnt\n";
342 my %update = map { $_ => undef } @rel_cols;
343 $rs_rel_delist->update( \
%update );
346 elsif ($info->{attrs
}{accessor
} eq 'single'
347 || $info->{attrs
}{accessor
} eq 'filter' )
350 #warn "\tupdating rel '$name': $if_not_submitted\n";
352 if ( ref $updates ) {
354 # for might_have relationship
355 if ( $info->{attrs
}{accessor
} eq 'single'
356 && defined $object->$name )
358 $sub_object = recursive_update
(
359 resultset
=> $related_resultset,
361 object
=> $object->$name
365 $sub_object = recursive_update
(
366 resultset
=> $related_resultset,
368 resolved
=> $resolved
373 $sub_object = $related_resultset->find($updates)
376 && ( exists $info->{attrs
}{join_type
}
377 && $info->{attrs
}{join_type
} eq 'LEFT' )
380 $object->set_from_related( $name, $sub_object )
384 && ( exists $info->{attrs
}{join_type
}
385 && $info->{attrs
}{join_type
} eq 'LEFT' )
389 $self->throw_exception(
390 "recursive_update doesn't now how to handle relationship '$name' with accessor "
391 . $info->{attrs
}{accessor
} );
396 my ( $self, $relation ) = @_;
397 my $rclass = $self->result_class;
399 # DBIx::Class::IntrospectableM2M
400 if ( $rclass->can('_m2m_metadata') ) {
401 return $rclass->_m2m_metadata->{$relation};
403 my $object = $self->new( {} );
404 if ( $object->can($relation)
405 and !$self->result_source->has_relationship($relation)
406 and $object->can( 'set_' . $relation ) )
414 my ( $self, $relation ) = @_;
415 my $rclass = $self->result_class;
417 # DBIx::Class::IntrospectableM2M
418 if ( $rclass->can('_m2m_metadata') ) {
419 return $self->result_source->related_source(
420 $rclass->_m2m_metadata->{$relation}{relation
} )
422 $rclass->_m2m_metadata->{$relation}{foreign_relation
} );
424 my $object = $self->new( {} );
425 my $r = $object->$relation;
426 return $r->result_source;
429 sub _delete_empty_auto_increment
{
430 my ( $self, $object ) = @_;
431 for my $col ( keys %{ $object->{_column_data
} } ) {
432 if ($object->result_source->column_info($col)->{is_auto_increment
}
433 and ( !defined $object->{_column_data
}{$col}
434 or $object->{_column_data
}{$col} eq '' )
437 delete $object->{_column_data
}{$col};
442 sub _get_pk_for_related
{
443 my ( $self, $relation ) = @_;
445 if ( $self->result_source->has_relationship($relation) ) {
446 $result_source = $self->result_source->related_source($relation);
450 if ( is_m2m
( $self, $relation ) ) {
451 $result_source = get_m2m_source
( $self, $relation );
453 return $result_source->primary_columns;
456 # This function determines wheter a relationship should be done before or
457 # after the row is inserted into the database
458 # relationships before: belongs_to
459 # relationships after: has_many, might_have and has_one
460 # true means before, false after
461 sub _master_relation_cond
{
462 my ( $self, $name ) = @_;
464 my $source = $self->result_source;
465 my $info = $source->relationship_info($name);
467 #warn "INFO: " . Dumper($info) . "\n";
469 # has_many rels are always after
471 if $info->{attrs
}->{accessor
} eq 'multi';
473 my @foreign_ids = _get_pk_for_related
( $self, $name );
475 #warn "IDS: " . join(', ', @foreign_ids) . "\n";
477 my $cond = $info->{cond
};
480 my ( $source, $cond, @foreign_ids ) = @_;
482 while ( my ( $f_key, $col ) = each %{$cond} ) {
484 # might_have is not master
486 $f_key =~ s/^foreign\.//;
487 if ( $source->column_info($col)->{is_auto_increment
} ) {
490 if ( any
{ $_ eq $f_key } @foreign_ids ) {
497 if ( ref $cond eq 'HASH' ) {
498 return _inner
( $source, $cond, @foreign_ids );
501 # arrayref of hashrefs
502 elsif ( ref $cond eq 'ARRAY' ) {
503 for my $new_cond (@$cond) {
504 return _inner
( $source, $new_cond, @foreign_ids );
508 $source->throw_exception(
509 "unhandled relation condition " . ref($cond) );
514 1; # Magic true value required at end of module
519 # The functional interface:
521 my $schema = MyDB::Schema->connect();
522 my $new_item = DBIx::Class::ResultSet::RecursiveUpdate::Functions::recursive_update(
523 resultset => $schema->resultset('User'),
528 title => "One Flew Over the Cuckoo's Nest"
535 # As ResultSet subclass:
537 __PACKAGE__->load_namespaces( default_resultset_class => '+DBIx::Class::ResultSet::RecursiveUpdate' );
539 # in the Schema file (see t/lib/DBSchema.pm). Or appropriate 'use base' in the ResultSet classes.
541 my $user = $schema->resultset('User')->recursive_update({
545 title => "One Flew Over the Cuckoo's Nest"
549 unknown_params_ok => 1,
555 This is still experimental.
557 You can feed the ->create method of DBIx::Class with a recursive datastructure
558 and have the related records created. Unfortunately you cannot do a similar
559 thing with update_or_create.
560 This module tries to fill that void until L<DBIx::Class> has an api itself.
562 The functional interface can be used without modifications of the model,
563 for example by form processors like L<HTML::FormHandler::Model::DBIC>.
565 It is a base class for L<DBIx::Class::ResultSet>s providing the method recursive_update
566 which works just like update_or_create but can recursively update or create
567 data objects composed of multiple rows. All rows need to be identified by primary keys
568 - so you need to provide them in the update structure (unless they can be deduced from
569 the parent row - for example when you have a belongs_to relationship).
570 If not all columns comprising the primary key are specified a new row will be created,
571 with the expectation that the missing columns will be filled by it (as in the case of auto_increment
575 If the resultset itself stores an assignement for the primary key,
578 my $restricted_rs = $user_rs->search( { id => 1 } );
580 then you need to inform recursive_update about additional predicate with a second argument:
582 my $user = $restricted_rs->recursive_update( {
585 title => 'One Flew Over the Cuckoo's Nest'
592 For a many_to_many (pseudo) relation you can supply a list of primary keys
593 from the other table and it will link the record at hand to those and
594 only those records identified by them. This is convenient for handling web
595 forms with check boxes (or a select field with multiple choice) that lets you
596 update such (pseudo) relations.
598 For a description how to set up base classes for ResultSets see L<DBIx::Class::Schema/load_namespaces>.
600 =head1 DESIGN CHOICES
602 Columns and relationships which are excluded from the updates hashref aren't
605 =head2 Treatment of belongs_to relations
607 In case the relationship is included but undefined in the updates hashref,
608 all columns forming the relationship will be set to null.
609 If not all of them are nullable, DBIx::Class will throw an error.
611 Updating the relationship:
613 my $dvd = $dvd_rs->recursive_update( {
618 Clearing the relationship (only works if cols are nullable!):
620 my $dvd = $dvd_rs->recursive_update( {
625 =head2 Treatment of might_have relationships
627 In case the relationship is included but undefined in the updates hashref,
628 all columns forming the relationship will be set to null.
630 Updating the relationship:
632 my $user = $user_rs->recursive_update( {
635 street => "101 Main Street",
641 Clearing the relationship:
643 my $user = $user_rs->recursive_update( {
648 =head2 Treatment of has_many relations
650 If a relationship key is included in the data structure with a value of undef
651 or an empty array, all existing related rows will be deleted, or their foreign
652 key columns will be set to null.
654 The exact behaviour depends on the nullability of the foreign key columns and
655 the value of the "if_not_submitted" parameter. The parameter defaults to
656 undefined which neither nullifies nor deletes.
658 When the array contains elements they are updated if they exist, created when
659 not and deleted if not included.
661 =head3 All foreign table columns are nullable
663 In this case recursive_update defaults to nullifying the foreign columns.
665 =head3 Not all foreign table columns are nullable
667 In this case recursive_update deletes the foreign rows.
669 Updating the relationship:
673 my $dvd = $dvd_rs->recursive_update( {
680 my $dvd = $dvd_rs->recursive_update( {
698 You can even mix them:
700 my $dvd = $dvd_rs->recursive_update( {
702 tags => [ '2', { id => '3' } ],
705 Clearing the relationship:
707 my $dvd = $dvd_rs->recursive_update( {
712 This is the same as passing an empty array:
714 my $dvd = $dvd_rs->recursive_update( {
719 =head2 Treatment of many-to-many pseudo relations
721 The function gets the information about m2m relations from L<DBIx::Class::IntrospectableM2M>.
722 If it isn't loaded in the ResultSource classes the code relies on the fact that:
724 if($object->can($name) and
725 !$object->result_source->has_relationship($name) and
726 $object->can( 'set_' . $name )
729 Then $name must be a many to many pseudo relation.
730 And that in a similarly ugly was I find out what is the ResultSource of
731 objects from that many to many pseudo relation.
738 =head2 recursive_update
740 The method that does the work here.
744 $self->is_m2m( 'name ' ) - answers the question if 'name' is a many to many
745 (pseudo) relation on $self.
747 =head2 get_m2m_source
749 $self->get_m2m_source( 'name' ) - returns the ResultSource linked to by the many
750 to many (pseudo) relation 'name' from $self.
756 =head1 CONFIGURATION AND ENVIRONMENT
758 DBIx::Class::RecursiveUpdate requires no configuration files or environment variables.
764 =head1 INCOMPATIBILITIES
769 =head1 BUGS AND LIMITATIONS
771 No bugs have been reported.
773 Please report any bugs or feature requests to
774 C<bug-dbix-class-recursiveput@rt.cpan.org>, or through the web interface at
775 L<http://rt.cpan.org>.