4 package DBIx
::Class
::ResultSet
::RecursiveUpdate
;
6 # ABSTRACT: like update_or_create - but recursive
8 use base
qw(DBIx::Class::ResultSet);
10 sub recursive_update
{
11 my ( $self, $updates, $attrs ) = @_;
14 my $unknown_params_ok;
17 if ( defined $attrs && ref $attrs eq 'HASH' ) {
18 $fixed_fields = $attrs->{fixed_fields
};
19 $unknown_params_ok = $attrs->{unknown_params_ok
};
23 elsif ( defined $attrs && ref $attrs eq 'ARRAY' ) {
24 $fixed_fields = $attrs;
28 DBIx
::Class
::ResultSet
::RecursiveUpdate
::Functions
::recursive_update
(
31 fixed_fields
=> $fixed_fields,
32 unknown_params_ok
=> $unknown_params_ok,
36 package DBIx
::Class
::ResultSet
::RecursiveUpdate
::Functions
;
37 use Carp
::Clan qw
/^DBIx::Class|^HTML::FormHandler|^Try::Tiny/;
38 use Scalar
::Util
qw( blessed );
39 use List
::MoreUtils qw
/ any /;
42 sub recursive_update
{
44 my ( $self, $updates, $fixed_fields, $object, $resolved,
45 $if_not_submitted, $unknown_params_ok )
47 qw
/resultset updates fixed_fields object resolved if_not_submitted unknown_params_ok/
51 my $source = $self->result_source;
53 croak
"first parameter needs to be defined"
54 unless defined $updates;
56 croak
"first parameter needs to be a hashref"
57 unless ref($updates) eq 'HASH';
59 # warn 'entering: ' . $source->from();
60 croak
'fixed fields needs to be an arrayref'
61 if defined $fixed_fields && ref $fixed_fields ne 'ARRAY';
63 # always warn about additional parameters if storage debugging is enabled
64 $unknown_params_ok = 0
65 if $source->storage->debug;
67 if ( blessed
($updates) && $updates->isa('DBIx::Class::Row') ) {
71 if ( !defined $object && exists $updates->{id
} ) {
73 # warn "finding object by id " . $updates->{id} . "\n";
74 $object = $self->find( $updates->{id
}, { key
=> 'primary' } );
76 # warn "object not found by id\n"
77 # unless defined $object;
80 my %fixed_fields = map { $_ => 1 } @$fixed_fields
83 # the updates hashref might contain the pk columns
84 # but with an undefined value
86 grep { !defined $updates->{$_} && !exists $fixed_fields{$_} }
87 $source->primary_columns;
89 # warn "MISSING: " . join(', ', @missing) . "\n";
90 if ( !defined $object && scalar @missing == 0 ) {
92 # warn 'finding by: ' . Dumper( $updates ); use Data::Dumper;
93 $object = $self->find( $updates, { key
=> 'primary' } );
96 # add the resolved columns to the updates hashref
97 $updates = { %$updates, %$resolved };
99 # the resolved hashref might contain the pk columns
100 # but with an undefined value
101 @missing = grep { !defined $resolved->{$_} } @missing;
103 #warn "MISSING2: " . join( ', ', @missing ) . "\n";
104 if ( !defined $object && scalar @missing == 0 ) {
106 # warn 'finding by +resolved: ' . Dumper( $updates ); use Data::Dumper;
107 $object = $self->find( $updates, { key
=> 'primary' } );
110 $object = $self->new( {} )
111 unless defined $object;
113 # warn Dumper( $updates ); use Data::Dumper;
114 # direct column accessors
117 # relations that that should be done before the row is inserted into the
118 # database like belongs_to
121 # relations that that should be done after the row is inserted into the
122 # database like has_many, might_have and has_one
126 my %columns_by_accessor = _get_columns_by_accessor
($self);
128 # warn 'resolved: ' . Dumper( $resolved );
129 # warn 'updates: ' . Dumper( $updates ); use Data::Dumper;
130 # warn 'columns: ' . Dumper( \%columns_by_accessor );
131 for my $name ( keys %$updates ) {
134 if ( exists $columns_by_accessor{$name}
135 && !( $source->has_relationship($name)
136 && ref( $updates->{$name} ) ) )
139 #warn "$name is a column\n";
140 $columns{$name} = $updates->{$name};
145 if ( $source->has_relationship($name) ) {
146 if ( _master_relation_cond
( $self, $name ) ) {
148 #warn "$name is a pre-update rel\n";
149 $pre_updates{$name} = $updates->{$name};
154 #warn "$name is a post-update rel\n";
155 $post_updates{$name} = $updates->{$name};
160 # many-to-many helper accessors
161 if ( is_m2m
( $self, $name ) ) {
163 #warn "$name is a many-to-many helper accessor\n";
164 $m2m_accessors{$name} = $updates->{$name};
169 if ( $object->can($name) && not $source->has_relationship($name) ) {
171 #warn "$name is an accessor";
172 $other_methods{$name} = $updates->{$name};
178 # don't throw a warning instead of an exception to give users
179 # time to adapt to the new API
181 "No such column, relationship, many-to-many helper accessor or generic accessor '$name'"
182 ) unless $unknown_params_ok;
184 #$self->throw_exception(
185 # "No such column, relationship, many-to-many helper accessor or generic accessor '$name'"
189 # warn 'other: ' . Dumper( \%other_methods ); use Data::Dumper;
191 # first update columns and other accessors
192 # so that later related records can be found
193 for my $name ( keys %columns ) {
195 #warn "update col $name\n";
196 $object->$name( $columns{$name} );
198 for my $name ( keys %other_methods ) {
200 #warn "update other $name\n";
201 $object->$name( $other_methods{$name} );
203 for my $name ( keys %pre_updates ) {
205 #warn "pre_update $name\n";
206 _update_relation
( $self, $name, $pre_updates{$name}, $object,
210 # $self->_delete_empty_auto_increment($object);
211 # don't allow insert to recurse to related objects
212 # do the recursion ourselves
213 # $object->{_rel_in_storage} = 1;
214 #warn "CHANGED: " . $object->is_changed . "\n";
215 #warn "IN STOR: " . $object->in_storage . "\n";
216 $object->update_or_insert if $object->is_changed;
217 $object->discard_changes;
219 # updating many_to_many
220 for my $name ( keys %m2m_accessors ) {
221 my $value = $m2m_accessors{$name};
223 #warn "update m2m $name\n";
224 # TODO: only first pk col is used
225 my ($pk) = _get_pk_for_related
( $self, $name );
227 my $result_source = $object->$name->result_source;
229 if ( defined $value && ref $value eq 'ARRAY' ) {
230 @updates = @{$value};
232 elsif ( defined $value && !ref $value ) {
235 elsif ( defined $value ) {
237 "value of many-to-many rel '$name' must be an arrayref or scalar: $value";
239 for my $elem (@updates) {
240 if ( blessed
($elem) && $elem->isa('DBIx::Class::Row') ) {
243 elsif ( ref $elem eq 'HASH' ) {
246 resultset
=> $result_source->resultset,
252 $result_source->resultset->find( { $pk => $elem } );
255 my $set_meth = 'set_' . $name;
256 $object->$set_meth( \
@rows );
258 for my $name ( keys %post_updates ) {
260 #warn "post_update $name\n";
261 _update_relation
( $self, $name, $post_updates{$name}, $object,
267 # returns DBIx::Class::ResultSource::column_info as a hash indexed by column accessor || name
268 sub _get_columns_by_accessor
{
270 my $source = $self->result_source;
272 for my $name ( $source->columns ) {
273 my $info = $source->column_info($name);
274 $info->{name
} = $name;
275 $columns{ $info->{accessor
} || $name } = $info;
280 # Arguments: $rs, $name, $updates, $row, $if_not_submitted
281 sub _update_relation
{
282 my ( $self, $name, $updates, $object, $if_not_submitted ) = @_;
284 # this should never happen because we're checking the paramters passed to
285 # recursive_update, but just to be sure...
286 $object->throw_exception("No such relationship '$name'")
287 unless $object->has_relationship($name);
289 #warn "_update_relation $name: OBJ: " . ref($object) . "\n";
291 my $info = $object->result_source->relationship_info($name);
293 # get a related resultset without a condition
294 my $related_resultset =
295 $self->related_resultset($name)->result_source->resultset;
297 if ( $self->result_source->can('_resolve_condition') ) {
299 $self->result_source->_resolve_condition( $info->{cond
}, $name,
303 $self->throw_exception(
304 "result_source must support _resolve_condition");
307 # warn "$name resolved: " . Dumper( $resolved ); use Data::Dumper;
309 if defined $DBIx::Class
::ResultSource
::UNRESOLVABLE_CONDITION
310 && $DBIx::Class
::ResultSource
::UNRESOLVABLE_CONDITION
313 #warn "RESOLVED: " . Dumper($resolved); use Data::Dumper;
315 my @rel_cols = keys %{ $info->{cond
} };
316 map {s/^foreign\.//} @rel_cols;
318 #warn "REL_COLS: " . Dumper(@rel_cols); use Data::Dumper;
319 #my $rel_col_cnt = scalar @rel_cols;
321 # find out if all related columns are nullable
322 my $all_fks_nullable = 1;
323 for my $rel_col (@rel_cols) {
324 $all_fks_nullable = 0
325 unless $related_resultset->result_source->column_info($rel_col)
329 $if_not_submitted = $all_fks_nullable ? 'nullify' : 'delete'
330 unless defined $if_not_submitted;
332 #warn "\tNULLABLE: $all_fks_nullable ACTION: $if_not_submitted\n";
334 #warn "RELINFO for $name: " . Dumper($info); use Data::Dumper;
336 # the only valid datatype for a has_many rels is an arrayref
337 if ( $info->{attrs
}{accessor
} eq 'multi' ) {
339 # handle undef like empty arrayref
341 unless defined $updates;
342 $self->throw_exception(
343 "data for has_many relationship '$name' must be an arrayref")
344 unless ref $updates eq 'ARRAY';
348 #warn "\tupdating has_many rel '$name' ($rel_col_cnt columns cols)\n";
349 for my $sub_updates ( @{$updates} ) {
350 my $sub_object = recursive_update
(
351 resultset
=> $related_resultset,
352 updates
=> $sub_updates,
353 resolved
=> $resolved
356 push @updated_objs, $sub_object;
359 #warn "\tcreated and updated related rows\n";
361 my @related_pks = $related_resultset->result_source->primary_columns;
363 my $rs_rel_delist = $object->$name;
365 # foreign table has a single pk column
366 if ( scalar @related_pks == 1 ) {
367 $rs_rel_delist = $rs_rel_delist->search_rs(
369 { -not_in
=> [ map ( $_->id, @updated_objs ) ] }
374 # foreign table has multiple pk columns
377 for my $obj (@updated_objs) {
379 for my $col (@related_pks) {
380 $cond_for_obj{$col} = $obj->get_column($col);
382 push @cond, \
%cond_for_obj;
385 # only limit resultset if there are related rows left
386 if ( scalar @cond ) {
388 $rs_rel_delist->search_rs( { -not => [@cond] } );
392 #warn "\tCOND: " . Dumper(\%cond);
393 #my $rel_delist_cnt = $rs_rel_delist->count;
394 if ( $if_not_submitted eq 'delete' ) {
396 #warn "\tdeleting related rows: $rel_delist_cnt\n";
397 $rs_rel_delist->delete;
399 elsif ( $if_not_submitted eq 'set_to_null' ) {
401 #warn "\tnullifying related rows: $rel_delist_cnt\n";
402 my %update = map { $_ => undef } @rel_cols;
403 $rs_rel_delist->update( \
%update );
406 elsif ($info->{attrs
}{accessor
} eq 'single'
407 || $info->{attrs
}{accessor
} eq 'filter' )
410 #warn "\tupdating rel '$name': $if_not_submitted\n";
412 if ( ref $updates ) {
413 if ( blessed
($updates) && $updates->isa('DBIx::Class::Row') ) {
414 $sub_object = $updates;
417 # for might_have relationship
418 elsif ( $info->{attrs
}{accessor
} eq 'single'
419 && defined $object->$name )
421 $sub_object = recursive_update
(
422 resultset
=> $related_resultset,
424 object
=> $object->$name
428 $sub_object = recursive_update
(
429 resultset
=> $related_resultset,
431 resolved
=> $resolved
436 $sub_object = $related_resultset->find($updates)
439 && ( exists $info->{attrs
}{join_type
}
440 && $info->{attrs
}{join_type
} eq 'LEFT' )
443 $object->set_from_related( $name, $sub_object )
447 && ( exists $info->{attrs
}{join_type
}
448 && $info->{attrs
}{join_type
} eq 'LEFT' )
452 $self->throw_exception(
453 "recursive_update doesn't now how to handle relationship '$name' with accessor "
454 . $info->{attrs
}{accessor
} );
459 my ( $self, $relation ) = @_;
460 my $rclass = $self->result_class;
462 # DBIx::Class::IntrospectableM2M
463 if ( $rclass->can('_m2m_metadata') ) {
464 return $rclass->_m2m_metadata->{$relation};
466 my $object = $self->new( {} );
467 if ( $object->can($relation)
468 and !$self->result_source->has_relationship($relation)
469 and $object->can( 'set_' . $relation ) )
477 my ( $self, $relation ) = @_;
478 my $rclass = $self->result_class;
480 # DBIx::Class::IntrospectableM2M
481 if ( $rclass->can('_m2m_metadata') ) {
482 return $self->result_source->related_source(
483 $rclass->_m2m_metadata->{$relation}{relation
} )
485 $rclass->_m2m_metadata->{$relation}{foreign_relation
} );
487 my $object = $self->new( {} );
488 my $r = $object->$relation;
489 return $r->result_source;
492 sub _delete_empty_auto_increment
{
493 my ( $self, $object ) = @_;
494 for my $col ( keys %{ $object->{_column_data
} } ) {
495 if ($object->result_source->column_info($col)->{is_auto_increment
}
496 and ( !defined $object->{_column_data
}{$col}
497 or $object->{_column_data
}{$col} eq '' )
500 delete $object->{_column_data
}{$col};
505 sub _get_pk_for_related
{
506 my ( $self, $relation ) = @_;
508 if ( $self->result_source->has_relationship($relation) ) {
509 $result_source = $self->result_source->related_source($relation);
513 if ( is_m2m
( $self, $relation ) ) {
514 $result_source = get_m2m_source
( $self, $relation );
516 return $result_source->primary_columns;
519 # This function determines wheter a relationship should be done before or
520 # after the row is inserted into the database
521 # relationships before: belongs_to
522 # relationships after: has_many, might_have and has_one
523 # true means before, false after
524 sub _master_relation_cond
{
525 my ( $self, $name ) = @_;
527 my $source = $self->result_source;
528 my $info = $source->relationship_info($name);
530 #warn "INFO: " . Dumper($info) . "\n";
532 # has_many rels are always after
534 if $info->{attrs
}->{accessor
} eq 'multi';
536 my @foreign_ids = _get_pk_for_related
( $self, $name );
538 #warn "IDS: " . join(', ', @foreign_ids) . "\n";
540 my $cond = $info->{cond
};
543 my ( $source, $cond, @foreign_ids ) = @_;
545 while ( my ( $f_key, $col ) = each %{$cond} ) {
547 # might_have is not master
549 $f_key =~ s/^foreign\.//;
550 if ( $source->column_info($col)->{is_auto_increment
} ) {
553 if ( any
{ $_ eq $f_key } @foreign_ids ) {
560 if ( ref $cond eq 'HASH' ) {
561 return _inner
( $source, $cond, @foreign_ids );
564 # arrayref of hashrefs
565 elsif ( ref $cond eq 'ARRAY' ) {
566 for my $new_cond (@$cond) {
567 return _inner
( $source, $new_cond, @foreign_ids );
571 $source->throw_exception(
572 "unhandled relation condition " . ref($cond) );
577 1; # Magic true value required at end of module
582 # The functional interface:
584 my $schema = MyDB::Schema->connect();
585 my $new_item = DBIx::Class::ResultSet::RecursiveUpdate::Functions::recursive_update(
586 resultset => $schema->resultset('User'),
591 title => "One Flew Over the Cuckoo's Nest"
595 unknown_params_ok => 1,
599 # As ResultSet subclass:
601 __PACKAGE__->load_namespaces( default_resultset_class => '+DBIx::Class::ResultSet::RecursiveUpdate' );
603 # in the Schema file (see t/lib/DBSchema.pm). Or appropriate 'use base' in the ResultSet classes.
605 my $user = $schema->resultset('User')->recursive_update({
609 title => "One Flew Over the Cuckoo's Nest"
613 unknown_params_ok => 1,
616 # You'll get a warning if you pass non-result specific data to
617 # recursive_update. See L</"Additional data in the updates hashref">
618 # for more information how to prevent this.
622 This is still experimental.
624 You can feed the ->create method of DBIx::Class with a recursive datastructure
625 and have the related records created. Unfortunately you cannot do a similar
626 thing with update_or_create. This module tries to fill that void until
627 L<DBIx::Class> has an api itself.
629 The functional interface can be used without modifications of the model,
630 for example by form processors like L<HTML::FormHandler::Model::DBIC>.
632 It is a base class for L<DBIx::Class::ResultSet>s providing the method
633 recursive_update which works just like update_or_create but can recursively
634 update or create result objects composed of multiple rows. All rows need to be
635 identified by primary keys so you need to provide them in the update structure
636 (unless they can be deduced from the parent row. For example a related row of
637 a belongs_to relationship). If any of the primary key columns are missing,
638 a new row will be created, with the expectation that the missing columns will
639 be filled by it (as in the case of auto_increment primary keys).
641 If the resultset itself stores an assignment for the primary key,
644 my $restricted_rs = $user_rs->search( { id => 1 } );
646 you need to inform recursive_update about the additional predicate with the fixed_fields attribute:
648 my $user = $restricted_rs->recursive_update( {
651 title => 'One Flew Over the Cuckoo's Nest'
656 fixed_fields => [ 'id' ],
660 For a many_to_many (pseudo) relation you can supply a list of primary keys
661 from the other table and it will link the record at hand to those and
662 only those records identified by them. This is convenient for handling web
663 forms with check boxes (or a select field with multiple choice) that lets you
664 update such (pseudo) relations.
666 For a description how to set up base classes for ResultSets see
667 L<DBIx::Class::Schema/load_namespaces>.
669 =head2 Additional data in the updates hashref
671 If you pass additional data to recursive_update which doesn't match a column
672 name, column accessor, relationship or many-to-many helper accessor, it will
673 throw a warning by default. To disable this behaviour you can set the
674 unknown_params_ok attribute to a true value.
676 The warning thrown is:
677 "No such column, relationship, many-to-many helper accessor or generic accessor '$key'"
679 When used by L<HTML::FormHandler::Model::DBIC> this can happen if you have
680 additional form fields that aren't relevant to the database but don't have the
681 noupdate attribute set to a true value.
683 NOTE: in a future version this behaviour will change and throw an exception
684 instead of a warning!
687 =head1 DESIGN CHOICES
689 Columns and relationships which are excluded from the updates hashref aren't
692 =head2 Treatment of belongs_to relations
694 In case the relationship is included but undefined in the updates hashref,
695 all columns forming the relationship will be set to null.
696 If not all of them are nullable, DBIx::Class will throw an error.
698 Updating the relationship:
700 my $dvd = $dvd_rs->recursive_update( {
705 Clearing the relationship (only works if cols are nullable!):
707 my $dvd = $dvd_rs->recursive_update( {
712 =head2 Treatment of might_have relationships
714 In case the relationship is included but undefined in the updates hashref,
715 all columns forming the relationship will be set to null.
717 Updating the relationship:
719 my $user = $user_rs->recursive_update( {
722 street => "101 Main Street",
728 Clearing the relationship:
730 my $user = $user_rs->recursive_update( {
735 =head2 Treatment of has_many relations
737 If a relationship key is included in the data structure with a value of undef
738 or an empty array, all existing related rows will be deleted, or their foreign
739 key columns will be set to null.
741 The exact behaviour depends on the nullability of the foreign key columns and
742 the value of the "if_not_submitted" parameter. The parameter defaults to
743 undefined which neither nullifies nor deletes.
745 When the array contains elements they are updated if they exist, created when
746 not and deleted if not included.
748 =head3 All foreign table columns are nullable
750 In this case recursive_update defaults to nullifying the foreign columns.
752 =head3 Not all foreign table columns are nullable
754 In this case recursive_update deletes the foreign rows.
756 Updating the relationship:
760 my $user = $user_rs->recursive_update( {
762 owned_dvds => [1, 2],
767 my $user = $user_rs->recursive_update( {
771 name => 'temp name 1',
774 name => 'temp name 2',
781 my $user = $user_rs->recursive_update( {
783 owned_dvds => [ $dvd1, $dvd2 ],
786 You can even mix them:
788 my $user = $user_rs->recursive_update( {
790 owned_dvds => [ 1, { id => 2 } ],
793 Clearing the relationship:
795 my $user = $user_rs->recursive_update( {
800 This is the same as passing an empty array:
802 my $user = $user_rs->recursive_update( {
807 =head2 Treatment of many-to-many pseudo relations
809 If a many-to-many accessor key is included in the data structure with a value
810 of undef or an empty array, all existing related rows are unlinked.
812 When the array contains elements they are updated if they exist, created when
813 not and deleted if not included.
815 See L</is_m2m> for many-to-many pseudo relationship detection.
817 Updating the relationship:
821 my $dvd = $dvd_rs->recursive_update( {
828 my $dvd = $dvd_rs->recursive_update( {
844 my $dvd = $dvd_rs->recursive_update( {
846 tags => [ $tag1, $tag2 ],
849 You can even mix them:
851 my $dvd = $dvd_rs->recursive_update( {
853 tags => [ 2, { id => 3 } ],
856 Clearing the relationship:
858 my $dvd = $dvd_rs->recursive_update( {
863 This is the same as passing an empty array:
865 my $dvd = $dvd_rs->recursive_update( {
875 =head2 recursive_update
877 The method that does the work here.
883 =item Arguments: $name
885 =item Return Value: true, if $name is a many to many pseudo-relationship
889 The function gets the information about m2m relations from
890 L<DBIx::Class::IntrospectableM2M>. If it isn't loaded in the ResultSource
891 class, the code relies on the fact:
893 if($object->can($name) and
894 !$object->result_source->has_relationship($name) and
895 $object->can( 'set_' . $name )
898 to identify a many to many pseudo relationship. In a similar ugly way the
899 ResultSource of that many to many pseudo relationship is detected.
901 So if you need many to many pseudo relationship support, it's strongly
902 recommended to load L<DBIx::Class::IntrospectableM2M> in your ResultSource
905 =head2 get_m2m_source
909 =item Arguments: $name
911 =item Return Value: $result_source
915 =head1 CONFIGURATION AND ENVIRONMENT
917 DBIx::Class::RecursiveUpdate requires no configuration files or environment variables.
923 optional but recommended:
924 DBIx::Class::IntrospectableM2M
926 =head1 INCOMPATIBILITIES
931 =head1 BUGS AND LIMITATIONS
933 The list of reported bugs can be viewed at L<http://rt.cpan.org/Public/Dist/Display.html?Name=DBIx-Class-ResultSet-RecursiveUpdate>.
935 Please report any bugs or feature requests to
936 C<bug-dbix-class-recursiveput@rt.cpan.org>, or through the web interface at
937 L<http://rt.cpan.org>.