use Carp::Clan instead of warn
[chaz/p5-DBIx-Class-ResultSet-RecursiveUpdate] / lib / DBIx / Class / ResultSet / RecursiveUpdate.pm
1 use strict;
2 use warnings;
3
4 package DBIx::Class::ResultSet::RecursiveUpdate;
5
6 # ABSTRACT: like update_or_create - but recursive
7
8 use base qw(DBIx::Class::ResultSet);
9
10 sub recursive_update {
11 my ( $self, $updates, $attrs ) = @_;
12
13 my $fixed_fields;
14 my $unknown_params_ok;
15
16 # 0.21+ api
17 if ( defined $attrs && ref $attrs eq 'HASH' ) {
18 $fixed_fields = $attrs->{fixed_fields};
19 $unknown_params_ok = $attrs->{unknown_params_ok};
20 }
21
22 # pre 0.21 api
23 elsif ( defined $attrs && ref $attrs eq 'ARRAY' ) {
24 $fixed_fields = $attrs;
25 }
26
27 return
28 DBIx::Class::ResultSet::RecursiveUpdate::Functions::recursive_update(
29 resultset => $self,
30 updates => $updates,
31 fixed_fields => $fixed_fields,
32 unknown_params_ok => $unknown_params_ok,
33 );
34 }
35
36 package DBIx::Class::ResultSet::RecursiveUpdate::Functions;
37 use Carp::Clan;
38 use Scalar::Util qw( blessed );
39 use List::MoreUtils qw/ any /;
40
41 sub recursive_update {
42 my %params = @_;
43 my ( $self, $updates, $fixed_fields, $object, $resolved,
44 $if_not_submitted, $unknown_params_ok )
45 = @params{
46 qw/resultset updates fixed_fields object resolved if_not_submitted unknown_params_ok/
47 };
48 $resolved ||= {};
49
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';
53
54 if ( blessed($updates) && $updates->isa('DBIx::Class::Row') ) {
55 return $updates;
56 }
57 if ( $updates->{id} ) {
58 $object = $self->find( $updates->{id}, { key => 'primary' } );
59 }
60
61 my %fixed_fields = map { $_ => 1 } @$fixed_fields
62 if $fixed_fields;
63 my @missing =
64 grep { !exists $updates->{$_} && !exists $fixed_fields{$_} }
65 $self->result_source->primary_columns;
66 if ( !$object && !scalar @missing ) {
67
68 # warn 'finding by: ' . Dumper( $updates ); use Data::Dumper;
69 $object = $self->find( $updates, { key => 'primary' } );
70 }
71 $updates = { %$updates, %$resolved };
72 @missing =
73 grep { !exists $resolved->{$_} } @missing;
74 if ( !$object && !scalar @missing ) {
75
76 # warn 'finding by +resolved: ' . Dumper( $updates ); use Data::Dumper;
77 $object = $self->find( $updates, { key => 'primary' } );
78 }
79 $object ||= $self->new( {} );
80
81 # warn Dumper( $updates ); use Data::Dumper;
82 # direct column accessors
83 my %columns;
84
85 # relations that that should be done before the row is inserted into the
86 # database like belongs_to
87 my %pre_updates;
88
89 # relations that that should be done after the row is inserted into the
90 # database like has_many, might_have and has_one
91 my %post_updates;
92 my %other_methods;
93 my %columns_by_accessor = _get_columns_by_accessor($self);
94
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;
100
101 # columns
102 if ( exists $columns_by_accessor{$name}
103 && !( $source->has_relationship($name)
104 && ref( $updates->{$name} ) ) )
105 {
106
107 #warn "$name is a column\n";
108 $columns{$name} = $updates->{$name};
109 next;
110 }
111
112 # relationships
113 if ( $source->has_relationship($name) ) {
114 if ( _master_relation_cond( $self, $name ) ) {
115
116 #warn "$name is a pre-update rel\n";
117 $pre_updates{$name} = $updates->{$name};
118 next;
119 }
120 else {
121
122 #warn "$name is a post-update rel\n";
123 $post_updates{$name} = $updates->{$name};
124 next;
125 }
126 }
127
128 # many-to-many helper accessors
129 if ( is_m2m( $self, $name ) ) {
130
131 #warn "$name is a many-to-many helper accessor\n";
132 $other_methods{$name} = $updates->{$name};
133 next;
134 }
135
136 # accessors
137 if ( $object->can($name) && not $source->has_relationship($name) ) {
138
139 #warn "$name is an accessor";
140 $other_methods{$name} = $updates->{$name};
141 next;
142 }
143
144 # unknown
145
146 # don't throw a warning instead of an exception to give users
147 # time to adapt to the new API
148 carp(
149 "No such column, relationship, many-to-many helper accessor or generic accessor '$name'"
150 ) unless $unknown_params_ok;
151
152 #$self->throw_exception(
153 # "No such column, relationship, many-to-many helper accessor or generic accessor '$name'"
154 #);
155 }
156
157 # warn 'other: ' . Dumper( \%other_methods ); use Data::Dumper;
158
159 # first update columns and other accessors
160 # so that later related records can be found
161 for my $name ( keys %columns ) {
162
163 #warn "update col $name\n";
164 $object->$name( $columns{$name} );
165 }
166 for my $name ( keys %other_methods ) {
167
168 #warn "update other $name\n";
169 $object->$name( $updates->{$name} );
170 }
171 for my $name ( keys %pre_updates ) {
172
173 #warn "pre_update $name\n";
174 _update_relation( $self, $name, $pre_updates{$name}, $object,
175 $if_not_submitted );
176 }
177
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;
186
187 # updating many_to_many
188 for my $name ( keys %$updates ) {
189 next if exists $columns{$name};
190 my $value = $updates->{$name};
191
192 if ( is_m2m( $self, $name ) ) {
193
194 #warn "update m2m $name\n";
195 my ($pk) = _get_pk_for_related( $self, $name );
196 my @rows;
197 my $result_source = $object->$name->result_source;
198 my @updates;
199 if ( !defined $value ) {
200 next;
201 }
202 elsif ( ref $value ) {
203 @updates = @{$value};
204 }
205 else {
206 @updates = ($value);
207 }
208 for my $elem (@updates) {
209 if ( ref $elem ) {
210 push @rows,
211 recursive_update(
212 resultset => $result_source->resultset,
213 updates => $elem
214 );
215 }
216 else {
217 push @rows,
218 $result_source->resultset->find( { $pk => $elem } );
219 }
220 }
221 my $set_meth = 'set_' . $name;
222 $object->$set_meth( \@rows );
223 }
224 }
225 for my $name ( keys %post_updates ) {
226
227 #warn "post_update $name\n";
228 _update_relation( $self, $name, $post_updates{$name}, $object,
229 $if_not_submitted );
230 }
231 return $object;
232 }
233
234 # returns DBIx::Class::ResultSource::column_info as a hash indexed by column accessor || name
235 sub _get_columns_by_accessor {
236 my $self = shift;
237 my $source = $self->result_source;
238 my %columns;
239 for my $name ( $source->columns ) {
240 my $info = $source->column_info($name);
241 $info->{name} = $name;
242 $columns{ $info->{accessor} || $name } = $info;
243 }
244 return %columns;
245 }
246
247 # Arguments: $rs, $name, $updates, $row, $if_not_submitted
248 sub _update_relation {
249 my ( $self, $name, $updates, $object, $if_not_submitted ) = @_;
250
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);
255
256 #warn "_update_relation $name: OBJ: " . ref($object) . "\n";
257
258 my $info = $object->result_source->relationship_info($name);
259
260 # get a related resultset without a condition
261 my $related_resultset =
262 $self->related_resultset($name)->result_source->resultset;
263 my $resolved;
264 if ( $self->result_source->can('_resolve_condition') ) {
265 $resolved =
266 $self->result_source->_resolve_condition( $info->{cond}, $name,
267 $object );
268 }
269 else {
270 $self->throw_exception(
271 "result_source must support _resolve_condition");
272 }
273
274 # warn "$name resolved: " . Dumper( $resolved ); use Data::Dumper;
275 $resolved = {}
276 if defined $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION
277 && $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION
278 == $resolved;
279
280 my @rel_cols = keys %{ $info->{cond} };
281 map {s/^foreign\.//} @rel_cols;
282
283 #warn "REL_COLS: " . Dumper(@rel_cols); use Data::Dumper;
284 #my $rel_col_cnt = scalar @rel_cols;
285
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)
291 ->{is_nullable};
292 }
293
294 $if_not_submitted = $all_fks_nullable ? 'nullify' : 'delete'
295 unless defined $if_not_submitted;
296
297 #warn "\tNULLABLE: $all_fks_nullable ACTION: $if_not_submitted\n";
298
299 #warn "RELINFO for $name: " . Dumper($info); use Data::Dumper;
300
301 # the only valid datatype for a has_many rels is an arrayref
302 if ( $info->{attrs}{accessor} eq 'multi' ) {
303
304 # handle undef like empty arrayref
305 $updates = []
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';
310
311 my @updated_objs;
312
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
319 );
320
321 push @updated_objs, $sub_object;
322 }
323
324 #warn "\tcreated and updated related rows\n";
325
326 my @related_pks = $related_resultset->result_source->primary_columns;
327
328 my $rs_rel_delist = $object->$name;
329
330 # foreign table has a single pk column
331 if ( scalar @related_pks == 1 ) {
332 $rs_rel_delist = $rs_rel_delist->search_rs(
333 { $related_pks[0] =>
334 { -not_in => [ map ( $_->id, @updated_objs ) ] }
335 }
336 );
337 }
338
339 # foreign table has multiple pk columns
340 else {
341 my @cond;
342 for my $obj (@updated_objs) {
343 my %cond_for_obj;
344 for my $col (@related_pks) {
345 $cond_for_obj{$col} = $obj->get_column($col);
346 }
347 push @cond, \%cond_for_obj;
348 }
349
350 # only limit resultset if there are related rows left
351 if ( scalar @cond ) {
352 $rs_rel_delist =
353 $rs_rel_delist->search_rs( { -not => [@cond] } );
354 }
355 }
356
357 #warn "\tCOND: " . Dumper(\%cond);
358 #my $rel_delist_cnt = $rs_rel_delist->count;
359 if ( $if_not_submitted eq 'delete' ) {
360
361 #warn "\tdeleting related rows: $rel_delist_cnt\n";
362 $rs_rel_delist->delete;
363 }
364 elsif ( $if_not_submitted eq 'set_to_null' ) {
365
366 #warn "\tnullifying related rows: $rel_delist_cnt\n";
367 my %update = map { $_ => undef } @rel_cols;
368 $rs_rel_delist->update( \%update );
369 }
370 }
371 elsif ($info->{attrs}{accessor} eq 'single'
372 || $info->{attrs}{accessor} eq 'filter' )
373 {
374
375 #warn "\tupdating rel '$name': $if_not_submitted\n";
376 my $sub_object;
377 if ( ref $updates ) {
378
379 # for might_have relationship
380 if ( $info->{attrs}{accessor} eq 'single'
381 && defined $object->$name )
382 {
383 $sub_object = recursive_update(
384 resultset => $related_resultset,
385 updates => $updates,
386 object => $object->$name
387 );
388 }
389 else {
390 $sub_object = recursive_update(
391 resultset => $related_resultset,
392 updates => $updates,
393 resolved => $resolved
394 );
395 }
396 }
397 else {
398 $sub_object = $related_resultset->find($updates)
399 unless (
400 !$updates
401 && ( exists $info->{attrs}{join_type}
402 && $info->{attrs}{join_type} eq 'LEFT' )
403 );
404 }
405 $object->set_from_related( $name, $sub_object )
406 unless (
407 !$sub_object
408 && !$updates
409 && ( exists $info->{attrs}{join_type}
410 && $info->{attrs}{join_type} eq 'LEFT' )
411 );
412 }
413 else {
414 $self->throw_exception(
415 "recursive_update doesn't now how to handle relationship '$name' with accessor "
416 . $info->{attrs}{accessor} );
417 }
418 }
419
420 sub is_m2m {
421 my ( $self, $relation ) = @_;
422 my $rclass = $self->result_class;
423
424 # DBIx::Class::IntrospectableM2M
425 if ( $rclass->can('_m2m_metadata') ) {
426 return $rclass->_m2m_metadata->{$relation};
427 }
428 my $object = $self->new( {} );
429 if ( $object->can($relation)
430 and !$self->result_source->has_relationship($relation)
431 and $object->can( 'set_' . $relation ) )
432 {
433 return 1;
434 }
435 return;
436 }
437
438 sub get_m2m_source {
439 my ( $self, $relation ) = @_;
440 my $rclass = $self->result_class;
441
442 # DBIx::Class::IntrospectableM2M
443 if ( $rclass->can('_m2m_metadata') ) {
444 return $self->result_source->related_source(
445 $rclass->_m2m_metadata->{$relation}{relation} )
446 ->related_source(
447 $rclass->_m2m_metadata->{$relation}{foreign_relation} );
448 }
449 my $object = $self->new( {} );
450 my $r = $object->$relation;
451 return $r->result_source;
452 }
453
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 '' )
460 )
461 {
462 delete $object->{_column_data}{$col};
463 }
464 }
465 }
466
467 sub _get_pk_for_related {
468 my ( $self, $relation ) = @_;
469 my $result_source;
470 if ( $self->result_source->has_relationship($relation) ) {
471 $result_source = $self->result_source->related_source($relation);
472 }
473
474 # many to many case
475 if ( is_m2m( $self, $relation ) ) {
476 $result_source = get_m2m_source( $self, $relation );
477 }
478 return $result_source->primary_columns;
479 }
480
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 ) = @_;
488
489 my $source = $self->result_source;
490 my $info = $source->relationship_info($name);
491
492 #warn "INFO: " . Dumper($info) . "\n";
493
494 # has_many rels are always after
495 return 0
496 if $info->{attrs}->{accessor} eq 'multi';
497
498 my @foreign_ids = _get_pk_for_related( $self, $name );
499
500 #warn "IDS: " . join(', ', @foreign_ids) . "\n";
501
502 my $cond = $info->{cond};
503
504 sub _inner {
505 my ( $source, $cond, @foreign_ids ) = @_;
506
507 while ( my ( $f_key, $col ) = each %{$cond} ) {
508
509 # might_have is not master
510 $col =~ s/^self\.//;
511 $f_key =~ s/^foreign\.//;
512 if ( $source->column_info($col)->{is_auto_increment} ) {
513 return 0;
514 }
515 if ( any { $_ eq $f_key } @foreign_ids ) {
516 return 1;
517 }
518 }
519 return 0;
520 }
521
522 if ( ref $cond eq 'HASH' ) {
523 return _inner( $source, $cond, @foreign_ids );
524 }
525
526 # arrayref of hashrefs
527 elsif ( ref $cond eq 'ARRAY' ) {
528 for my $new_cond (@$cond) {
529 return _inner( $source, $new_cond, @foreign_ids );
530 }
531 }
532 else {
533 $source->throw_exception(
534 "unhandled relation condition " . ref($cond) );
535 }
536 return;
537 }
538
539 1; # Magic true value required at end of module
540 __END__
541
542 =head1 SYNOPSIS
543
544 # The functional interface:
545
546 my $schema = MyDB::Schema->connect();
547 my $new_item = DBIx::Class::ResultSet::RecursiveUpdate::Functions::recursive_update(
548 resultset => $schema->resultset('User'),
549 updates => {
550 id => 1,
551 owned_dvds => [
552 {
553 title => "One Flew Over the Cuckoo's Nest"
554 }
555 ]
556 },
557 unknown_params_ok => 1,
558 );
559
560
561 # As ResultSet subclass:
562
563 __PACKAGE__->load_namespaces( default_resultset_class => '+DBIx::Class::ResultSet::RecursiveUpdate' );
564
565 # in the Schema file (see t/lib/DBSchema.pm). Or appropriate 'use base' in the ResultSet classes.
566
567 my $user = $schema->resultset('User')->recursive_update({
568 id => 1,
569 owned_dvds => [
570 {
571 title => "One Flew Over the Cuckoo's Nest"
572 }
573 ]
574 }, {
575 unknown_params_ok => 1,
576 });
577
578
579 =head1 DESCRIPTION
580
581 This is still experimental.
582
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.
587
588 The functional interface can be used without modifications of the model,
589 for example by form processors like L<HTML::FormHandler::Model::DBIC>.
590
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
598 primary keys).
599
600
601 If the resultset itself stores an assignement for the primary key,
602 like in the case of:
603
604 my $restricted_rs = $user_rs->search( { id => 1 } );
605
606 then you need to inform recursive_update about the additional predicate with the fixed_fields attribute:
607
608 my $user = $restricted_rs->recursive_update( {
609 owned_dvds => [
610 {
611 title => 'One Flew Over the Cuckoo's Nest'
612 }
613 ]
614 },
615 {
616 fixed_fields => [ 'id' ],
617 }
618 );
619
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.
625
626 For a description how to set up base classes for ResultSets see L<DBIx::Class::Schema/load_namespaces>.
627
628 =head1 DESIGN CHOICES
629
630 Columns and relationships which are excluded from the updates hashref aren't
631 touched at all.
632
633 =head2 Treatment of belongs_to relations
634
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.
638
639 Updating the relationship:
640
641 my $dvd = $dvd_rs->recursive_update( {
642 id => 1,
643 owner => $user->id,
644 });
645
646 Clearing the relationship (only works if cols are nullable!):
647
648 my $dvd = $dvd_rs->recursive_update( {
649 id => 1,
650 owner => undef,
651 });
652
653 =head2 Treatment of might_have relationships
654
655 In case the relationship is included but undefined in the updates hashref,
656 all columns forming the relationship will be set to null.
657
658 Updating the relationship:
659
660 my $user = $user_rs->recursive_update( {
661 id => 1,
662 address => {
663 street => "101 Main Street",
664 city => "Podunk",
665 state => "New York",
666 }
667 });
668
669 Clearing the relationship:
670
671 my $user = $user_rs->recursive_update( {
672 id => 1,
673 address => undef,
674 });
675
676 =head2 Treatment of has_many relations
677
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.
681
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.
685
686 When the array contains elements they are updated if they exist, created when
687 not and deleted if not included.
688
689 =head3 All foreign table columns are nullable
690
691 In this case recursive_update defaults to nullifying the foreign columns.
692
693 =head3 Not all foreign table columns are nullable
694
695 In this case recursive_update deletes the foreign rows.
696
697 Updating the relationship:
698
699 Passing ids:
700
701 my $dvd = $dvd_rs->recursive_update( {
702 id => 1,
703 tags => [1, 2],
704 });
705
706 Passing hashrefs:
707
708 my $dvd = $dvd_rs->recursive_update( {
709 id => 1,
710 tags => [
711 {
712 id => 1,
713 file => 'file0'
714 },
715 {
716 id => 2,
717 file => 'file1',
718 },
719 ],
720 });
721
722 Passing objects:
723
724 TODO
725
726 You can even mix them:
727
728 my $dvd = $dvd_rs->recursive_update( {
729 id => 1,
730 tags => [ '2', { id => '3' } ],
731 });
732
733 Clearing the relationship:
734
735 my $dvd = $dvd_rs->recursive_update( {
736 id => 1,
737 tags => undef,
738 });
739
740 This is the same as passing an empty array:
741
742 my $dvd = $dvd_rs->recursive_update( {
743 id => 1,
744 tags => [],
745 });
746
747 =head2 Treatment of many-to-many pseudo relations
748
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:
751
752 if($object->can($name) and
753 !$object->result_source->has_relationship($name) and
754 $object->can( 'set_' . $name )
755 )
756
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.
760
761
762 =head1 INTERFACE
763
764 =head1 METHODS
765
766 =head2 recursive_update
767
768 The method that does the work here.
769
770 =head2 is_m2m
771
772 $self->is_m2m( 'name ' ) - answers the question if 'name' is a many to many
773 (pseudo) relation on $self.
774
775 =head2 get_m2m_source
776
777 $self->get_m2m_source( 'name' ) - returns the ResultSource linked to by the many
778 to many (pseudo) relation 'name' from $self.
779
780
781 =head1 DIAGNOSTICS
782
783
784 =head1 CONFIGURATION AND ENVIRONMENT
785
786 DBIx::Class::RecursiveUpdate requires no configuration files or environment variables.
787
788 =head1 DEPENDENCIES
789
790 DBIx::Class
791
792 =head1 INCOMPATIBILITIES
793
794 None reported.
795
796
797 =head1 BUGS AND LIMITATIONS
798
799 No bugs have been reported.
800
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>.
This page took 0.083512 seconds and 4 git commands to generate.