]> Dogcows Code - chaz/p5-DBIx-Class-ResultSet-RecursiveUpdate/blob - lib/DBIx/Class/ResultSet/RecursiveUpdate.pm
doc improvements
[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
325 # only limit resultset if there are related rows left
326 if ( scalar @cond ) {
327 $rs_rel_delist =
328 $rs_rel_delist->search_rs( { -not => [@cond] } );
329 }
330 }
331
332 #warn "\tCOND: " . Dumper(\%cond);
333 #my $rel_delist_cnt = $rs_rel_delist->count;
334 if ( $if_not_submitted eq 'delete' ) {
335
336 #warn "\tdeleting related rows: $rel_delist_cnt\n";
337 $rs_rel_delist->delete;
338 }
339 elsif ( $if_not_submitted eq 'set_to_null' ) {
340
341 #warn "\tnullifying related rows: $rel_delist_cnt\n";
342 my %update = map { $_ => undef } @rel_cols;
343 $rs_rel_delist->update( \%update );
344 }
345 }
346 elsif ($info->{attrs}{accessor} eq 'single'
347 || $info->{attrs}{accessor} eq 'filter' )
348 {
349
350 #warn "\tupdating rel '$name': $if_not_submitted\n";
351 my $sub_object;
352 if ( ref $updates ) {
353
354 # for might_have relationship
355 if ( $info->{attrs}{accessor} eq 'single'
356 && defined $object->$name )
357 {
358 $sub_object = recursive_update(
359 resultset => $related_resultset,
360 updates => $updates,
361 object => $object->$name
362 );
363 }
364 else {
365 $sub_object = recursive_update(
366 resultset => $related_resultset,
367 updates => $updates,
368 resolved => $resolved
369 );
370 }
371 }
372 else {
373 $sub_object = $related_resultset->find($updates)
374 unless (
375 !$updates
376 && ( exists $info->{attrs}{join_type}
377 && $info->{attrs}{join_type} eq 'LEFT' )
378 );
379 }
380 $object->set_from_related( $name, $sub_object )
381 unless (
382 !$sub_object
383 && !$updates
384 && ( exists $info->{attrs}{join_type}
385 && $info->{attrs}{join_type} eq 'LEFT' )
386 );
387 }
388 else {
389 $self->throw_exception(
390 "recursive_update doesn't now how to handle relationship '$name' with accessor "
391 . $info->{attrs}{accessor} );
392 }
393 }
394
395 sub is_m2m {
396 my ( $self, $relation ) = @_;
397 my $rclass = $self->result_class;
398
399 # DBIx::Class::IntrospectableM2M
400 if ( $rclass->can('_m2m_metadata') ) {
401 return $rclass->_m2m_metadata->{$relation};
402 }
403 my $object = $self->new( {} );
404 if ( $object->can($relation)
405 and !$self->result_source->has_relationship($relation)
406 and $object->can( 'set_' . $relation ) )
407 {
408 return 1;
409 }
410 return;
411 }
412
413 sub get_m2m_source {
414 my ( $self, $relation ) = @_;
415 my $rclass = $self->result_class;
416
417 # DBIx::Class::IntrospectableM2M
418 if ( $rclass->can('_m2m_metadata') ) {
419 return $self->result_source->related_source(
420 $rclass->_m2m_metadata->{$relation}{relation} )
421 ->related_source(
422 $rclass->_m2m_metadata->{$relation}{foreign_relation} );
423 }
424 my $object = $self->new( {} );
425 my $r = $object->$relation;
426 return $r->result_source;
427 }
428
429 sub _delete_empty_auto_increment {
430 my ( $self, $object ) = @_;
431 for my $col ( keys %{ $object->{_column_data} } ) {
432 if ($object->result_source->column_info($col)->{is_auto_increment}
433 and ( !defined $object->{_column_data}{$col}
434 or $object->{_column_data}{$col} eq '' )
435 )
436 {
437 delete $object->{_column_data}{$col};
438 }
439 }
440 }
441
442 sub _get_pk_for_related {
443 my ( $self, $relation ) = @_;
444 my $result_source;
445 if ( $self->result_source->has_relationship($relation) ) {
446 $result_source = $self->result_source->related_source($relation);
447 }
448
449 # many to many case
450 if ( is_m2m( $self, $relation ) ) {
451 $result_source = get_m2m_source( $self, $relation );
452 }
453 return $result_source->primary_columns;
454 }
455
456 # This function determines wheter a relationship should be done before or
457 # after the row is inserted into the database
458 # relationships before: belongs_to
459 # relationships after: has_many, might_have and has_one
460 # true means before, false after
461 sub _master_relation_cond {
462 my ( $self, $name ) = @_;
463
464 my $source = $self->result_source;
465 my $info = $source->relationship_info($name);
466
467 #warn "INFO: " . Dumper($info) . "\n";
468
469 # has_many rels are always after
470 return 0
471 if $info->{attrs}->{accessor} eq 'multi';
472
473 my @foreign_ids = _get_pk_for_related( $self, $name );
474
475 #warn "IDS: " . join(', ', @foreign_ids) . "\n";
476
477 my $cond = $info->{cond};
478
479 sub _inner {
480 my ( $source, $cond, @foreign_ids ) = @_;
481
482 while ( my ( $f_key, $col ) = each %{$cond} ) {
483
484 # might_have is not master
485 $col =~ s/^self\.//;
486 $f_key =~ s/^foreign\.//;
487 if ( $source->column_info($col)->{is_auto_increment} ) {
488 return 0;
489 }
490 if ( any { $_ eq $f_key } @foreign_ids ) {
491 return 1;
492 }
493 }
494 return 0;
495 }
496
497 if ( ref $cond eq 'HASH' ) {
498 return _inner( $source, $cond, @foreign_ids );
499 }
500
501 # arrayref of hashrefs
502 elsif ( ref $cond eq 'ARRAY' ) {
503 for my $new_cond (@$cond) {
504 return _inner( $source, $new_cond, @foreign_ids );
505 }
506 }
507 else {
508 $source->throw_exception(
509 "unhandled relation condition " . ref($cond) );
510 }
511 return;
512 }
513
514 1; # Magic true value required at end of module
515 __END__
516
517 =head1 SYNOPSIS
518
519 # The functional interface:
520
521 my $schema = MyDB::Schema->connect();
522 my $new_item = DBIx::Class::ResultSet::RecursiveUpdate::Functions::recursive_update(
523 resultset => $schema->resultset('User'),
524 updates => {
525 id => 1,
526 owned_dvds => [
527 {
528 title => "One Flew Over the Cuckoo's Nest"
529 }
530 ]
531 }
532 });
533
534
535 # As ResultSet subclass:
536
537 __PACKAGE__->load_namespaces( default_resultset_class => '+DBIx::Class::ResultSet::RecursiveUpdate' );
538
539 # in the Schema file (see t/lib/DBSchema.pm). Or appropriate 'use base' in the ResultSet classes.
540
541 my $user = $schema->resultset('User')->recursive_update({
542 id => 1,
543 owned_dvds => [
544 {
545 title => "One Flew Over the Cuckoo's Nest"
546 }
547 ]
548 }, {
549 unknown_params_ok => 1,
550 });
551
552
553 =head1 DESCRIPTION
554
555 This is still experimental.
556
557 You can feed the ->create method of DBIx::Class with a recursive datastructure
558 and have the related records created. Unfortunately you cannot do a similar
559 thing with update_or_create.
560 This module tries to fill that void until L<DBIx::Class> has an api itself.
561
562 The functional interface can be used without modifications of the model,
563 for example by form processors like L<HTML::FormHandler::Model::DBIC>.
564
565 It is a base class for L<DBIx::Class::ResultSet>s providing the method recursive_update
566 which works just like update_or_create but can recursively update or create
567 data objects composed of multiple rows. All rows need to be identified by primary keys
568 - so you need to provide them in the update structure (unless they can be deduced from
569 the parent row - for example when you have a belongs_to relationship).
570 If not all columns comprising the primary key are specified a new row will be created,
571 with the expectation that the missing columns will be filled by it (as in the case of auto_increment
572 primary keys).
573
574
575 If the resultset itself stores an assignement for the primary key,
576 like in the case of:
577
578 my $restricted_rs = $user_rs->search( { id => 1 } );
579
580 then you need to inform recursive_update about additional predicate with a second argument:
581
582 my $user = $restricted_rs->recursive_update( {
583 owned_dvds => [
584 {
585 title => 'One Flew Over the Cuckoo's Nest'
586 }
587 ]
588 },
589 [ 'id' ]
590 );
591
592 For a many_to_many (pseudo) relation you can supply a list of primary keys
593 from the other table and it will link the record at hand to those and
594 only those records identified by them. This is convenient for handling web
595 forms with check boxes (or a select field with multiple choice) that lets you
596 update such (pseudo) relations.
597
598 For a description how to set up base classes for ResultSets see L<DBIx::Class::Schema/load_namespaces>.
599
600 =head1 DESIGN CHOICES
601
602 Columns and relationships which are excluded from the updates hashref aren't
603 touched at all.
604
605 =head2 Treatment of belongs_to relations
606
607 In case the relationship is included but undefined in the updates hashref,
608 all columns forming the relationship will be set to null.
609 If not all of them are nullable, DBIx::Class will throw an error.
610
611 Updating the relationship:
612
613 my $dvd = $dvd_rs->recursive_update( {
614 id => 1,
615 owner => $user->id,
616 });
617
618 Clearing the relationship (only works if cols are nullable!):
619
620 my $dvd = $dvd_rs->recursive_update( {
621 id => 1,
622 owner => undef,
623 });
624
625 =head2 Treatment of might_have relationships
626
627 In case the relationship is included but undefined in the updates hashref,
628 all columns forming the relationship will be set to null.
629
630 Updating the relationship:
631
632 my $user = $user_rs->recursive_update( {
633 id => 1,
634 address => {
635 street => "101 Main Street",
636 city => "Podunk",
637 state => "New York",
638 }
639 });
640
641 Clearing the relationship:
642
643 my $user = $user_rs->recursive_update( {
644 id => 1,
645 address => undef,
646 });
647
648 =head2 Treatment of has_many relations
649
650 If a relationship key is included in the data structure with a value of undef
651 or an empty array, all existing related rows will be deleted, or their foreign
652 key columns will be set to null.
653
654 The exact behaviour depends on the nullability of the foreign key columns and
655 the value of the "if_not_submitted" parameter. The parameter defaults to
656 undefined which neither nullifies nor deletes.
657
658 When the array contains elements they are updated if they exist, created when
659 not and deleted if not included.
660
661 =head3 All foreign table columns are nullable
662
663 In this case recursive_update defaults to nullifying the foreign columns.
664
665 =head3 Not all foreign table columns are nullable
666
667 In this case recursive_update deletes the foreign rows.
668
669 Updating the relationship:
670
671 Passing ids:
672
673 my $dvd = $dvd_rs->recursive_update( {
674 id => 1,
675 tags => [1, 2],
676 });
677
678 Passing hashrefs:
679
680 my $dvd = $dvd_rs->recursive_update( {
681 id => 1,
682 tags => [
683 {
684 id => 1,
685 file => 'file0'
686 },
687 {
688 id => 2,
689 file => 'file1',
690 },
691 ],
692 });
693
694 Passing objects:
695
696 TODO
697
698 You can even mix them:
699
700 my $dvd = $dvd_rs->recursive_update( {
701 id => 1,
702 tags => [ '2', { id => '3' } ],
703 });
704
705 Clearing the relationship:
706
707 my $dvd = $dvd_rs->recursive_update( {
708 id => 1,
709 tags => undef,
710 });
711
712 This is the same as passing an empty array:
713
714 my $dvd = $dvd_rs->recursive_update( {
715 id => 1,
716 tags => [],
717 });
718
719 =head2 Treatment of many-to-many pseudo relations
720
721 The function gets the information about m2m relations from L<DBIx::Class::IntrospectableM2M>.
722 If it isn't loaded in the ResultSource classes the code relies on the fact that:
723
724 if($object->can($name) and
725 !$object->result_source->has_relationship($name) and
726 $object->can( 'set_' . $name )
727 )
728
729 Then $name must be a many to many pseudo relation.
730 And that in a similarly ugly was I find out what is the ResultSource of
731 objects from that many to many pseudo relation.
732
733
734 =head1 INTERFACE
735
736 =head1 METHODS
737
738 =head2 recursive_update
739
740 The method that does the work here.
741
742 =head2 is_m2m
743
744 $self->is_m2m( 'name ' ) - answers the question if 'name' is a many to many
745 (pseudo) relation on $self.
746
747 =head2 get_m2m_source
748
749 $self->get_m2m_source( 'name' ) - returns the ResultSource linked to by the many
750 to many (pseudo) relation 'name' from $self.
751
752
753 =head1 DIAGNOSTICS
754
755
756 =head1 CONFIGURATION AND ENVIRONMENT
757
758 DBIx::Class::RecursiveUpdate requires no configuration files or environment variables.
759
760 =head1 DEPENDENCIES
761
762 DBIx::Class
763
764 =head1 INCOMPATIBILITIES
765
766 None reported.
767
768
769 =head1 BUGS AND LIMITATIONS
770
771 No bugs have been reported.
772
773 Please report any bugs or feature requests to
774 C<bug-dbix-class-recursiveput@rt.cpan.org>, or through the web interface at
775 L<http://rt.cpan.org>.
This page took 0.085575 seconds and 5 git commands to generate.