]> Dogcows Code - chaz/p5-DBIx-Class-ResultSet-RecursiveUpdate/blob - lib/DBIx/Class/ResultSet/RecursiveUpdate.pm
converted to Dist::Zilla
[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 NAME
516
517 DBIx::Class::ResultSet::RecursiveUpdate - like update_or_create - but recursive
518
519 =head1 SYNOPSIS
520
521 The functional interface:
522
523 my $new_item = DBIx::Class::ResultSet::RecursiveUpdate::Functions::recursive_update({
524 resultset => $schema->resultset( 'Dvd' ),
525 updates => {
526 id => 1,
527 owned_dvds => [
528 {
529 title => 'One Flew Over the Cuckoo's Nest'
530 }
531 ]
532 }
533 });
534
535
536 As ResultSet subclass:
537
538 __PACKAGE__->load_namespaces( default_resultset_class => '+DBIx::Class::ResultSet::RecursiveUpdate' );
539
540 in the Schema file (see t/lib/DBSchema.pm). Or appriopriate 'use base' in the ResultSet classes.
541
542 Then:
543
544 my $user = $user_rs->recursive_update( {
545 id => 1,
546 owned_dvds => [
547 {
548 title => 'One Flew Over the Cuckoo's Nest'
549 }
550 ]
551 }
552 );
553
554
555 =head1 DESCRIPTION
556
557 This is still experimental. I've added a functional interface so that it can be used
558 in Form Processors and not require modification of the model.
559
560 You can feed the ->create method with a recursive datastructure and have the related records
561 created. Unfortunately you cannot do a similar thing with update_or_create - this module
562 tries to fill that void.
563
564 It is a base class for ResultSets providing just one method: recursive_update
565 which works just like update_or_create but can recursively update or create
566 data objects composed of multiple rows. All rows need to be identified by primary keys
567 - so you need to provide them in the update structure (unless they can be deduced from
568 the parent row - for example when you have a belongs_to relationship).
569 If not all colums comprising the primary key are specified - then a new row will be created,
570 with the expectation that the missing columns will be filled by it (as in the case of auto_increment
571 primary keys).
572
573
574 If the resultset itself stores an assignement for the primary key,
575 like in the case of:
576
577 my $restricted_rs = $user_rs->search( { id => 1 } );
578
579 then you need to inform recursive_update about additional predicate with a second argument:
580
581 my $user = $restricted_rs->recursive_update( {
582 owned_dvds => [
583 {
584 title => 'One Flew Over the Cuckoo's Nest'
585 }
586 ]
587 },
588 [ 'id' ]
589 );
590
591 This will work with a new DBIC release.
592
593 For a many_to_many (pseudo) relation you can supply a list of primary keys
594 from the other table - and it will link the record at hand to those and
595 only those records identified by them. This is convenient for handling web
596 forms with check boxes (or a SELECT box with multiple choice) that let you
597 update such (pseudo) relations.
598
599 For a description how to set up base classes for ResultSets see load_namespaces
600 in DBIx::Class::Schema.
601
602 =head1 DESIGN CHOICES
603
604 Columns and relationships which are excluded from the updates hashref aren't
605 touched at all.
606
607 =head2 Treatment of belongs_to relations
608
609 In case the relationship is included but undefined in the updates hashref,
610 all columns forming the relationship will be set to null.
611 If not all of them are nullable, DBIx::Class will throw an error.
612
613 Updating the relationship:
614
615 my $dvd = $dvd_rs->recursive_update( {
616 id => 1,
617 owner => $user->id,
618 });
619
620 Clearing the relationship (only works if cols are nullable!):
621
622 my $dvd = $dvd_rs->recursive_update( {
623 id => 1,
624 owner => undef,
625 });
626
627 =head2 Treatment of might_have relationships
628
629 In case the relationship is included but undefined in the updates hashref,
630 all columns forming the relationship will be set to null.
631
632 Updating the relationship:
633
634 my $user = $user_rs->recursive_update( {
635 id => 1,
636 address => {
637 street => "101 Main Street",
638 city => "Podunk",
639 state => "New York",
640 }
641 });
642
643 Clearing the relationship:
644
645 my $user = $user_rs->recursive_update( {
646 id => 1,
647 address => undef,
648 });
649
650 =head2 Treatment of has_many relations
651
652 If a relationship key is included in the data structure with a value of undef
653 or an empty array, all existing related rows will be deleted, or their foreign
654 key columns will be set to null.
655
656 The exact behaviour depends on the nullability of the foreign key columns and
657 the value of the "if_not_submitted" parameter. The parameter defaults to
658 undefined which neither nullifies nor deletes.
659
660 When the array contains elements they are updated if they exist, created when
661 not and deleted if not included.
662
663 =head3 All foreign table columns are nullable
664
665 In this case recursive_update defaults to nullifying the foreign columns.
666
667 =head3 Not all foreign table columns are nullable
668
669 In this case recursive_update deletes the foreign rows.
670
671 Updating the relationship:
672
673 Passing ids:
674
675 my $dvd = $dvd_rs->recursive_update( {
676 id => 1,
677 tags => [1, 2],
678 });
679
680 Passing hashrefs:
681
682 my $dvd = $dvd_rs->recursive_update( {
683 id => 1,
684 tags => [
685 {
686 id => 1,
687 file => 'file0'
688 },
689 {
690 id => 2,
691 file => 'file1',
692 },
693 ],
694 });
695
696 Passing objects:
697
698 TODO
699
700 You can even mix them:
701
702 my $dvd = $dvd_rs->recursive_update( {
703 id => 1,
704 tags => [ '2', { id => '3' } ],
705 });
706
707 Clearing the relationship:
708
709 my $dvd = $dvd_rs->recursive_update( {
710 id => 1,
711 tags => undef,
712 });
713
714 This is the same as passing an empty array:
715
716 my $dvd = $dvd_rs->recursive_update( {
717 id => 1,
718 tags => [],
719 });
720
721 =head2 Treatment of many-to-many pseudo relations
722
723 The function gets the information about m2m relations from DBIx::Class::IntrospectableM2M.
724 If it isn't loaded in the ResultSource classes the code relies on the fact that:
725
726 if($object->can($name) and
727 !$object->result_source->has_relationship($name) and
728 $object->can( 'set_' . $name )
729 )
730
731 Then $name must be a many to many pseudo relation.
732 And that in a similarly ugly was I find out what is the ResultSource of
733 objects from that many to many pseudo relation.
734
735
736 =head1 INTERFACE
737
738 =head1 METHODS
739
740 =head2 recursive_update
741
742 The method that does the work here.
743
744 =head2 is_m2m
745
746 $self->is_m2m( 'name ' ) - answers the question if 'name' is a many to many
747 (pseudo) relation on $self.
748
749 =head2 get_m2m_source
750
751 $self->get_m2m_source( 'name' ) - returns the ResultSource linked to by the many
752 to many (pseudo) relation 'name' from $self.
753
754
755 =head1 DIAGNOSTICS
756
757
758 =head1 CONFIGURATION AND ENVIRONMENT
759
760 DBIx::Class::RecursiveUpdate requires no configuration files or environment variables.
761
762 =head1 DEPENDENCIES
763
764 DBIx::Class
765
766 =head1 INCOMPATIBILITIES
767
768 None reported.
769
770
771 =head1 BUGS AND LIMITATIONS
772
773 No bugs have been reported.
774
775 Please report any bugs or feature requests to
776 C<bug-dbix-class-recursiveput@rt.cpan.org>, or through the web interface at
777 L<http://rt.cpan.org>.
This page took 0.076604 seconds and 5 git commands to generate.