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') ) {
69 if ( exists $updates->{id
} ) {
71 # warn "finding object by id " . $updates->{id} . "\n";
72 $object = $self->find( $updates->{id
}, { key
=> 'primary' } );
74 # warn "object not found by id\n"
75 # unless defined $object;
78 my %fixed_fields = map { $_ => 1 } @$fixed_fields
81 grep { !exists $updates->{$_} && !exists $fixed_fields{$_} }
82 $source->primary_columns;
83 if ( !$object && !scalar @missing ) {
85 # warn 'finding by: ' . Dumper( $updates ); use Data::Dumper;
86 $object = $self->find( $updates, { key
=> 'primary' } );
88 $updates = { %$updates, %$resolved };
90 grep { !exists $resolved->{$_} } @missing;
91 if ( !$object && !scalar @missing ) {
93 # warn 'finding by +resolved: ' . Dumper( $updates ); use Data::Dumper;
94 $object = $self->find( $updates, { key
=> 'primary' } );
97 $object = $self->new( {} )
98 unless defined $object;
100 # warn Dumper( $updates ); use Data::Dumper;
101 # direct column accessors
104 # relations that that should be done before the row is inserted into the
105 # database like belongs_to
108 # relations that that should be done after the row is inserted into the
109 # database like has_many, might_have and has_one
113 my %columns_by_accessor = _get_columns_by_accessor
($self);
115 # warn 'resolved: ' . Dumper( $resolved );
116 # warn 'updates: ' . Dumper( $updates ); use Data::Dumper;
117 # warn 'columns: ' . Dumper( \%columns_by_accessor );
118 for my $name ( keys %$updates ) {
121 if ( exists $columns_by_accessor{$name}
122 && !( $source->has_relationship($name)
123 && ref( $updates->{$name} ) ) )
126 #warn "$name is a column\n";
127 $columns{$name} = $updates->{$name};
132 if ( $source->has_relationship($name) ) {
133 if ( _master_relation_cond
( $self, $name ) ) {
135 #warn "$name is a pre-update rel\n";
136 $pre_updates{$name} = $updates->{$name};
141 #warn "$name is a post-update rel\n";
142 $post_updates{$name} = $updates->{$name};
147 # many-to-many helper accessors
148 if ( is_m2m
( $self, $name ) ) {
150 #warn "$name is a many-to-many helper accessor\n";
151 $m2m_accessors{$name} = $updates->{$name};
156 if ( $object->can($name) && not $source->has_relationship($name) ) {
158 #warn "$name is an accessor";
159 $other_methods{$name} = $updates->{$name};
165 # don't throw a warning instead of an exception to give users
166 # time to adapt to the new API
168 "No such column, relationship, many-to-many helper accessor or generic accessor '$name'"
169 ) unless $unknown_params_ok;
171 #$self->throw_exception(
172 # "No such column, relationship, many-to-many helper accessor or generic accessor '$name'"
176 # warn 'other: ' . Dumper( \%other_methods ); use Data::Dumper;
178 # first update columns and other accessors
179 # so that later related records can be found
180 for my $name ( keys %columns ) {
182 #warn "update col $name\n";
183 $object->$name( $columns{$name} );
185 for my $name ( keys %other_methods ) {
187 #warn "update other $name\n";
188 $object->$name( $other_methods{$name} );
190 for my $name ( keys %pre_updates ) {
192 #warn "pre_update $name\n";
193 _update_relation
( $self, $name, $pre_updates{$name}, $object,
197 # $self->_delete_empty_auto_increment($object);
198 # don't allow insert to recurse to related objects
199 # do the recursion ourselves
200 # $object->{_rel_in_storage} = 1;
201 #warn "CHANGED: " . $object->is_changed . "\n";
202 #warn "IN STOR: " . $object->in_storage . "\n";
203 $object->update_or_insert if $object->is_changed;
204 $object->discard_changes;
206 # updating many_to_many
207 for my $name ( keys %m2m_accessors ) {
208 my $value = $m2m_accessors{$name};
210 #warn "update m2m $name\n";
211 # TODO: only first pk col is used
212 my ($pk) = _get_pk_for_related
( $self, $name );
214 my $result_source = $object->$name->result_source;
216 if ( defined $value && ref $value eq 'ARRAY' ) {
217 @updates = @{$value};
219 elsif ( defined $value && !ref $value ) {
223 carp
"value of many-to-many rel '$name' must be an arrayref or scalar";
225 for my $elem (@updates) {
226 if ( blessed
($elem) && $elem->isa('DBIx::Class::Row') ) {
229 elsif ( ref $elem eq 'HASH' ) {
232 resultset
=> $result_source->resultset,
238 $result_source->resultset->find( { $pk => $elem } );
241 my $set_meth = 'set_' . $name;
242 $object->$set_meth( \
@rows );
244 for my $name ( keys %post_updates ) {
246 #warn "post_update $name\n";
247 _update_relation
( $self, $name, $post_updates{$name}, $object,
253 # returns DBIx::Class::ResultSource::column_info as a hash indexed by column accessor || name
254 sub _get_columns_by_accessor
{
256 my $source = $self->result_source;
258 for my $name ( $source->columns ) {
259 my $info = $source->column_info($name);
260 $info->{name
} = $name;
261 $columns{ $info->{accessor
} || $name } = $info;
266 # Arguments: $rs, $name, $updates, $row, $if_not_submitted
267 sub _update_relation
{
268 my ( $self, $name, $updates, $object, $if_not_submitted ) = @_;
270 # this should never happen because we're checking the paramters passed to
271 # recursive_update, but just to be sure...
272 $object->throw_exception("No such relationship '$name'")
273 unless $object->has_relationship($name);
275 #warn "_update_relation $name: OBJ: " . ref($object) . "\n";
277 my $info = $object->result_source->relationship_info($name);
279 # get a related resultset without a condition
280 my $related_resultset =
281 $self->related_resultset($name)->result_source->resultset;
283 if ( $self->result_source->can('_resolve_condition') ) {
285 $self->result_source->_resolve_condition( $info->{cond
}, $name,
289 $self->throw_exception(
290 "result_source must support _resolve_condition");
293 # warn "$name resolved: " . Dumper( $resolved ); use Data::Dumper;
295 if defined $DBIx::Class
::ResultSource
::UNRESOLVABLE_CONDITION
296 && $DBIx::Class
::ResultSource
::UNRESOLVABLE_CONDITION
299 my @rel_cols = keys %{ $info->{cond
} };
300 map {s/^foreign\.//} @rel_cols;
302 #warn "REL_COLS: " . Dumper(@rel_cols); use Data::Dumper;
303 #my $rel_col_cnt = scalar @rel_cols;
305 # find out if all related columns are nullable
306 my $all_fks_nullable = 1;
307 for my $rel_col (@rel_cols) {
308 $all_fks_nullable = 0
309 unless $related_resultset->result_source->column_info($rel_col)
313 $if_not_submitted = $all_fks_nullable ? 'nullify' : 'delete'
314 unless defined $if_not_submitted;
316 #warn "\tNULLABLE: $all_fks_nullable ACTION: $if_not_submitted\n";
318 #warn "RELINFO for $name: " . Dumper($info); use Data::Dumper;
320 # the only valid datatype for a has_many rels is an arrayref
321 if ( $info->{attrs
}{accessor
} eq 'multi' ) {
323 # handle undef like empty arrayref
325 unless defined $updates;
326 $self->throw_exception(
327 "data for has_many relationship '$name' must be an arrayref")
328 unless ref $updates eq 'ARRAY';
332 #warn "\tupdating has_many rel '$name' ($rel_col_cnt columns cols)\n";
333 for my $sub_updates ( @{$updates} ) {
334 my $sub_object = recursive_update
(
335 resultset
=> $related_resultset,
336 updates
=> $sub_updates,
337 resolved
=> $resolved
340 push @updated_objs, $sub_object;
343 #warn "\tcreated and updated related rows\n";
345 my @related_pks = $related_resultset->result_source->primary_columns;
347 my $rs_rel_delist = $object->$name;
349 # foreign table has a single pk column
350 if ( scalar @related_pks == 1 ) {
351 $rs_rel_delist = $rs_rel_delist->search_rs(
353 { -not_in
=> [ map ( $_->id, @updated_objs ) ] }
358 # foreign table has multiple pk columns
361 for my $obj (@updated_objs) {
363 for my $col (@related_pks) {
364 $cond_for_obj{$col} = $obj->get_column($col);
366 push @cond, \
%cond_for_obj;
369 # only limit resultset if there are related rows left
370 if ( scalar @cond ) {
372 $rs_rel_delist->search_rs( { -not => [@cond] } );
376 #warn "\tCOND: " . Dumper(\%cond);
377 #my $rel_delist_cnt = $rs_rel_delist->count;
378 if ( $if_not_submitted eq 'delete' ) {
380 #warn "\tdeleting related rows: $rel_delist_cnt\n";
381 $rs_rel_delist->delete;
383 elsif ( $if_not_submitted eq 'set_to_null' ) {
385 #warn "\tnullifying related rows: $rel_delist_cnt\n";
386 my %update = map { $_ => undef } @rel_cols;
387 $rs_rel_delist->update( \
%update );
390 elsif ($info->{attrs
}{accessor
} eq 'single'
391 || $info->{attrs
}{accessor
} eq 'filter' )
394 #warn "\tupdating rel '$name': $if_not_submitted\n";
396 if ( ref $updates ) {
397 if ( blessed
($updates) && $updates->isa('DBIx::Class::Row') ) {
398 $sub_object = $updates;
401 # for might_have relationship
402 elsif ( $info->{attrs
}{accessor
} eq 'single'
403 && defined $object->$name )
405 $sub_object = recursive_update
(
406 resultset
=> $related_resultset,
408 object
=> $object->$name
412 $sub_object = recursive_update
(
413 resultset
=> $related_resultset,
415 resolved
=> $resolved
420 $sub_object = $related_resultset->find($updates)
423 && ( exists $info->{attrs
}{join_type
}
424 && $info->{attrs
}{join_type
} eq 'LEFT' )
427 $object->set_from_related( $name, $sub_object )
431 && ( exists $info->{attrs
}{join_type
}
432 && $info->{attrs
}{join_type
} eq 'LEFT' )
436 $self->throw_exception(
437 "recursive_update doesn't now how to handle relationship '$name' with accessor "
438 . $info->{attrs
}{accessor
} );
443 my ( $self, $relation ) = @_;
444 my $rclass = $self->result_class;
446 # DBIx::Class::IntrospectableM2M
447 if ( $rclass->can('_m2m_metadata') ) {
448 return $rclass->_m2m_metadata->{$relation};
450 my $object = $self->new( {} );
451 if ( $object->can($relation)
452 and !$self->result_source->has_relationship($relation)
453 and $object->can( 'set_' . $relation ) )
461 my ( $self, $relation ) = @_;
462 my $rclass = $self->result_class;
464 # DBIx::Class::IntrospectableM2M
465 if ( $rclass->can('_m2m_metadata') ) {
466 return $self->result_source->related_source(
467 $rclass->_m2m_metadata->{$relation}{relation
} )
469 $rclass->_m2m_metadata->{$relation}{foreign_relation
} );
471 my $object = $self->new( {} );
472 my $r = $object->$relation;
473 return $r->result_source;
476 sub _delete_empty_auto_increment
{
477 my ( $self, $object ) = @_;
478 for my $col ( keys %{ $object->{_column_data
} } ) {
479 if ($object->result_source->column_info($col)->{is_auto_increment
}
480 and ( !defined $object->{_column_data
}{$col}
481 or $object->{_column_data
}{$col} eq '' )
484 delete $object->{_column_data
}{$col};
489 sub _get_pk_for_related
{
490 my ( $self, $relation ) = @_;
492 if ( $self->result_source->has_relationship($relation) ) {
493 $result_source = $self->result_source->related_source($relation);
497 if ( is_m2m
( $self, $relation ) ) {
498 $result_source = get_m2m_source
( $self, $relation );
500 return $result_source->primary_columns;
503 # This function determines wheter a relationship should be done before or
504 # after the row is inserted into the database
505 # relationships before: belongs_to
506 # relationships after: has_many, might_have and has_one
507 # true means before, false after
508 sub _master_relation_cond
{
509 my ( $self, $name ) = @_;
511 my $source = $self->result_source;
512 my $info = $source->relationship_info($name);
514 #warn "INFO: " . Dumper($info) . "\n";
516 # has_many rels are always after
518 if $info->{attrs
}->{accessor
} eq 'multi';
520 my @foreign_ids = _get_pk_for_related
( $self, $name );
522 #warn "IDS: " . join(', ', @foreign_ids) . "\n";
524 my $cond = $info->{cond
};
527 my ( $source, $cond, @foreign_ids ) = @_;
529 while ( my ( $f_key, $col ) = each %{$cond} ) {
531 # might_have is not master
533 $f_key =~ s/^foreign\.//;
534 if ( $source->column_info($col)->{is_auto_increment
} ) {
537 if ( any
{ $_ eq $f_key } @foreign_ids ) {
544 if ( ref $cond eq 'HASH' ) {
545 return _inner
( $source, $cond, @foreign_ids );
548 # arrayref of hashrefs
549 elsif ( ref $cond eq 'ARRAY' ) {
550 for my $new_cond (@$cond) {
551 return _inner
( $source, $new_cond, @foreign_ids );
555 $source->throw_exception(
556 "unhandled relation condition " . ref($cond) );
561 1; # Magic true value required at end of module
566 # The functional interface:
568 my $schema = MyDB::Schema->connect();
569 my $new_item = DBIx::Class::ResultSet::RecursiveUpdate::Functions::recursive_update(
570 resultset => $schema->resultset('User'),
575 title => "One Flew Over the Cuckoo's Nest"
579 unknown_params_ok => 1,
583 # As ResultSet subclass:
585 __PACKAGE__->load_namespaces( default_resultset_class => '+DBIx::Class::ResultSet::RecursiveUpdate' );
587 # in the Schema file (see t/lib/DBSchema.pm). Or appropriate 'use base' in the ResultSet classes.
589 my $user = $schema->resultset('User')->recursive_update({
593 title => "One Flew Over the Cuckoo's Nest"
597 unknown_params_ok => 1,
600 # You'll get a warning if you pass non-result specific data to
601 # recursive_update. See L</"Additional data in the updates hashref">
602 # for more information how to prevent this.
606 This is still experimental.
608 You can feed the ->create method of DBIx::Class with a recursive datastructure
609 and have the related records created. Unfortunately you cannot do a similar
610 thing with update_or_create. This module tries to fill that void until
611 L<DBIx::Class> has an api itself.
613 The functional interface can be used without modifications of the model,
614 for example by form processors like L<HTML::FormHandler::Model::DBIC>.
616 It is a base class for L<DBIx::Class::ResultSet>s providing the method
617 recursive_update which works just like update_or_create but can recursively
618 update or create result objects composed of multiple rows. All rows need to be
619 identified by primary keys so you need to provide them in the update structure
620 (unless they can be deduced from the parent row. For example a related row of
621 a belongs_to relationship). If any of the primary key columns are missing,
622 a new row will be created, with the expectation that the missing columns will
623 be filled by it (as in the case of auto_increment primary keys).
625 If the resultset itself stores an assignment for the primary key,
628 my $restricted_rs = $user_rs->search( { id => 1 } );
630 you need to inform recursive_update about the additional predicate with the fixed_fields attribute:
632 my $user = $restricted_rs->recursive_update( {
635 title => 'One Flew Over the Cuckoo's Nest'
640 fixed_fields => [ 'id' ],
644 For a many_to_many (pseudo) relation you can supply a list of primary keys
645 from the other table and it will link the record at hand to those and
646 only those records identified by them. This is convenient for handling web
647 forms with check boxes (or a select field with multiple choice) that lets you
648 update such (pseudo) relations.
650 For a description how to set up base classes for ResultSets see
651 L<DBIx::Class::Schema/load_namespaces>.
653 =head2 Additional data in the updates hashref
655 If you pass additional data to recursive_update which doesn't match a column
656 name, column accessor, relationship or many-to-many helper accessor, it will
657 throw a warning by default. To disable this behaviour you can set the
658 unknown_params_ok attribute to a true value.
660 The warning thrown is:
661 "No such column, relationship, many-to-many helper accessor or generic accessor '$key'"
663 When used by L<HTML::FormHandler::Model::DBIC> this can happen if you have
664 additional form fields that aren't relevant to the database but don't have the
665 noupdate attribute set to a true value.
667 NOTE: in a future version this behaviour will change and throw an exception
668 instead of a warning!
671 =head1 DESIGN CHOICES
673 Columns and relationships which are excluded from the updates hashref aren't
676 =head2 Treatment of belongs_to relations
678 In case the relationship is included but undefined in the updates hashref,
679 all columns forming the relationship will be set to null.
680 If not all of them are nullable, DBIx::Class will throw an error.
682 Updating the relationship:
684 my $dvd = $dvd_rs->recursive_update( {
689 Clearing the relationship (only works if cols are nullable!):
691 my $dvd = $dvd_rs->recursive_update( {
696 =head2 Treatment of might_have relationships
698 In case the relationship is included but undefined in the updates hashref,
699 all columns forming the relationship will be set to null.
701 Updating the relationship:
703 my $user = $user_rs->recursive_update( {
706 street => "101 Main Street",
712 Clearing the relationship:
714 my $user = $user_rs->recursive_update( {
719 =head2 Treatment of has_many relations
721 If a relationship key is included in the data structure with a value of undef
722 or an empty array, all existing related rows will be deleted, or their foreign
723 key columns will be set to null.
725 The exact behaviour depends on the nullability of the foreign key columns and
726 the value of the "if_not_submitted" parameter. The parameter defaults to
727 undefined which neither nullifies nor deletes.
729 When the array contains elements they are updated if they exist, created when
730 not and deleted if not included.
732 =head3 All foreign table columns are nullable
734 In this case recursive_update defaults to nullifying the foreign columns.
736 =head3 Not all foreign table columns are nullable
738 In this case recursive_update deletes the foreign rows.
740 Updating the relationship:
744 my $user = $user_rs->recursive_update( {
746 owned_dvds => [1, 2],
751 my $user = $user_rs->recursive_update( {
755 name => 'temp name 1',
758 name => 'temp name 2',
765 my $user = $user_rs->recursive_update( {
767 owned_dvds => [ $dvd1, $dvd2 ],
770 You can even mix them:
772 my $user = $user_rs->recursive_update( {
774 owned_dvds => [ 1, { id => 2 } ],
777 Clearing the relationship:
779 my $user = $user_rs->recursive_update( {
784 This is the same as passing an empty array:
786 my $user = $user_rs->recursive_update( {
791 =head2 Treatment of many-to-many pseudo relations
793 If a many-to-many accessor key is included in the data structure with a value
794 of undef or an empty array, all existing related rows are unlinked.
796 When the array contains elements they are updated if they exist, created when
797 not and deleted if not included.
799 See L</is_m2m> for many-to-many pseudo relationship detection.
801 Updating the relationship:
805 my $dvd = $dvd_rs->recursive_update( {
812 my $dvd = $dvd_rs->recursive_update( {
828 my $dvd = $dvd_rs->recursive_update( {
830 tags => [ $tag1, $tag2 ],
833 You can even mix them:
835 my $dvd = $dvd_rs->recursive_update( {
837 tags => [ 2, { id => 3 } ],
840 Clearing the relationship:
842 my $dvd = $dvd_rs->recursive_update( {
847 This is the same as passing an empty array:
849 my $dvd = $dvd_rs->recursive_update( {
859 =head2 recursive_update
861 The method that does the work here.
867 =item Arguments: $name
869 =item Return Value: true, if $name is a many to many pseudo-relationship
873 The function gets the information about m2m relations from
874 L<DBIx::Class::IntrospectableM2M>. If it isn't loaded in the ResultSource
875 class, the code relies on the fact:
877 if($object->can($name) and
878 !$object->result_source->has_relationship($name) and
879 $object->can( 'set_' . $name )
882 to identify a many to many pseudo relationship. In a similar ugly way the
883 ResultSource of that many to many pseudo relationship is detected.
885 So if you need many to many pseudo relationship support, it's strongly
886 recommended to load L<DBIx::Class::IntrospectableM2M> in your ResultSource
889 =head2 get_m2m_source
893 =item Arguments: $name
895 =item Return Value: $result_source
899 =head1 CONFIGURATION AND ENVIRONMENT
901 DBIx::Class::RecursiveUpdate requires no configuration files or environment variables.
907 optional but recommended:
908 DBIx::Class::IntrospectableM2M
910 =head1 INCOMPATIBILITIES
915 =head1 BUGS AND LIMITATIONS
917 The list of reported bugs can be viewed at L<http://rt.cpan.org/Public/Dist/Display.html?Name=DBIx-Class-ResultSet-RecursiveUpdate>.
919 Please report any bugs or feature requests to
920 C<bug-dbix-class-recursiveput@rt.cpan.org>, or through the web interface at
921 L<http://rt.cpan.org>.