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