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 # warn 'entering: ' . $source->from();
53 carp
'fixed fields needs to be an array ref'
54 if defined $fixed_fields && ref $fixed_fields ne 'ARRAY';
56 if ( blessed
($updates) && $updates->isa('DBIx::Class::Row') ) {
59 if ( exists $updates->{id
} ) {
60 # warn "finding object by id " . $updates->{id} . "\n";
61 $object = $self->find( $updates->{id
}, { key
=> 'primary' } );
62 # warn "object not found by id\n"
63 # unless defined $object;
66 my %fixed_fields = map { $_ => 1 } @$fixed_fields
69 grep { !exists $updates->{$_} && !exists $fixed_fields{$_} }
70 $source->primary_columns;
71 if ( !$object && !scalar @missing ) {
73 # warn 'finding by: ' . Dumper( $updates ); use Data::Dumper;
74 $object = $self->find( $updates, { key
=> 'primary' } );
76 $updates = { %$updates, %$resolved };
78 grep { !exists $resolved->{$_} } @missing;
79 if ( !$object && !scalar @missing ) {
81 # warn 'finding by +resolved: ' . Dumper( $updates ); use Data::Dumper;
82 $object = $self->find( $updates, { key
=> 'primary' } );
84 $object ||= $self->new( {} );
86 # warn Dumper( $updates ); use Data::Dumper;
87 # direct column accessors
90 # relations that that should be done before the row is inserted into the
91 # database like belongs_to
94 # relations that that should be done after the row is inserted into the
95 # database like has_many, might_have and has_one
98 my %columns_by_accessor = _get_columns_by_accessor
($self);
100 # warn 'resolved: ' . Dumper( $resolved );
101 # warn 'updates: ' . Dumper( $updates ); use Data::Dumper;
102 # warn 'columns: ' . Dumper( \%columns_by_accessor );
103 for my $name ( keys %$updates ) {
105 if ( exists $columns_by_accessor{$name}
106 && !( $source->has_relationship($name)
107 && ref( $updates->{$name} ) ) )
110 #warn "$name is a column\n";
111 $columns{$name} = $updates->{$name};
116 if ( $source->has_relationship($name) ) {
117 if ( _master_relation_cond
( $self, $name ) ) {
119 #warn "$name is a pre-update rel\n";
120 $pre_updates{$name} = $updates->{$name};
125 #warn "$name is a post-update rel\n";
126 $post_updates{$name} = $updates->{$name};
131 # many-to-many helper accessors
132 if ( is_m2m
( $self, $name ) ) {
134 #warn "$name is a many-to-many helper accessor\n";
135 $other_methods{$name} = $updates->{$name};
140 if ( $object->can($name) && not $source->has_relationship($name) ) {
142 #warn "$name is an accessor";
143 $other_methods{$name} = $updates->{$name};
149 # don't throw a warning instead of an exception to give users
150 # time to adapt to the new API
152 "No such column, relationship, many-to-many helper accessor or generic accessor '$name'"
153 ) unless $unknown_params_ok;
155 #$self->throw_exception(
156 # "No such column, relationship, many-to-many helper accessor or generic accessor '$name'"
160 # warn 'other: ' . Dumper( \%other_methods ); use Data::Dumper;
162 # first update columns and other accessors
163 # so that later related records can be found
164 for my $name ( keys %columns ) {
166 #warn "update col $name\n";
167 $object->$name( $columns{$name} );
169 for my $name ( keys %other_methods ) {
171 #warn "update other $name\n";
172 $object->$name( $updates->{$name} );
174 for my $name ( keys %pre_updates ) {
176 #warn "pre_update $name\n";
177 _update_relation
( $self, $name, $pre_updates{$name}, $object,
181 # $self->_delete_empty_auto_increment($object);
182 # don't allow insert to recurse to related objects
183 # do the recursion ourselves
184 # $object->{_rel_in_storage} = 1;
185 #warn "CHANGED: " . $object->is_changed . "\n":
186 #warn "IN STOR: " . $object->in_storage . "\n";
187 $object->update_or_insert if $object->is_changed;
188 $object->discard_changes;
190 # updating many_to_many
191 for my $name ( keys %$updates ) {
192 next if exists $columns{$name};
193 my $value = $updates->{$name};
195 if ( is_m2m
( $self, $name ) ) {
197 #warn "update m2m $name\n";
198 my ($pk) = _get_pk_for_related
( $self, $name );
200 my $result_source = $object->$name->result_source;
202 if ( !defined $value ) {
205 elsif ( ref $value ) {
206 @updates = @{$value};
211 for my $elem (@updates) {
215 resultset
=> $result_source->resultset,
221 $result_source->resultset->find( { $pk => $elem } );
224 my $set_meth = 'set_' . $name;
225 $object->$set_meth( \
@rows );
228 for my $name ( keys %post_updates ) {
230 #warn "post_update $name\n";
231 _update_relation
( $self, $name, $post_updates{$name}, $object,
237 # returns DBIx::Class::ResultSource::column_info as a hash indexed by column accessor || name
238 sub _get_columns_by_accessor
{
240 my $source = $self->result_source;
242 for my $name ( $source->columns ) {
243 my $info = $source->column_info($name);
244 $info->{name
} = $name;
245 $columns{ $info->{accessor
} || $name } = $info;
250 # Arguments: $rs, $name, $updates, $row, $if_not_submitted
251 sub _update_relation
{
252 my ( $self, $name, $updates, $object, $if_not_submitted ) = @_;
254 # this should never happen because we're checking the paramters passed to
255 # recursive_update, but just to be sure...
256 $object->throw_exception("No such relationship '$name'")
257 unless $object->has_relationship($name);
259 #warn "_update_relation $name: OBJ: " . ref($object) . "\n";
261 my $info = $object->result_source->relationship_info($name);
263 # get a related resultset without a condition
264 my $related_resultset =
265 $self->related_resultset($name)->result_source->resultset;
267 if ( $self->result_source->can('_resolve_condition') ) {
269 $self->result_source->_resolve_condition( $info->{cond
}, $name,
273 $self->throw_exception(
274 "result_source must support _resolve_condition");
277 # warn "$name resolved: " . Dumper( $resolved ); use Data::Dumper;
279 if defined $DBIx::Class
::ResultSource
::UNRESOLVABLE_CONDITION
280 && $DBIx::Class
::ResultSource
::UNRESOLVABLE_CONDITION
283 my @rel_cols = keys %{ $info->{cond
} };
284 map {s/^foreign\.//} @rel_cols;
286 #warn "REL_COLS: " . Dumper(@rel_cols); use Data::Dumper;
287 #my $rel_col_cnt = scalar @rel_cols;
289 # find out if all related columns are nullable
290 my $all_fks_nullable = 1;
291 for my $rel_col (@rel_cols) {
292 $all_fks_nullable = 0
293 unless $related_resultset->result_source->column_info($rel_col)
297 $if_not_submitted = $all_fks_nullable ? 'nullify' : 'delete'
298 unless defined $if_not_submitted;
300 #warn "\tNULLABLE: $all_fks_nullable ACTION: $if_not_submitted\n";
302 #warn "RELINFO for $name: " . Dumper($info); use Data::Dumper;
304 # the only valid datatype for a has_many rels is an arrayref
305 if ( $info->{attrs
}{accessor
} eq 'multi' ) {
307 # handle undef like empty arrayref
309 unless defined $updates;
310 $self->throw_exception(
311 "data for has_many relationship '$name' must be an arrayref")
312 unless ref $updates eq 'ARRAY';
316 #warn "\tupdating has_many rel '$name' ($rel_col_cnt columns cols)\n";
317 for my $sub_updates ( @{$updates} ) {
318 my $sub_object = recursive_update
(
319 resultset
=> $related_resultset,
320 updates
=> $sub_updates,
321 resolved
=> $resolved
324 push @updated_objs, $sub_object;
327 #warn "\tcreated and updated related rows\n";
329 my @related_pks = $related_resultset->result_source->primary_columns;
331 my $rs_rel_delist = $object->$name;
333 # foreign table has a single pk column
334 if ( scalar @related_pks == 1 ) {
335 $rs_rel_delist = $rs_rel_delist->search_rs(
337 { -not_in
=> [ map ( $_->id, @updated_objs ) ] }
342 # foreign table has multiple pk columns
345 for my $obj (@updated_objs) {
347 for my $col (@related_pks) {
348 $cond_for_obj{$col} = $obj->get_column($col);
350 push @cond, \
%cond_for_obj;
353 # only limit resultset if there are related rows left
354 if ( scalar @cond ) {
356 $rs_rel_delist->search_rs( { -not => [@cond] } );
360 #warn "\tCOND: " . Dumper(\%cond);
361 #my $rel_delist_cnt = $rs_rel_delist->count;
362 if ( $if_not_submitted eq 'delete' ) {
364 #warn "\tdeleting related rows: $rel_delist_cnt\n";
365 $rs_rel_delist->delete;
367 elsif ( $if_not_submitted eq 'set_to_null' ) {
369 #warn "\tnullifying related rows: $rel_delist_cnt\n";
370 my %update = map { $_ => undef } @rel_cols;
371 $rs_rel_delist->update( \
%update );
374 elsif ($info->{attrs
}{accessor
} eq 'single'
375 || $info->{attrs
}{accessor
} eq 'filter' )
378 #warn "\tupdating rel '$name': $if_not_submitted\n";
380 if ( ref $updates ) {
382 # for might_have relationship
383 if ( $info->{attrs
}{accessor
} eq 'single'
384 && defined $object->$name )
386 $sub_object = recursive_update
(
387 resultset
=> $related_resultset,
389 object
=> $object->$name
393 $sub_object = recursive_update
(
394 resultset
=> $related_resultset,
396 resolved
=> $resolved
401 $sub_object = $related_resultset->find($updates)
404 && ( exists $info->{attrs
}{join_type
}
405 && $info->{attrs
}{join_type
} eq 'LEFT' )
408 $object->set_from_related( $name, $sub_object )
412 && ( exists $info->{attrs
}{join_type
}
413 && $info->{attrs
}{join_type
} eq 'LEFT' )
417 $self->throw_exception(
418 "recursive_update doesn't now how to handle relationship '$name' with accessor "
419 . $info->{attrs
}{accessor
} );
424 my ( $self, $relation ) = @_;
425 my $rclass = $self->result_class;
427 # DBIx::Class::IntrospectableM2M
428 if ( $rclass->can('_m2m_metadata') ) {
429 return $rclass->_m2m_metadata->{$relation};
431 my $object = $self->new( {} );
432 if ( $object->can($relation)
433 and !$self->result_source->has_relationship($relation)
434 and $object->can( 'set_' . $relation ) )
442 my ( $self, $relation ) = @_;
443 my $rclass = $self->result_class;
445 # DBIx::Class::IntrospectableM2M
446 if ( $rclass->can('_m2m_metadata') ) {
447 return $self->result_source->related_source(
448 $rclass->_m2m_metadata->{$relation}{relation
} )
450 $rclass->_m2m_metadata->{$relation}{foreign_relation
} );
452 my $object = $self->new( {} );
453 my $r = $object->$relation;
454 return $r->result_source;
457 sub _delete_empty_auto_increment
{
458 my ( $self, $object ) = @_;
459 for my $col ( keys %{ $object->{_column_data
} } ) {
460 if ($object->result_source->column_info($col)->{is_auto_increment
}
461 and ( !defined $object->{_column_data
}{$col}
462 or $object->{_column_data
}{$col} eq '' )
465 delete $object->{_column_data
}{$col};
470 sub _get_pk_for_related
{
471 my ( $self, $relation ) = @_;
473 if ( $self->result_source->has_relationship($relation) ) {
474 $result_source = $self->result_source->related_source($relation);
478 if ( is_m2m
( $self, $relation ) ) {
479 $result_source = get_m2m_source
( $self, $relation );
481 return $result_source->primary_columns;
484 # This function determines wheter a relationship should be done before or
485 # after the row is inserted into the database
486 # relationships before: belongs_to
487 # relationships after: has_many, might_have and has_one
488 # true means before, false after
489 sub _master_relation_cond
{
490 my ( $self, $name ) = @_;
492 my $source = $self->result_source;
493 my $info = $source->relationship_info($name);
495 #warn "INFO: " . Dumper($info) . "\n";
497 # has_many rels are always after
499 if $info->{attrs
}->{accessor
} eq 'multi';
501 my @foreign_ids = _get_pk_for_related
( $self, $name );
503 #warn "IDS: " . join(', ', @foreign_ids) . "\n";
505 my $cond = $info->{cond
};
508 my ( $source, $cond, @foreign_ids ) = @_;
510 while ( my ( $f_key, $col ) = each %{$cond} ) {
512 # might_have is not master
514 $f_key =~ s/^foreign\.//;
515 if ( $source->column_info($col)->{is_auto_increment
} ) {
518 if ( any
{ $_ eq $f_key } @foreign_ids ) {
525 if ( ref $cond eq 'HASH' ) {
526 return _inner
( $source, $cond, @foreign_ids );
529 # arrayref of hashrefs
530 elsif ( ref $cond eq 'ARRAY' ) {
531 for my $new_cond (@$cond) {
532 return _inner
( $source, $new_cond, @foreign_ids );
536 $source->throw_exception(
537 "unhandled relation condition " . ref($cond) );
542 1; # Magic true value required at end of module
547 # The functional interface:
549 my $schema = MyDB::Schema->connect();
550 my $new_item = DBIx::Class::ResultSet::RecursiveUpdate::Functions::recursive_update(
551 resultset => $schema->resultset('User'),
556 title => "One Flew Over the Cuckoo's Nest"
560 unknown_params_ok => 1,
564 # As ResultSet subclass:
566 __PACKAGE__->load_namespaces( default_resultset_class => '+DBIx::Class::ResultSet::RecursiveUpdate' );
568 # in the Schema file (see t/lib/DBSchema.pm). Or appropriate 'use base' in the ResultSet classes.
570 my $user = $schema->resultset('User')->recursive_update({
574 title => "One Flew Over the Cuckoo's Nest"
578 unknown_params_ok => 1,
581 # You'll get a warning if you pass non-result specific data to
582 # recursive_update. See L</"Additional data in the updates hashref">
583 # for more information how to prevent this.
587 This is still experimental.
589 You can feed the ->create method of DBIx::Class with a recursive datastructure
590 and have the related records created. Unfortunately you cannot do a similar
591 thing with update_or_create. This module tries to fill that void until
592 L<DBIx::Class> has an api itself.
594 The functional interface can be used without modifications of the model,
595 for example by form processors like L<HTML::FormHandler::Model::DBIC>.
597 It is a base class for L<DBIx::Class::ResultSet>s providing the method
598 recursive_update which works just like update_or_create but can recursively
599 update or create result objects composed of multiple rows. All rows need to be
600 identified by primary keys so you need to provide them in the update structure
601 (unless they can be deduced from the parent row. For example a related row of
602 a belongs_to relationship). If any of the primary key columns are missing,
603 a new row will be created, with the expectation that the missing columns will
604 be filled by it (as in the case of auto_increment primary keys).
606 If the resultset itself stores an assignment for the primary key,
609 my $restricted_rs = $user_rs->search( { id => 1 } );
611 you need to inform recursive_update about the additional predicate with the fixed_fields attribute:
613 my $user = $restricted_rs->recursive_update( {
616 title => 'One Flew Over the Cuckoo's Nest'
621 fixed_fields => [ 'id' ],
625 For a many_to_many (pseudo) relation you can supply a list of primary keys
626 from the other table and it will link the record at hand to those and
627 only those records identified by them. This is convenient for handling web
628 forms with check boxes (or a select field with multiple choice) that lets you
629 update such (pseudo) relations.
631 For a description how to set up base classes for ResultSets see
632 L<DBIx::Class::Schema/load_namespaces>.
634 =head2 Additional data in the updates hashref
636 If you pass additional data to recursive_update which doesn't match a column
637 name, column accessor, relationship or many-to-many helper accessor, it will
638 throw a warning by default. To disable this behaviour you can set the
639 unknown_params_ok attribute to a true value.
641 The warning thrown is:
642 "No such column, relationship, many-to-many helper accessor or generic accessor '$key'"
644 When used by L<HTML::FormHandler::Model::DBIC> this can happen if you have
645 additional form fields that aren't relevant to the database but don't have the
646 noupdate attribute set to a true value.
648 NOTE: in a future version this behaviour will change and throw an exception
649 instead of a warning!
652 =head1 DESIGN CHOICES
654 Columns and relationships which are excluded from the updates hashref aren't
657 =head2 Treatment of belongs_to relations
659 In case the relationship is included but undefined in the updates hashref,
660 all columns forming the relationship will be set to null.
661 If not all of them are nullable, DBIx::Class will throw an error.
663 Updating the relationship:
665 my $dvd = $dvd_rs->recursive_update( {
670 Clearing the relationship (only works if cols are nullable!):
672 my $dvd = $dvd_rs->recursive_update( {
677 =head2 Treatment of might_have relationships
679 In case the relationship is included but undefined in the updates hashref,
680 all columns forming the relationship will be set to null.
682 Updating the relationship:
684 my $user = $user_rs->recursive_update( {
687 street => "101 Main Street",
693 Clearing the relationship:
695 my $user = $user_rs->recursive_update( {
700 =head2 Treatment of has_many relations
702 If a relationship key is included in the data structure with a value of undef
703 or an empty array, all existing related rows will be deleted, or their foreign
704 key columns will be set to null.
706 The exact behaviour depends on the nullability of the foreign key columns and
707 the value of the "if_not_submitted" parameter. The parameter defaults to
708 undefined which neither nullifies nor deletes.
710 When the array contains elements they are updated if they exist, created when
711 not and deleted if not included.
713 =head3 All foreign table columns are nullable
715 In this case recursive_update defaults to nullifying the foreign columns.
717 =head3 Not all foreign table columns are nullable
719 In this case recursive_update deletes the foreign rows.
721 Updating the relationship:
725 my $user = $user_rs->recursive_update( {
727 owned_dvds => [1, 2],
732 my $user = $user_rs->recursive_update( {
736 name => 'temp name 1',
739 name => 'temp name 2',
746 my $user = $user_rs->recursive_update( {
748 owned_dvds => [ $dvd1, $dvd2 ],
751 You can even mix them:
753 my $user = $user_rs->recursive_update( {
755 owned_dvds => [ 1, { id => 2 } ],
758 Clearing the relationship:
760 my $user = $user_rs->recursive_update( {
765 This is the same as passing an empty array:
767 my $user = $user_rs->recursive_update( {
772 =head2 Treatment of many-to-many pseudo relations
774 If a many-to-many accessor key is included in the data structure with a value
775 of undef or an empty array, all existing related rows are unlinked.
777 When the array contains elements they are updated if they exist, created when
778 not and deleted if not included.
780 See L</is_m2m> for many-to-many pseudo relationship detection.
782 Updating the relationship:
786 my $dvd = $dvd_rs->recursive_update( {
793 my $dvd = $dvd_rs->recursive_update( {
809 my $dvd = $dvd_rs->recursive_update( {
811 tags => [ $tag1, $tag2 ],
814 You can even mix them:
816 my $dvd = $dvd_rs->recursive_update( {
818 tags => [ 2, { id => 3 } ],
821 Clearing the relationship:
823 my $dvd = $dvd_rs->recursive_update( {
828 This is the same as passing an empty array:
830 my $dvd = $dvd_rs->recursive_update( {
840 =head2 recursive_update
842 The method that does the work here.
848 =item Arguments: $name
850 =item Return Value: true, if $name is a many to many pseudo-relationship
854 The function gets the information about m2m relations from
855 L<DBIx::Class::IntrospectableM2M>. If it isn't loaded in the ResultSource
856 class, the code relies on the fact:
858 if($object->can($name) and
859 !$object->result_source->has_relationship($name) and
860 $object->can( 'set_' . $name )
863 to identify a many to many pseudo relationship. In a similar ugly way the
864 ResultSource of that many to many pseudo relationship is detected.
866 So if you need many to many pseudo relationship support, it's strongly
867 recommended to load L<DBIx::Class::IntrospectableM2M> in your ResultSource
870 =head2 get_m2m_source
874 =item Arguments: $name
876 =item Return Value: $result_source
880 =head1 CONFIGURATION AND ENVIRONMENT
882 DBIx::Class::RecursiveUpdate requires no configuration files or environment variables.
888 optional but recommended:
889 DBIx::Class::IntrospectableM2M
891 =head1 INCOMPATIBILITIES
896 =head1 BUGS AND LIMITATIONS
898 The list of reported bugs can be viewed at L<http://rt.cpan.org/Public/Dist/Display.html?Name=DBIx-Class-ResultSet-RecursiveUpdate>.
900 Please report any bugs or feature requests to
901 C<bug-dbix-class-recursiveput@rt.cpan.org>, or through the web interface at
902 L<http://rt.cpan.org>.