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 /;
41 sub recursive_update
{
43 my ( $self, $updates, $fixed_fields, $object, $resolved,
44 $if_not_submitted, $unknown_params_ok )
46 qw
/resultset updates fixed_fields object resolved if_not_submitted unknown_params_ok/
50 my $source = $self->result_source;
52 croak
"first parameter needs to be defined"
53 unless defined $updates;
55 croak
"first parameter needs to be a hashref"
56 unless ref($updates) eq 'HASH';
58 # warn 'entering: ' . $source->from();
59 croak
'fixed fields needs to be an arrayref'
60 if defined $fixed_fields && ref $fixed_fields ne 'ARRAY';
62 # always warn about additional parameters if storage debugging is enabled
63 $unknown_params_ok = 0
64 if $source->storage->debug;
66 if ( blessed
($updates) && $updates->isa('DBIx::Class::Row') ) {
70 if ( !defined $object && exists $updates->{id
} ) {
72 # warn "finding object by id " . $updates->{id} . "\n";
73 $object = $self->find( $updates->{id
}, { key
=> 'primary' } );
75 # warn "object not found by id\n"
76 # unless defined $object;
79 my %fixed_fields = map { $_ => 1 } @$fixed_fields
82 grep { !exists $updates->{$_} && !exists $fixed_fields{$_} }
83 $source->primary_columns;
85 # warn "MISSING: " . join(', ', @missing) . "\n";
86 if ( !defined $object && scalar @missing == 0 ) {
88 # warn 'finding by: ' . Dumper( $updates ); use Data::Dumper;
89 $object = $self->find( $updates, { key
=> 'primary' } );
91 $updates = { %$updates, %$resolved };
92 @missing = grep { !exists $resolved->{$_} } @missing;
93 if ( !defined $object && scalar @missing == 0 ) {
95 # warn 'finding by +resolved: ' . Dumper( $updates ); use Data::Dumper;
96 $object = $self->find( $updates, { key
=> 'primary' } );
99 $object = $self->new( {} )
100 unless defined $object;
102 # warn Dumper( $updates ); use Data::Dumper;
103 # direct column accessors
106 # relations that that should be done before the row is inserted into the
107 # database like belongs_to
110 # relations that that should be done after the row is inserted into the
111 # database like has_many, might_have and has_one
115 my %columns_by_accessor = _get_columns_by_accessor
($self);
117 # warn 'resolved: ' . Dumper( $resolved );
118 # warn 'updates: ' . Dumper( $updates ); use Data::Dumper;
119 # warn 'columns: ' . Dumper( \%columns_by_accessor );
120 for my $name ( keys %$updates ) {
123 if ( exists $columns_by_accessor{$name}
124 && !( $source->has_relationship($name)
125 && ref( $updates->{$name} ) ) )
128 #warn "$name is a column\n";
129 $columns{$name} = $updates->{$name};
134 if ( $source->has_relationship($name) ) {
135 if ( _master_relation_cond
( $self, $name ) ) {
137 #warn "$name is a pre-update rel\n";
138 $pre_updates{$name} = $updates->{$name};
143 #warn "$name is a post-update rel\n";
144 $post_updates{$name} = $updates->{$name};
149 # many-to-many helper accessors
150 if ( is_m2m
( $self, $name ) ) {
152 #warn "$name is a many-to-many helper accessor\n";
153 $m2m_accessors{$name} = $updates->{$name};
158 if ( $object->can($name) && not $source->has_relationship($name) ) {
160 #warn "$name is an accessor";
161 $other_methods{$name} = $updates->{$name};
167 # don't throw a warning instead of an exception to give users
168 # time to adapt to the new API
170 "No such column, relationship, many-to-many helper accessor or generic accessor '$name'"
171 ) unless $unknown_params_ok;
173 #$self->throw_exception(
174 # "No such column, relationship, many-to-many helper accessor or generic accessor '$name'"
178 # warn 'other: ' . Dumper( \%other_methods ); use Data::Dumper;
180 # first update columns and other accessors
181 # so that later related records can be found
182 for my $name ( keys %columns ) {
184 #warn "update col $name\n";
185 $object->$name( $columns{$name} );
187 for my $name ( keys %other_methods ) {
189 #warn "update other $name\n";
190 $object->$name( $other_methods{$name} );
192 for my $name ( keys %pre_updates ) {
194 #warn "pre_update $name\n";
195 _update_relation
( $self, $name, $pre_updates{$name}, $object,
199 # $self->_delete_empty_auto_increment($object);
200 # don't allow insert to recurse to related objects
201 # do the recursion ourselves
202 # $object->{_rel_in_storage} = 1;
203 #warn "CHANGED: " . $object->is_changed . "\n";
204 #warn "IN STOR: " . $object->in_storage . "\n";
205 $object->update_or_insert if $object->is_changed;
206 $object->discard_changes;
208 # updating many_to_many
209 for my $name ( keys %m2m_accessors ) {
210 my $value = $m2m_accessors{$name};
212 #warn "update m2m $name\n";
213 # TODO: only first pk col is used
214 my ($pk) = _get_pk_for_related
( $self, $name );
216 my $result_source = $object->$name->result_source;
218 if ( defined $value && ref $value eq 'ARRAY' ) {
219 @updates = @{$value};
221 elsif ( defined $value && !ref $value ) {
224 elsif ( defined $value ) {
226 "value of many-to-many rel '$name' must be an arrayref or scalar: $value";
228 for my $elem (@updates) {
229 if ( blessed
($elem) && $elem->isa('DBIx::Class::Row') ) {
232 elsif ( ref $elem eq 'HASH' ) {
235 resultset
=> $result_source->resultset,
241 $result_source->resultset->find( { $pk => $elem } );
244 my $set_meth = 'set_' . $name;
245 $object->$set_meth( \
@rows );
247 for my $name ( keys %post_updates ) {
249 #warn "post_update $name\n";
250 _update_relation
( $self, $name, $post_updates{$name}, $object,
256 # returns DBIx::Class::ResultSource::column_info as a hash indexed by column accessor || name
257 sub _get_columns_by_accessor
{
259 my $source = $self->result_source;
261 for my $name ( $source->columns ) {
262 my $info = $source->column_info($name);
263 $info->{name
} = $name;
264 $columns{ $info->{accessor
} || $name } = $info;
269 # Arguments: $rs, $name, $updates, $row, $if_not_submitted
270 sub _update_relation
{
271 my ( $self, $name, $updates, $object, $if_not_submitted ) = @_;
273 # this should never happen because we're checking the paramters passed to
274 # recursive_update, but just to be sure...
275 $object->throw_exception("No such relationship '$name'")
276 unless $object->has_relationship($name);
278 #warn "_update_relation $name: OBJ: " . ref($object) . "\n";
280 my $info = $object->result_source->relationship_info($name);
282 # get a related resultset without a condition
283 my $related_resultset =
284 $self->related_resultset($name)->result_source->resultset;
286 if ( $self->result_source->can('_resolve_condition') ) {
288 $self->result_source->_resolve_condition( $info->{cond
}, $name,
292 $self->throw_exception(
293 "result_source must support _resolve_condition");
296 # warn "$name resolved: " . Dumper( $resolved ); use Data::Dumper;
298 if defined $DBIx::Class
::ResultSource
::UNRESOLVABLE_CONDITION
299 && $DBIx::Class
::ResultSource
::UNRESOLVABLE_CONDITION
302 #warn "RESOLVED: " . Dumper($resolved); use Data::Dumper;
304 my @rel_cols = keys %{ $info->{cond
} };
305 map {s/^foreign\.//} @rel_cols;
307 #warn "REL_COLS: " . Dumper(@rel_cols); use Data::Dumper;
308 #my $rel_col_cnt = scalar @rel_cols;
310 # find out if all related columns are nullable
311 my $all_fks_nullable = 1;
312 for my $rel_col (@rel_cols) {
313 $all_fks_nullable = 0
314 unless $related_resultset->result_source->column_info($rel_col)
318 $if_not_submitted = $all_fks_nullable ? 'nullify' : 'delete'
319 unless defined $if_not_submitted;
321 #warn "\tNULLABLE: $all_fks_nullable ACTION: $if_not_submitted\n";
323 #warn "RELINFO for $name: " . Dumper($info); use Data::Dumper;
325 # the only valid datatype for a has_many rels is an arrayref
326 if ( $info->{attrs
}{accessor
} eq 'multi' ) {
328 # handle undef like empty arrayref
330 unless defined $updates;
331 $self->throw_exception(
332 "data for has_many relationship '$name' must be an arrayref")
333 unless ref $updates eq 'ARRAY';
337 #warn "\tupdating has_many rel '$name' ($rel_col_cnt columns cols)\n";
338 for my $sub_updates ( @{$updates} ) {
339 my $sub_object = recursive_update
(
340 resultset
=> $related_resultset,
341 updates
=> $sub_updates,
342 resolved
=> $resolved
345 push @updated_objs, $sub_object;
348 #warn "\tcreated and updated related rows\n";
350 my @related_pks = $related_resultset->result_source->primary_columns;
352 my $rs_rel_delist = $object->$name;
354 # foreign table has a single pk column
355 if ( scalar @related_pks == 1 ) {
356 $rs_rel_delist = $rs_rel_delist->search_rs(
358 { -not_in
=> [ map ( $_->id, @updated_objs ) ] }
363 # foreign table has multiple pk columns
366 for my $obj (@updated_objs) {
368 for my $col (@related_pks) {
369 $cond_for_obj{$col} = $obj->get_column($col);
371 push @cond, \
%cond_for_obj;
374 # only limit resultset if there are related rows left
375 if ( scalar @cond ) {
377 $rs_rel_delist->search_rs( { -not => [@cond] } );
381 #warn "\tCOND: " . Dumper(\%cond);
382 #my $rel_delist_cnt = $rs_rel_delist->count;
383 if ( $if_not_submitted eq 'delete' ) {
385 #warn "\tdeleting related rows: $rel_delist_cnt\n";
386 $rs_rel_delist->delete;
388 elsif ( $if_not_submitted eq 'set_to_null' ) {
390 #warn "\tnullifying related rows: $rel_delist_cnt\n";
391 my %update = map { $_ => undef } @rel_cols;
392 $rs_rel_delist->update( \
%update );
395 elsif ($info->{attrs
}{accessor
} eq 'single'
396 || $info->{attrs
}{accessor
} eq 'filter' )
399 #warn "\tupdating rel '$name': $if_not_submitted\n";
401 if ( ref $updates ) {
402 if ( blessed
($updates) && $updates->isa('DBIx::Class::Row') ) {
403 $sub_object = $updates;
406 # for might_have relationship
407 elsif ( $info->{attrs
}{accessor
} eq 'single'
408 && defined $object->$name )
410 $sub_object = recursive_update
(
411 resultset
=> $related_resultset,
413 object
=> $object->$name
417 $sub_object = recursive_update
(
418 resultset
=> $related_resultset,
420 resolved
=> $resolved
425 $sub_object = $related_resultset->find($updates)
428 && ( exists $info->{attrs
}{join_type
}
429 && $info->{attrs
}{join_type
} eq 'LEFT' )
432 $object->set_from_related( $name, $sub_object )
436 && ( exists $info->{attrs
}{join_type
}
437 && $info->{attrs
}{join_type
} eq 'LEFT' )
441 $self->throw_exception(
442 "recursive_update doesn't now how to handle relationship '$name' with accessor "
443 . $info->{attrs
}{accessor
} );
448 my ( $self, $relation ) = @_;
449 my $rclass = $self->result_class;
451 # DBIx::Class::IntrospectableM2M
452 if ( $rclass->can('_m2m_metadata') ) {
453 return $rclass->_m2m_metadata->{$relation};
455 my $object = $self->new( {} );
456 if ( $object->can($relation)
457 and !$self->result_source->has_relationship($relation)
458 and $object->can( 'set_' . $relation ) )
466 my ( $self, $relation ) = @_;
467 my $rclass = $self->result_class;
469 # DBIx::Class::IntrospectableM2M
470 if ( $rclass->can('_m2m_metadata') ) {
471 return $self->result_source->related_source(
472 $rclass->_m2m_metadata->{$relation}{relation
} )
474 $rclass->_m2m_metadata->{$relation}{foreign_relation
} );
476 my $object = $self->new( {} );
477 my $r = $object->$relation;
478 return $r->result_source;
481 sub _delete_empty_auto_increment
{
482 my ( $self, $object ) = @_;
483 for my $col ( keys %{ $object->{_column_data
} } ) {
484 if ($object->result_source->column_info($col)->{is_auto_increment
}
485 and ( !defined $object->{_column_data
}{$col}
486 or $object->{_column_data
}{$col} eq '' )
489 delete $object->{_column_data
}{$col};
494 sub _get_pk_for_related
{
495 my ( $self, $relation ) = @_;
497 if ( $self->result_source->has_relationship($relation) ) {
498 $result_source = $self->result_source->related_source($relation);
502 if ( is_m2m
( $self, $relation ) ) {
503 $result_source = get_m2m_source
( $self, $relation );
505 return $result_source->primary_columns;
508 # This function determines wheter a relationship should be done before or
509 # after the row is inserted into the database
510 # relationships before: belongs_to
511 # relationships after: has_many, might_have and has_one
512 # true means before, false after
513 sub _master_relation_cond
{
514 my ( $self, $name ) = @_;
516 my $source = $self->result_source;
517 my $info = $source->relationship_info($name);
519 #warn "INFO: " . Dumper($info) . "\n";
521 # has_many rels are always after
523 if $info->{attrs
}->{accessor
} eq 'multi';
525 my @foreign_ids = _get_pk_for_related
( $self, $name );
527 #warn "IDS: " . join(', ', @foreign_ids) . "\n";
529 my $cond = $info->{cond
};
532 my ( $source, $cond, @foreign_ids ) = @_;
534 while ( my ( $f_key, $col ) = each %{$cond} ) {
536 # might_have is not master
538 $f_key =~ s/^foreign\.//;
539 if ( $source->column_info($col)->{is_auto_increment
} ) {
542 if ( any
{ $_ eq $f_key } @foreign_ids ) {
549 if ( ref $cond eq 'HASH' ) {
550 return _inner
( $source, $cond, @foreign_ids );
553 # arrayref of hashrefs
554 elsif ( ref $cond eq 'ARRAY' ) {
555 for my $new_cond (@$cond) {
556 return _inner
( $source, $new_cond, @foreign_ids );
560 $source->throw_exception(
561 "unhandled relation condition " . ref($cond) );
566 1; # Magic true value required at end of module
571 # The functional interface:
573 my $schema = MyDB::Schema->connect();
574 my $new_item = DBIx::Class::ResultSet::RecursiveUpdate::Functions::recursive_update(
575 resultset => $schema->resultset('User'),
580 title => "One Flew Over the Cuckoo's Nest"
584 unknown_params_ok => 1,
588 # As ResultSet subclass:
590 __PACKAGE__->load_namespaces( default_resultset_class => '+DBIx::Class::ResultSet::RecursiveUpdate' );
592 # in the Schema file (see t/lib/DBSchema.pm). Or appropriate 'use base' in the ResultSet classes.
594 my $user = $schema->resultset('User')->recursive_update({
598 title => "One Flew Over the Cuckoo's Nest"
602 unknown_params_ok => 1,
605 # You'll get a warning if you pass non-result specific data to
606 # recursive_update. See L</"Additional data in the updates hashref">
607 # for more information how to prevent this.
611 This is still experimental.
613 You can feed the ->create method of DBIx::Class with a recursive datastructure
614 and have the related records created. Unfortunately you cannot do a similar
615 thing with update_or_create. This module tries to fill that void until
616 L<DBIx::Class> has an api itself.
618 The functional interface can be used without modifications of the model,
619 for example by form processors like L<HTML::FormHandler::Model::DBIC>.
621 It is a base class for L<DBIx::Class::ResultSet>s providing the method
622 recursive_update which works just like update_or_create but can recursively
623 update or create result objects composed of multiple rows. All rows need to be
624 identified by primary keys so you need to provide them in the update structure
625 (unless they can be deduced from the parent row. For example a related row of
626 a belongs_to relationship). If any of the primary key columns are missing,
627 a new row will be created, with the expectation that the missing columns will
628 be filled by it (as in the case of auto_increment primary keys).
630 If the resultset itself stores an assignment for the primary key,
633 my $restricted_rs = $user_rs->search( { id => 1 } );
635 you need to inform recursive_update about the additional predicate with the fixed_fields attribute:
637 my $user = $restricted_rs->recursive_update( {
640 title => 'One Flew Over the Cuckoo's Nest'
645 fixed_fields => [ 'id' ],
649 For a many_to_many (pseudo) relation you can supply a list of primary keys
650 from the other table and it will link the record at hand to those and
651 only those records identified by them. This is convenient for handling web
652 forms with check boxes (or a select field with multiple choice) that lets you
653 update such (pseudo) relations.
655 For a description how to set up base classes for ResultSets see
656 L<DBIx::Class::Schema/load_namespaces>.
658 =head2 Additional data in the updates hashref
660 If you pass additional data to recursive_update which doesn't match a column
661 name, column accessor, relationship or many-to-many helper accessor, it will
662 throw a warning by default. To disable this behaviour you can set the
663 unknown_params_ok attribute to a true value.
665 The warning thrown is:
666 "No such column, relationship, many-to-many helper accessor or generic accessor '$key'"
668 When used by L<HTML::FormHandler::Model::DBIC> this can happen if you have
669 additional form fields that aren't relevant to the database but don't have the
670 noupdate attribute set to a true value.
672 NOTE: in a future version this behaviour will change and throw an exception
673 instead of a warning!
676 =head1 DESIGN CHOICES
678 Columns and relationships which are excluded from the updates hashref aren't
681 =head2 Treatment of belongs_to relations
683 In case the relationship is included but undefined in the updates hashref,
684 all columns forming the relationship will be set to null.
685 If not all of them are nullable, DBIx::Class will throw an error.
687 Updating the relationship:
689 my $dvd = $dvd_rs->recursive_update( {
694 Clearing the relationship (only works if cols are nullable!):
696 my $dvd = $dvd_rs->recursive_update( {
701 =head2 Treatment of might_have relationships
703 In case the relationship is included but undefined in the updates hashref,
704 all columns forming the relationship will be set to null.
706 Updating the relationship:
708 my $user = $user_rs->recursive_update( {
711 street => "101 Main Street",
717 Clearing the relationship:
719 my $user = $user_rs->recursive_update( {
724 =head2 Treatment of has_many relations
726 If a relationship key is included in the data structure with a value of undef
727 or an empty array, all existing related rows will be deleted, or their foreign
728 key columns will be set to null.
730 The exact behaviour depends on the nullability of the foreign key columns and
731 the value of the "if_not_submitted" parameter. The parameter defaults to
732 undefined which neither nullifies nor deletes.
734 When the array contains elements they are updated if they exist, created when
735 not and deleted if not included.
737 =head3 All foreign table columns are nullable
739 In this case recursive_update defaults to nullifying the foreign columns.
741 =head3 Not all foreign table columns are nullable
743 In this case recursive_update deletes the foreign rows.
745 Updating the relationship:
749 my $user = $user_rs->recursive_update( {
751 owned_dvds => [1, 2],
756 my $user = $user_rs->recursive_update( {
760 name => 'temp name 1',
763 name => 'temp name 2',
770 my $user = $user_rs->recursive_update( {
772 owned_dvds => [ $dvd1, $dvd2 ],
775 You can even mix them:
777 my $user = $user_rs->recursive_update( {
779 owned_dvds => [ 1, { id => 2 } ],
782 Clearing the relationship:
784 my $user = $user_rs->recursive_update( {
789 This is the same as passing an empty array:
791 my $user = $user_rs->recursive_update( {
796 =head2 Treatment of many-to-many pseudo relations
798 If a many-to-many accessor key is included in the data structure with a value
799 of undef or an empty array, all existing related rows are unlinked.
801 When the array contains elements they are updated if they exist, created when
802 not and deleted if not included.
804 See L</is_m2m> for many-to-many pseudo relationship detection.
806 Updating the relationship:
810 my $dvd = $dvd_rs->recursive_update( {
817 my $dvd = $dvd_rs->recursive_update( {
833 my $dvd = $dvd_rs->recursive_update( {
835 tags => [ $tag1, $tag2 ],
838 You can even mix them:
840 my $dvd = $dvd_rs->recursive_update( {
842 tags => [ 2, { id => 3 } ],
845 Clearing the relationship:
847 my $dvd = $dvd_rs->recursive_update( {
852 This is the same as passing an empty array:
854 my $dvd = $dvd_rs->recursive_update( {
864 =head2 recursive_update
866 The method that does the work here.
872 =item Arguments: $name
874 =item Return Value: true, if $name is a many to many pseudo-relationship
878 The function gets the information about m2m relations from
879 L<DBIx::Class::IntrospectableM2M>. If it isn't loaded in the ResultSource
880 class, the code relies on the fact:
882 if($object->can($name) and
883 !$object->result_source->has_relationship($name) and
884 $object->can( 'set_' . $name )
887 to identify a many to many pseudo relationship. In a similar ugly way the
888 ResultSource of that many to many pseudo relationship is detected.
890 So if you need many to many pseudo relationship support, it's strongly
891 recommended to load L<DBIx::Class::IntrospectableM2M> in your ResultSource
894 =head2 get_m2m_source
898 =item Arguments: $name
900 =item Return Value: $result_source
904 =head1 CONFIGURATION AND ENVIRONMENT
906 DBIx::Class::RecursiveUpdate requires no configuration files or environment variables.
912 optional but recommended:
913 DBIx::Class::IntrospectableM2M
915 =head1 INCOMPATIBILITIES
920 =head1 BUGS AND LIMITATIONS
922 The list of reported bugs can be viewed at L<http://rt.cpan.org/Public/Dist/Display.html?Name=DBIx-Class-ResultSet-RecursiveUpdate>.
924 Please report any bugs or feature requests to
925 C<bug-dbix-class-recursiveput@rt.cpan.org>, or through the web interface at
926 L<http://rt.cpan.org>.