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
;
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,
581 This is still experimental.
583 You can feed the ->create method of DBIx::Class with a recursive datastructure
584 and have the related records created. Unfortunately you cannot do a similar
585 thing with update_or_create.
586 This module tries to fill that void until L<DBIx::Class> has an api itself.
588 The functional interface can be used without modifications of the model,
589 for example by form processors like L<HTML::FormHandler::Model::DBIC>.
591 It is a base class for L<DBIx::Class::ResultSet>s providing the method recursive_update
592 which works just like update_or_create but can recursively update or create
593 data objects composed of multiple rows. All rows need to be identified by primary keys
594 - so you need to provide them in the update structure (unless they can be deduced from
595 the parent row - for example when you have a belongs_to relationship).
596 If not all columns comprising the primary key are specified a new row will be created,
597 with the expectation that the missing columns will be filled by it (as in the case of auto_increment
601 If the resultset itself stores an assignement for the primary key,
604 my $restricted_rs = $user_rs->search( { id => 1 } );
606 then you need to inform recursive_update about the additional predicate with the fixed_fields attribute:
608 my $user = $restricted_rs->recursive_update( {
611 title => 'One Flew Over the Cuckoo's Nest'
616 fixed_fields => [ 'id' ],
620 For a many_to_many (pseudo) relation you can supply a list of primary keys
621 from the other table and it will link the record at hand to those and
622 only those records identified by them. This is convenient for handling web
623 forms with check boxes (or a select field with multiple choice) that lets you
624 update such (pseudo) relations.
626 For a description how to set up base classes for ResultSets see L<DBIx::Class::Schema/load_namespaces>.
628 =head1 DESIGN CHOICES
630 Columns and relationships which are excluded from the updates hashref aren't
633 =head2 Treatment of belongs_to relations
635 In case the relationship is included but undefined in the updates hashref,
636 all columns forming the relationship will be set to null.
637 If not all of them are nullable, DBIx::Class will throw an error.
639 Updating the relationship:
641 my $dvd = $dvd_rs->recursive_update( {
646 Clearing the relationship (only works if cols are nullable!):
648 my $dvd = $dvd_rs->recursive_update( {
653 =head2 Treatment of might_have relationships
655 In case the relationship is included but undefined in the updates hashref,
656 all columns forming the relationship will be set to null.
658 Updating the relationship:
660 my $user = $user_rs->recursive_update( {
663 street => "101 Main Street",
669 Clearing the relationship:
671 my $user = $user_rs->recursive_update( {
676 =head2 Treatment of has_many relations
678 If a relationship key is included in the data structure with a value of undef
679 or an empty array, all existing related rows will be deleted, or their foreign
680 key columns will be set to null.
682 The exact behaviour depends on the nullability of the foreign key columns and
683 the value of the "if_not_submitted" parameter. The parameter defaults to
684 undefined which neither nullifies nor deletes.
686 When the array contains elements they are updated if they exist, created when
687 not and deleted if not included.
689 =head3 All foreign table columns are nullable
691 In this case recursive_update defaults to nullifying the foreign columns.
693 =head3 Not all foreign table columns are nullable
695 In this case recursive_update deletes the foreign rows.
697 Updating the relationship:
701 my $dvd = $dvd_rs->recursive_update( {
708 my $dvd = $dvd_rs->recursive_update( {
726 You can even mix them:
728 my $dvd = $dvd_rs->recursive_update( {
730 tags => [ '2', { id => '3' } ],
733 Clearing the relationship:
735 my $dvd = $dvd_rs->recursive_update( {
740 This is the same as passing an empty array:
742 my $dvd = $dvd_rs->recursive_update( {
747 =head2 Treatment of many-to-many pseudo relations
749 The function gets the information about m2m relations from L<DBIx::Class::IntrospectableM2M>.
750 If it isn't loaded in the ResultSource classes the code relies on the fact that:
752 if($object->can($name) and
753 !$object->result_source->has_relationship($name) and
754 $object->can( 'set_' . $name )
757 Then $name must be a many to many pseudo relation.
758 And that in a similarly ugly was I find out what is the ResultSource of
759 objects from that many to many pseudo relation.
766 =head2 recursive_update
768 The method that does the work here.
772 $self->is_m2m( 'name ' ) - answers the question if 'name' is a many to many
773 (pseudo) relation on $self.
775 =head2 get_m2m_source
777 $self->get_m2m_source( 'name' ) - returns the ResultSource linked to by the many
778 to many (pseudo) relation 'name' from $self.
784 =head1 CONFIGURATION AND ENVIRONMENT
786 DBIx::Class::RecursiveUpdate requires no configuration files or environment variables.
792 =head1 INCOMPATIBILITIES
797 =head1 BUGS AND LIMITATIONS
799 No bugs have been reported.
801 Please report any bugs or feature requests to
802 C<bug-dbix-class-recursiveput@rt.cpan.org>, or through the web interface at
803 L<http://rt.cpan.org>.