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 # warn 'entering: ' . $self->result_source->from();
51 carp
'fixed fields needs to be an array ref'
52 if defined $fixed_fields && ref $fixed_fields ne 'ARRAY';
54 if ( blessed
($updates) && $updates->isa('DBIx::Class::Row') ) {
57 if ( $updates->{id
} ) {
58 $object = $self->find( $updates->{id
}, { key
=> 'primary' } );
61 my %fixed_fields = map { $_ => 1 } @$fixed_fields
64 grep { !exists $updates->{$_} && !exists $fixed_fields{$_} }
65 $self->result_source->primary_columns;
66 if ( !$object && !scalar @missing ) {
68 # warn 'finding by: ' . Dumper( $updates ); use Data::Dumper;
69 $object = $self->find( $updates, { key
=> 'primary' } );
71 $updates = { %$updates, %$resolved };
73 grep { !exists $resolved->{$_} } @missing;
74 if ( !$object && !scalar @missing ) {
76 # warn 'finding by +resolved: ' . Dumper( $updates ); use Data::Dumper;
77 $object = $self->find( $updates, { key
=> 'primary' } );
79 $object ||= $self->new( {} );
81 # warn Dumper( $updates ); use Data::Dumper;
82 # direct column accessors
85 # relations that that should be done before the row is inserted into the
86 # database like belongs_to
89 # relations that that should be done after the row is inserted into the
90 # database like has_many, might_have and has_one
93 my %columns_by_accessor = _get_columns_by_accessor
($self);
95 # warn 'resolved: ' . Dumper( $resolved );
96 # warn 'updates: ' . Dumper( $updates ); use Data::Dumper;
97 # warn 'columns: ' . Dumper( \%columns_by_accessor );
98 for my $name ( keys %$updates ) {
99 my $source = $self->result_source;
102 if ( exists $columns_by_accessor{$name}
103 && !( $source->has_relationship($name)
104 && ref( $updates->{$name} ) ) )
107 #warn "$name is a column\n";
108 $columns{$name} = $updates->{$name};
113 if ( $source->has_relationship($name) ) {
114 if ( _master_relation_cond
( $self, $name ) ) {
116 #warn "$name is a pre-update rel\n";
117 $pre_updates{$name} = $updates->{$name};
122 #warn "$name is a post-update rel\n";
123 $post_updates{$name} = $updates->{$name};
128 # many-to-many helper accessors
129 if ( is_m2m
( $self, $name ) ) {
131 #warn "$name is a many-to-many helper accessor\n";
132 $other_methods{$name} = $updates->{$name};
137 if ( $object->can($name) && not $source->has_relationship($name) ) {
139 #warn "$name is an accessor";
140 $other_methods{$name} = $updates->{$name};
146 # don't throw a warning instead of an exception to give users
147 # time to adapt to the new API
149 "No such column, relationship, many-to-many helper accessor or generic accessor '$name'"
150 ) unless $unknown_params_ok;
152 #$self->throw_exception(
153 # "No such column, relationship, many-to-many helper accessor or generic accessor '$name'"
157 # warn 'other: ' . Dumper( \%other_methods ); use Data::Dumper;
159 # first update columns and other accessors
160 # so that later related records can be found
161 for my $name ( keys %columns ) {
163 #warn "update col $name\n";
164 $object->$name( $columns{$name} );
166 for my $name ( keys %other_methods ) {
168 #warn "update other $name\n";
169 $object->$name( $updates->{$name} );
171 for my $name ( keys %pre_updates ) {
173 #warn "pre_update $name\n";
174 _update_relation
( $self, $name, $pre_updates{$name}, $object,
178 # $self->_delete_empty_auto_increment($object);
179 # don't allow insert to recurse to related objects
180 # do the recursion ourselves
181 # $object->{_rel_in_storage} = 1;
182 #warn "CHANGED: " . $object->is_changed . "\n":
183 #warn "IN STOR: " . $object->in_storage . "\n";
184 $object->update_or_insert if $object->is_changed;
185 $object->discard_changes;
187 # updating many_to_many
188 for my $name ( keys %$updates ) {
189 next if exists $columns{$name};
190 my $value = $updates->{$name};
192 if ( is_m2m
( $self, $name ) ) {
194 #warn "update m2m $name\n";
195 my ($pk) = _get_pk_for_related
( $self, $name );
197 my $result_source = $object->$name->result_source;
199 if ( !defined $value ) {
202 elsif ( ref $value ) {
203 @updates = @{$value};
208 for my $elem (@updates) {
212 resultset
=> $result_source->resultset,
218 $result_source->resultset->find( { $pk => $elem } );
221 my $set_meth = 'set_' . $name;
222 $object->$set_meth( \
@rows );
225 for my $name ( keys %post_updates ) {
227 #warn "post_update $name\n";
228 _update_relation
( $self, $name, $post_updates{$name}, $object,
234 # returns DBIx::Class::ResultSource::column_info as a hash indexed by column accessor || name
235 sub _get_columns_by_accessor
{
237 my $source = $self->result_source;
239 for my $name ( $source->columns ) {
240 my $info = $source->column_info($name);
241 $info->{name
} = $name;
242 $columns{ $info->{accessor
} || $name } = $info;
247 # Arguments: $rs, $name, $updates, $row, $if_not_submitted
248 sub _update_relation
{
249 my ( $self, $name, $updates, $object, $if_not_submitted ) = @_;
251 # this should never happen because we're checking the paramters passed to
252 # recursive_update, but just to be sure...
253 $object->throw_exception("No such relationship '$name'")
254 unless $object->has_relationship($name);
256 #warn "_update_relation $name: OBJ: " . ref($object) . "\n";
258 my $info = $object->result_source->relationship_info($name);
260 # get a related resultset without a condition
261 my $related_resultset =
262 $self->related_resultset($name)->result_source->resultset;
264 if ( $self->result_source->can('_resolve_condition') ) {
266 $self->result_source->_resolve_condition( $info->{cond
}, $name,
270 $self->throw_exception(
271 "result_source must support _resolve_condition");
274 # warn "$name resolved: " . Dumper( $resolved ); use Data::Dumper;
276 if defined $DBIx::Class
::ResultSource
::UNRESOLVABLE_CONDITION
277 && $DBIx::Class
::ResultSource
::UNRESOLVABLE_CONDITION
280 my @rel_cols = keys %{ $info->{cond
} };
281 map {s/^foreign\.//} @rel_cols;
283 #warn "REL_COLS: " . Dumper(@rel_cols); use Data::Dumper;
284 #my $rel_col_cnt = scalar @rel_cols;
286 # find out if all related columns are nullable
287 my $all_fks_nullable = 1;
288 for my $rel_col (@rel_cols) {
289 $all_fks_nullable = 0
290 unless $related_resultset->result_source->column_info($rel_col)
294 $if_not_submitted = $all_fks_nullable ? 'nullify' : 'delete'
295 unless defined $if_not_submitted;
297 #warn "\tNULLABLE: $all_fks_nullable ACTION: $if_not_submitted\n";
299 #warn "RELINFO for $name: " . Dumper($info); use Data::Dumper;
301 # the only valid datatype for a has_many rels is an arrayref
302 if ( $info->{attrs
}{accessor
} eq 'multi' ) {
304 # handle undef like empty arrayref
306 unless defined $updates;
307 $self->throw_exception(
308 "data for has_many relationship '$name' must be an arrayref")
309 unless ref $updates eq 'ARRAY';
313 #warn "\tupdating has_many rel '$name' ($rel_col_cnt columns cols)\n";
314 for my $sub_updates ( @{$updates} ) {
315 my $sub_object = recursive_update
(
316 resultset
=> $related_resultset,
317 updates
=> $sub_updates,
318 resolved
=> $resolved
321 push @updated_objs, $sub_object;
324 #warn "\tcreated and updated related rows\n";
326 my @related_pks = $related_resultset->result_source->primary_columns;
328 my $rs_rel_delist = $object->$name;
330 # foreign table has a single pk column
331 if ( scalar @related_pks == 1 ) {
332 $rs_rel_delist = $rs_rel_delist->search_rs(
334 { -not_in
=> [ map ( $_->id, @updated_objs ) ] }
339 # foreign table has multiple pk columns
342 for my $obj (@updated_objs) {
344 for my $col (@related_pks) {
345 $cond_for_obj{$col} = $obj->get_column($col);
347 push @cond, \
%cond_for_obj;
350 # only limit resultset if there are related rows left
351 if ( scalar @cond ) {
353 $rs_rel_delist->search_rs( { -not => [@cond] } );
357 #warn "\tCOND: " . Dumper(\%cond);
358 #my $rel_delist_cnt = $rs_rel_delist->count;
359 if ( $if_not_submitted eq 'delete' ) {
361 #warn "\tdeleting related rows: $rel_delist_cnt\n";
362 $rs_rel_delist->delete;
364 elsif ( $if_not_submitted eq 'set_to_null' ) {
366 #warn "\tnullifying related rows: $rel_delist_cnt\n";
367 my %update = map { $_ => undef } @rel_cols;
368 $rs_rel_delist->update( \
%update );
371 elsif ($info->{attrs
}{accessor
} eq 'single'
372 || $info->{attrs
}{accessor
} eq 'filter' )
375 #warn "\tupdating rel '$name': $if_not_submitted\n";
377 if ( ref $updates ) {
379 # for might_have relationship
380 if ( $info->{attrs
}{accessor
} eq 'single'
381 && defined $object->$name )
383 $sub_object = recursive_update
(
384 resultset
=> $related_resultset,
386 object
=> $object->$name
390 $sub_object = recursive_update
(
391 resultset
=> $related_resultset,
393 resolved
=> $resolved
398 $sub_object = $related_resultset->find($updates)
401 && ( exists $info->{attrs
}{join_type
}
402 && $info->{attrs
}{join_type
} eq 'LEFT' )
405 $object->set_from_related( $name, $sub_object )
409 && ( exists $info->{attrs
}{join_type
}
410 && $info->{attrs
}{join_type
} eq 'LEFT' )
414 $self->throw_exception(
415 "recursive_update doesn't now how to handle relationship '$name' with accessor "
416 . $info->{attrs
}{accessor
} );
421 my ( $self, $relation ) = @_;
422 my $rclass = $self->result_class;
424 # DBIx::Class::IntrospectableM2M
425 if ( $rclass->can('_m2m_metadata') ) {
426 return $rclass->_m2m_metadata->{$relation};
428 my $object = $self->new( {} );
429 if ( $object->can($relation)
430 and !$self->result_source->has_relationship($relation)
431 and $object->can( 'set_' . $relation ) )
439 my ( $self, $relation ) = @_;
440 my $rclass = $self->result_class;
442 # DBIx::Class::IntrospectableM2M
443 if ( $rclass->can('_m2m_metadata') ) {
444 return $self->result_source->related_source(
445 $rclass->_m2m_metadata->{$relation}{relation
} )
447 $rclass->_m2m_metadata->{$relation}{foreign_relation
} );
449 my $object = $self->new( {} );
450 my $r = $object->$relation;
451 return $r->result_source;
454 sub _delete_empty_auto_increment
{
455 my ( $self, $object ) = @_;
456 for my $col ( keys %{ $object->{_column_data
} } ) {
457 if ($object->result_source->column_info($col)->{is_auto_increment
}
458 and ( !defined $object->{_column_data
}{$col}
459 or $object->{_column_data
}{$col} eq '' )
462 delete $object->{_column_data
}{$col};
467 sub _get_pk_for_related
{
468 my ( $self, $relation ) = @_;
470 if ( $self->result_source->has_relationship($relation) ) {
471 $result_source = $self->result_source->related_source($relation);
475 if ( is_m2m
( $self, $relation ) ) {
476 $result_source = get_m2m_source
( $self, $relation );
478 return $result_source->primary_columns;
481 # This function determines wheter a relationship should be done before or
482 # after the row is inserted into the database
483 # relationships before: belongs_to
484 # relationships after: has_many, might_have and has_one
485 # true means before, false after
486 sub _master_relation_cond
{
487 my ( $self, $name ) = @_;
489 my $source = $self->result_source;
490 my $info = $source->relationship_info($name);
492 #warn "INFO: " . Dumper($info) . "\n";
494 # has_many rels are always after
496 if $info->{attrs
}->{accessor
} eq 'multi';
498 my @foreign_ids = _get_pk_for_related
( $self, $name );
500 #warn "IDS: " . join(', ', @foreign_ids) . "\n";
502 my $cond = $info->{cond
};
505 my ( $source, $cond, @foreign_ids ) = @_;
507 while ( my ( $f_key, $col ) = each %{$cond} ) {
509 # might_have is not master
511 $f_key =~ s/^foreign\.//;
512 if ( $source->column_info($col)->{is_auto_increment
} ) {
515 if ( any
{ $_ eq $f_key } @foreign_ids ) {
522 if ( ref $cond eq 'HASH' ) {
523 return _inner
( $source, $cond, @foreign_ids );
526 # arrayref of hashrefs
527 elsif ( ref $cond eq 'ARRAY' ) {
528 for my $new_cond (@$cond) {
529 return _inner
( $source, $new_cond, @foreign_ids );
533 $source->throw_exception(
534 "unhandled relation condition " . ref($cond) );
539 1; # Magic true value required at end of module
544 # The functional interface:
546 my $schema = MyDB::Schema->connect();
547 my $new_item = DBIx::Class::ResultSet::RecursiveUpdate::Functions::recursive_update(
548 resultset => $schema->resultset('User'),
553 title => "One Flew Over the Cuckoo's Nest"
557 unknown_params_ok => 1,
561 # As ResultSet subclass:
563 __PACKAGE__->load_namespaces( default_resultset_class => '+DBIx::Class::ResultSet::RecursiveUpdate' );
565 # in the Schema file (see t/lib/DBSchema.pm). Or appropriate 'use base' in the ResultSet classes.
567 my $user = $schema->resultset('User')->recursive_update({
571 title => "One Flew Over the Cuckoo's Nest"
575 unknown_params_ok => 1,
578 # You'll get a warning if you pass non-result specific data to
579 # recursive_update. See L</"Additional data in the updates hashref">
580 # for more information how to prevent this.
584 This is still experimental.
586 You can feed the ->create method of DBIx::Class with a recursive datastructure
587 and have the related records created. Unfortunately you cannot do a similar
588 thing with update_or_create. This module tries to fill that void until
589 L<DBIx::Class> has an api itself.
591 The functional interface can be used without modifications of the model,
592 for example by form processors like L<HTML::FormHandler::Model::DBIC>.
594 It is a base class for L<DBIx::Class::ResultSet>s providing the method
595 recursive_update which works just like update_or_create but can recursively
596 update or create result objects composed of multiple rows. All rows need to be
597 identified by primary keys so you need to provide them in the update structure
598 (unless they can be deduced from the parent row. For example a related row of
599 a belongs_to relationship). If any of the primary key columns are missing,
600 a new row will be created, with the expectation that the missing columns will
601 be filled by it (as in the case of auto_increment primary keys).
603 If the resultset itself stores an assignment for the primary key,
606 my $restricted_rs = $user_rs->search( { id => 1 } );
608 you need to inform recursive_update about the additional predicate with the fixed_fields attribute:
610 my $user = $restricted_rs->recursive_update( {
613 title => 'One Flew Over the Cuckoo's Nest'
618 fixed_fields => [ 'id' ],
622 For a many_to_many (pseudo) relation you can supply a list of primary keys
623 from the other table and it will link the record at hand to those and
624 only those records identified by them. This is convenient for handling web
625 forms with check boxes (or a select field with multiple choice) that lets you
626 update such (pseudo) relations.
628 For a description how to set up base classes for ResultSets see
629 L<DBIx::Class::Schema/load_namespaces>.
631 =head2 Additional data in the updates hashref
633 If you pass additional data to recursive_update which doesn't match a column
634 name, column accessor, relationship or many-to-many helper accessor, it will
635 throw a warning by default. To disable this behaviour you can set the
636 unknown_params_ok attribute to a true value.
638 The warning thrown is:
639 "No such column, relationship, many-to-many helper accessor or generic accessor '$key'"
641 When used by L<HTML::FormHandler::Model::DBIC> this can happen if you have
642 additional form fields that aren't relevant to the database but don't have the
643 noupdate attribute set to a true value.
645 NOTE: in a future version this behaviour will change and throw an exception
646 instead of a warning!
649 =head1 DESIGN CHOICES
651 Columns and relationships which are excluded from the updates hashref aren't
654 =head2 Treatment of belongs_to relations
656 In case the relationship is included but undefined in the updates hashref,
657 all columns forming the relationship will be set to null.
658 If not all of them are nullable, DBIx::Class will throw an error.
660 Updating the relationship:
662 my $dvd = $dvd_rs->recursive_update( {
667 Clearing the relationship (only works if cols are nullable!):
669 my $dvd = $dvd_rs->recursive_update( {
674 =head2 Treatment of might_have relationships
676 In case the relationship is included but undefined in the updates hashref,
677 all columns forming the relationship will be set to null.
679 Updating the relationship:
681 my $user = $user_rs->recursive_update( {
684 street => "101 Main Street",
690 Clearing the relationship:
692 my $user = $user_rs->recursive_update( {
697 =head2 Treatment of has_many relations
699 If a relationship key is included in the data structure with a value of undef
700 or an empty array, all existing related rows will be deleted, or their foreign
701 key columns will be set to null.
703 The exact behaviour depends on the nullability of the foreign key columns and
704 the value of the "if_not_submitted" parameter. The parameter defaults to
705 undefined which neither nullifies nor deletes.
707 When the array contains elements they are updated if they exist, created when
708 not and deleted if not included.
710 =head3 All foreign table columns are nullable
712 In this case recursive_update defaults to nullifying the foreign columns.
714 =head3 Not all foreign table columns are nullable
716 In this case recursive_update deletes the foreign rows.
718 Updating the relationship:
722 my $user = $user_rs->recursive_update( {
724 owned_dvds => [1, 2],
729 my $user = $user_rs->recursive_update( {
733 name => 'temp name 1',
736 name => 'temp name 2',
743 my $user = $user_rs->recursive_update( {
745 owned_dvds => [ $dvd1, $dvd2 ],
748 You can even mix them:
750 my $user = $user_rs->recursive_update( {
752 owned_dvds => [ 1, { id => 2 } ],
755 Clearing the relationship:
757 my $user = $user_rs->recursive_update( {
762 This is the same as passing an empty array:
764 my $user = $user_rs->recursive_update( {
769 =head2 Treatment of many-to-many pseudo relations
771 If a many-to-many accessor key is included in the data structure with a value
772 of undef or an empty array, all existing related rows are unlinked.
774 When the array contains elements they are updated if they exist, created when
775 not and deleted if not included.
777 See L</is_m2m> for many-to-many pseudo relationship detection.
779 Updating the relationship:
783 my $dvd = $dvd_rs->recursive_update( {
790 my $dvd = $dvd_rs->recursive_update( {
806 my $dvd = $dvd_rs->recursive_update( {
808 tags => [ $tag1, $tag2 ],
811 You can even mix them:
813 my $dvd = $dvd_rs->recursive_update( {
815 tags => [ 2, { id => 3 } ],
818 Clearing the relationship:
820 my $dvd = $dvd_rs->recursive_update( {
825 This is the same as passing an empty array:
827 my $dvd = $dvd_rs->recursive_update( {
837 =head2 recursive_update
839 The method that does the work here.
845 =item Arguments: $name
847 =item Return Value: true, if $name is a many to many pseudo-relationship
851 The function gets the information about m2m relations from
852 L<DBIx::Class::IntrospectableM2M>. If it isn't loaded in the ResultSource
853 class, the code relies on the fact:
855 if($object->can($name) and
856 !$object->result_source->has_relationship($name) and
857 $object->can( 'set_' . $name )
860 to identify a many to many pseudo relationship. In a similar ugly way the
861 ResultSource of that many to many pseudo relationship is detected.
863 So if you need many to many pseudo relationship support, it's strongly
864 recommended to load L<DBIx::Class::IntrospectableM2M> in your ResultSource
867 =head2 get_m2m_source
871 =item Arguments: $name
873 =item Return Value: $result_source
877 =head1 CONFIGURATION AND ENVIRONMENT
879 DBIx::Class::RecursiveUpdate requires no configuration files or environment variables.
885 optional but recommended:
886 DBIx::Class::IntrospectableM2M
888 =head1 INCOMPATIBILITIES
893 =head1 BUGS AND LIMITATIONS
895 The list of reported bugs can be viewed at L<http://rt.cpan.org/Public/Dist/Display.html?Name=DBIx-Class-ResultSet-RecursiveUpdate>.
897 Please report any bugs or feature requests to
898 C<bug-dbix-class-recursiveput@rt.cpan.org>, or through the web interface at
899 L<http://rt.cpan.org>.