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;
324 # only limit resultset if there are related rows left
326 $rs_rel_delist = $rs_rel_delist->search_rs( { -not => [@cond] } );
330 #warn "\tCOND: " . Dumper(\%cond);
331 #my $rel_delist_cnt = $rs_rel_delist->count;
332 if ( $if_not_submitted eq 'delete' ) {
334 #warn "\tdeleting related rows: $rel_delist_cnt\n";
335 $rs_rel_delist->delete;
337 elsif ( $if_not_submitted eq 'set_to_null' ) {
339 #warn "\tnullifying related rows: $rel_delist_cnt\n";
340 my %update = map { $_ => undef } @rel_cols;
341 $rs_rel_delist->update( \
%update );
344 elsif ($info->{attrs
}{accessor
} eq 'single'
345 || $info->{attrs
}{accessor
} eq 'filter' )
348 #warn "\tupdating rel '$name': $if_not_submitted\n";
350 if ( ref $updates ) {
352 # for might_have relationship
353 if ( $info->{attrs
}{accessor
} eq 'single'
354 && defined $object->$name )
356 $sub_object = recursive_update
(
357 resultset
=> $related_resultset,
359 object
=> $object->$name
363 $sub_object = recursive_update
(
364 resultset
=> $related_resultset,
366 resolved
=> $resolved
371 $sub_object = $related_resultset->find($updates)
374 && ( exists $info->{attrs
}{join_type
}
375 && $info->{attrs
}{join_type
} eq 'LEFT' )
378 $object->set_from_related( $name, $sub_object )
382 && ( exists $info->{attrs
}{join_type
}
383 && $info->{attrs
}{join_type
} eq 'LEFT' )
387 $self->throw_exception(
388 "recursive_update doesn't now how to handle relationship '$name' with accessor "
389 . $info->{attrs
}{accessor
} );
394 my ( $self, $relation ) = @_;
395 my $rclass = $self->result_class;
397 # DBIx::Class::IntrospectableM2M
398 if ( $rclass->can('_m2m_metadata') ) {
399 return $rclass->_m2m_metadata->{$relation};
401 my $object = $self->new( {} );
402 if ( $object->can($relation)
403 and !$self->result_source->has_relationship($relation)
404 and $object->can( 'set_' . $relation ) )
412 my ( $self, $relation ) = @_;
413 my $rclass = $self->result_class;
415 # DBIx::Class::IntrospectableM2M
416 if ( $rclass->can('_m2m_metadata') ) {
417 return $self->result_source->related_source(
418 $rclass->_m2m_metadata->{$relation}{relation
} )
420 $rclass->_m2m_metadata->{$relation}{foreign_relation
} );
422 my $object = $self->new( {} );
423 my $r = $object->$relation;
424 return $r->result_source;
427 sub _delete_empty_auto_increment
{
428 my ( $self, $object ) = @_;
429 for my $col ( keys %{ $object->{_column_data
} } ) {
430 if ($object->result_source->column_info($col)->{is_auto_increment
}
431 and ( !defined $object->{_column_data
}{$col}
432 or $object->{_column_data
}{$col} eq '' )
435 delete $object->{_column_data
}{$col};
440 sub _get_pk_for_related
{
441 my ( $self, $relation ) = @_;
443 if ( $self->result_source->has_relationship($relation) ) {
444 $result_source = $self->result_source->related_source($relation);
448 if ( is_m2m
( $self, $relation ) ) {
449 $result_source = get_m2m_source
( $self, $relation );
451 return $result_source->primary_columns;
454 # This function determines wheter a relationship should be done before or
455 # after the row is inserted into the database
456 # relationships before: belongs_to
457 # relationships after: has_many, might_have and has_one
458 # true means before, false after
459 sub _master_relation_cond
{
460 my ( $self, $name ) = @_;
462 my $source = $self->result_source;
463 my $info = $source->relationship_info($name);
465 #warn "INFO: " . Dumper($info) . "\n";
467 # has_many rels are always after
469 if $info->{attrs
}->{accessor
} eq 'multi';
471 my @foreign_ids = _get_pk_for_related
( $self, $name );
473 #warn "IDS: " . join(', ', @foreign_ids) . "\n";
475 my $cond = $info->{cond
};
478 my ( $source, $cond, @foreign_ids ) = @_;
480 while ( my ( $f_key, $col ) = each %{$cond} ) {
482 # might_have is not master
484 $f_key =~ s/^foreign\.//;
485 if ( $source->column_info($col)->{is_auto_increment
} ) {
488 if ( any
{ $_ eq $f_key } @foreign_ids ) {
495 if ( ref $cond eq 'HASH' ) {
496 return _inner
( $source, $cond, @foreign_ids );
499 # arrayref of hashrefs
500 elsif ( ref $cond eq 'ARRAY' ) {
501 for my $new_cond (@$cond) {
502 return _inner
( $source, $new_cond, @foreign_ids );
506 $source->throw_exception(
507 "unhandled relation condition " . ref($cond) );
512 1; # Magic true value required at end of module
517 # The functional interface:
519 my $schema = MyDB::Schema->connect();
520 my $new_item = DBIx::Class::ResultSet::RecursiveUpdate::Functions::recursive_update({
521 resultset => $schema->resultset('User'),
526 title => "One Flew Over the Cuckoo's Nest"
533 # As ResultSet subclass:
535 __PACKAGE__->load_namespaces( default_resultset_class => '+DBIx::Class::ResultSet::RecursiveUpdate' );
537 # in the Schema file (see t/lib/DBSchema.pm). Or appriopriate 'use base' in the ResultSet classes.
539 my $user = $schema->resultset('User')->recursive_update({
543 title => "One Flew Over the Cuckoo's Nest"
551 This is still experimental. I've added a functional interface so that it can be used
552 in Form Processors and not require modification of the model.
554 You can feed the ->create method with a recursive datastructure and have the related records
555 created. Unfortunately you cannot do a similar thing with update_or_create - this module
556 tries to fill that void.
558 It is a base class for ResultSets providing just one method: recursive_update
559 which works just like update_or_create but can recursively update or create
560 data objects composed of multiple rows. All rows need to be identified by primary keys
561 - so you need to provide them in the update structure (unless they can be deduced from
562 the parent row - for example when you have a belongs_to relationship).
563 If not all colums comprising the primary key are specified - then a new row will be created,
564 with the expectation that the missing columns will be filled by it (as in the case of auto_increment
568 If the resultset itself stores an assignement for the primary key,
571 my $restricted_rs = $user_rs->search( { id => 1 } );
573 then you need to inform recursive_update about additional predicate with a second argument:
575 my $user = $restricted_rs->recursive_update( {
578 title => 'One Flew Over the Cuckoo's Nest'
585 This will work with a new DBIC release.
587 For a many_to_many (pseudo) relation you can supply a list of primary keys
588 from the other table - and it will link the record at hand to those and
589 only those records identified by them. This is convenient for handling web
590 forms with check boxes (or a SELECT box with multiple choice) that let you
591 update such (pseudo) relations.
593 For a description how to set up base classes for ResultSets see load_namespaces
594 in DBIx::Class::Schema.
596 =head1 DESIGN CHOICES
598 Columns and relationships which are excluded from the updates hashref aren't
601 =head2 Treatment of belongs_to relations
603 In case the relationship is included but undefined in the updates hashref,
604 all columns forming the relationship will be set to null.
605 If not all of them are nullable, DBIx::Class will throw an error.
607 Updating the relationship:
609 my $dvd = $dvd_rs->recursive_update( {
614 Clearing the relationship (only works if cols are nullable!):
616 my $dvd = $dvd_rs->recursive_update( {
621 =head2 Treatment of might_have relationships
623 In case the relationship is included but undefined in the updates hashref,
624 all columns forming the relationship will be set to null.
626 Updating the relationship:
628 my $user = $user_rs->recursive_update( {
631 street => "101 Main Street",
637 Clearing the relationship:
639 my $user = $user_rs->recursive_update( {
644 =head2 Treatment of has_many relations
646 If a relationship key is included in the data structure with a value of undef
647 or an empty array, all existing related rows will be deleted, or their foreign
648 key columns will be set to null.
650 The exact behaviour depends on the nullability of the foreign key columns and
651 the value of the "if_not_submitted" parameter. The parameter defaults to
652 undefined which neither nullifies nor deletes.
654 When the array contains elements they are updated if they exist, created when
655 not and deleted if not included.
657 =head3 All foreign table columns are nullable
659 In this case recursive_update defaults to nullifying the foreign columns.
661 =head3 Not all foreign table columns are nullable
663 In this case recursive_update deletes the foreign rows.
665 Updating the relationship:
669 my $dvd = $dvd_rs->recursive_update( {
676 my $dvd = $dvd_rs->recursive_update( {
694 You can even mix them:
696 my $dvd = $dvd_rs->recursive_update( {
698 tags => [ '2', { id => '3' } ],
701 Clearing the relationship:
703 my $dvd = $dvd_rs->recursive_update( {
708 This is the same as passing an empty array:
710 my $dvd = $dvd_rs->recursive_update( {
715 =head2 Treatment of many-to-many pseudo relations
717 The function gets the information about m2m relations from DBIx::Class::IntrospectableM2M.
718 If it isn't loaded in the ResultSource classes the code relies on the fact that:
720 if($object->can($name) and
721 !$object->result_source->has_relationship($name) and
722 $object->can( 'set_' . $name )
725 Then $name must be a many to many pseudo relation.
726 And that in a similarly ugly was I find out what is the ResultSource of
727 objects from that many to many pseudo relation.
734 =head2 recursive_update
736 The method that does the work here.
740 $self->is_m2m( 'name ' ) - answers the question if 'name' is a many to many
741 (pseudo) relation on $self.
743 =head2 get_m2m_source
745 $self->get_m2m_source( 'name' ) - returns the ResultSource linked to by the many
746 to many (pseudo) relation 'name' from $self.
752 =head1 CONFIGURATION AND ENVIRONMENT
754 DBIx::Class::RecursiveUpdate requires no configuration files or environment variables.
760 =head1 INCOMPATIBILITIES
765 =head1 BUGS AND LIMITATIONS
767 No bugs have been reported.
769 Please report any bugs or feature requests to
770 C<bug-dbix-class-recursiveput@rt.cpan.org>, or through the web interface at
771 L<http://rt.cpan.org>.