more debug warnings and comments
[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 our $VERSION = '0.013';
7
8 use base qw(DBIx::Class::ResultSet);
9
10 sub recursive_update {
11 my ( $self, $updates, $fixed_fields ) = @_;
12 return
13 DBIx::Class::ResultSet::RecursiveUpdate::Functions::recursive_update(
14 resultset => $self,
15 updates => $updates,
16 fixed_fields => $fixed_fields
17 );
18 }
19
20 package DBIx::Class::ResultSet::RecursiveUpdate::Functions;
21 use Carp;
22 use Scalar::Util qw( blessed );
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 my $info = $source->relationship_info($name);
95 if (_master_relation_cond(
96 $source, $info->{cond},
97 _get_pk_for_related( $self, $name )
98 )
99 )
100 {
101
102 #warn "$name is a pre-update rel\n";
103 $pre_updates{$name} = $updates->{$name};
104 next;
105 }
106 else {
107
108 #warn "$name is a post-update rel\n";
109 $post_updates{$name} = $updates->{$name};
110 next;
111 }
112 }
113
114 # many-to-many helper accessors
115 if ( is_m2m( $self, $name ) ) {
116
117 #warn "$name is a many-to-many helper accessor\n";
118 $other_methods{$name} = $updates->{$name};
119 next;
120 }
121
122 # accessors
123 if ( $object->can($name) && not $source->has_relationship($name) ) {
124
125 #warn "$name is an accessor";
126 $other_methods{$name} = $updates->{$name};
127 next;
128 }
129
130 # unknown
131 # TODO: don't throw a warning instead of an exception to give users
132 # time to adapt to the new API
133 $self->throw_exception(
134 "No such column, relationship, many-to-many helper accessor or generic accessor '$name'"
135 );
136 }
137
138 # warn 'other: ' . Dumper( \%other_methods ); use Data::Dumper;
139
140 # first update columns and other accessors
141 # so that later related records can be found
142 for my $name ( keys %columns ) {
143 #warn "update col $name\n";
144 $object->$name( $columns{$name} );
145 }
146 for my $name ( keys %other_methods ) {
147 #warn "update other $name\n";
148 $object->$name( $updates->{$name} );
149 }
150 for my $name ( keys %pre_updates ) {
151 #warn "pre_update $name\n";
152 _update_relation( $self, $name, $pre_updates{$name}, $object,
153 $if_not_submitted );
154 }
155
156 # $self->_delete_empty_auto_increment($object);
157 # don't allow insert to recurse to related objects
158 # do the recursion ourselves
159 # $object->{_rel_in_storage} = 1;
160 #warn "CHANGED: " . $object->is_changed . " IN STOR: " . $object->in_storage . "\n";
161 $object->update_or_insert if $object->is_changed;
162
163 # updating many_to_many
164 for my $name ( keys %$updates ) {
165 next if exists $columns{$name};
166 my $value = $updates->{$name};
167
168 if ( is_m2m( $self, $name ) ) {
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 #warn "post_update $name\n";
202 _update_relation( $self, $name, $post_updates{$name}, $object,
203 $if_not_submitted );
204 }
205 return $object;
206 }
207
208 # returns DBIx::Class::ResultSource::column_info as a hash indexed by column accessor || name
209 sub _get_columns_by_accessor {
210 my $self = shift;
211 my $source = $self->result_source;
212 my %columns;
213 for my $name ( $source->columns ) {
214 my $info = $source->column_info($name);
215 $info->{name} = $name;
216 $columns{ $info->{accessor} || $name } = $info;
217 }
218 return %columns;
219 }
220
221 # Arguments: $rs, $name, $updates, $row, $if_not_submitted
222
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) . " IN STOR: " . $object->in_storage . "\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
245 # warn "$name resolved: " . Dumper( $resolved ); use Data::Dumper;
246 $resolved = {}
247 if defined $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION
248 && $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION
249 == $resolved;
250
251 my $rel_col_cnt = scalar keys %{ $info->{cond} };
252 use Data::Dumper;
253 warn "RELINFO for $name: " . Dumper($info);
254 warn "REL_COL_CNT: $rel_col_cnt";
255
256 #warn "REV RELINFO for $name: " . Dumper($revrelinfo);
257
258 # the only valid datatype for a has_many rels is an arrayref
259 if ( $info->{attrs}{accessor} eq 'multi' ) {
260 $self->throw_exception(
261 "data for has_many relationship '$name' must be an arrayref")
262 unless ref $updates eq 'ARRAY';
263
264 my @updated_ids;
265 for my $sub_updates ( @{$updates} ) {
266 my $sub_object = recursive_update(
267 resultset => $related_resultset,
268 updates => $sub_updates,
269 resolved => $resolved
270 );
271 push @updated_ids, $sub_object->id;
272 }
273 my @related_pks = $related_resultset->result_source->primary_columns;
274 if ( defined $if_not_submitted && $if_not_submitted eq 'delete' ) {
275
276 # only handles related result classes with single primary keys
277 if ( 1 == scalar @related_pks ) {
278 $object->$name->search(
279 { $related_pks[0] => { -not_in => \@updated_ids } } )
280 ->delete;
281 }
282 }
283 elsif ( defined $if_not_submitted
284 && $if_not_submitted eq 'set_to_null' )
285 {
286
287 # only handles related result classes with single primary keys
288 if ( 1 == scalar @related_pks ) {
289 my @fk = keys %$resolved;
290 $object->$name->search(
291 { $related_pks[0] => { -not_in => \@updated_ids } } )
292 ->update( { $fk[0] => undef } );
293 }
294 }
295 }
296 elsif ($info->{attrs}{accessor} eq 'single'
297 || $info->{attrs}{accessor} eq 'filter' )
298 {
299 #warn "\tupdating rel '$name': $if_not_submitted\n";
300 my $sub_object;
301 if ( ref $updates ) {
302
303 # for might_have relationship
304 if ( $info->{attrs}{accessor} eq 'single'
305 && defined $object->$name )
306 {
307 $sub_object = recursive_update(
308 resultset => $related_resultset,
309 updates => $updates,
310 object => $object->$name
311 );
312 }
313 else {
314 $sub_object = recursive_update(
315 resultset => $related_resultset,
316 updates => $updates,
317 resolved => $resolved
318 );
319 }
320 }
321 else {
322 $sub_object = $related_resultset->find($updates)
323 unless (
324 !$updates
325 && ( exists $info->{attrs}{join_type}
326 && $info->{attrs}{join_type} eq 'LEFT' )
327 );
328 }
329 $object->set_from_related( $name, $sub_object )
330 unless (
331 !$sub_object
332 && !$updates
333 && ( exists $info->{attrs}{join_type}
334 && $info->{attrs}{join_type} eq 'LEFT' )
335 );
336 }
337 else {
338 $self->throw_exception(
339 "recursive_update doesn't now how to handle relationship '$name' with accessor "
340 . $info->{attrs}{accessor} );
341 }
342 }
343
344 sub is_m2m {
345 my ( $self, $relation ) = @_;
346 my $rclass = $self->result_class;
347
348 # DBIx::Class::IntrospectableM2M
349 if ( $rclass->can('_m2m_metadata') ) {
350 return $rclass->_m2m_metadata->{$relation};
351 }
352 my $object = $self->new( {} );
353 if ( $object->can($relation)
354 and !$self->result_source->has_relationship($relation)
355 and $object->can( 'set_' . $relation ) )
356 {
357 return 1;
358 }
359 return;
360 }
361
362 sub get_m2m_source {
363 my ( $self, $relation ) = @_;
364 my $rclass = $self->result_class;
365
366 # DBIx::Class::IntrospectableM2M
367 if ( $rclass->can('_m2m_metadata') ) {
368 return $self->result_source->related_source(
369 $rclass->_m2m_metadata->{$relation}{relation} )
370 ->related_source(
371 $rclass->_m2m_metadata->{$relation}{foreign_relation} );
372 }
373 my $object = $self->new( {} );
374 my $r = $object->$relation;
375 return $r->result_source;
376 }
377
378 sub _delete_empty_auto_increment {
379 my ( $self, $object ) = @_;
380 for my $col ( keys %{ $object->{_column_data} } ) {
381 if ($object->result_source->column_info($col)->{is_auto_increment}
382 and ( !defined $object->{_column_data}{$col}
383 or $object->{_column_data}{$col} eq '' )
384 )
385 {
386 delete $object->{_column_data}{$col};
387 }
388 }
389 }
390
391 sub _get_pk_for_related {
392 my ( $self, $relation ) = @_;
393 my $result_source;
394 if ( $self->result_source->has_relationship($relation) ) {
395 $result_source = $self->result_source->related_source($relation);
396 }
397
398 # many to many case
399 if ( is_m2m( $self, $relation ) ) {
400 $result_source = get_m2m_source( $self, $relation );
401 }
402 return $result_source->primary_columns;
403 }
404
405 # This function determines wheter a relationship should be done before or
406 # after the row is inserted into the database
407 # relationships before: belongs_to
408 # relationships after: has_many, might_have and has_one
409 # true means before, false after
410 sub _master_relation_cond {
411 my ( $source, $cond, @foreign_ids ) = @_;
412 my $foreign_ids_re = join '|', @foreign_ids;
413 if ( ref $cond eq 'HASH' ) {
414 for my $f_key ( keys %{$cond} ) {
415
416 # might_have is not master
417 my $col = $cond->{$f_key};
418 $col =~ s/self\.//;
419 if ( $source->column_info($col)->{is_auto_increment} ) {
420 return 0;
421 }
422 if ( $f_key =~ /^foreign\.$foreign_ids_re/ ) {
423 return 1;
424 }
425 }
426 }
427 elsif ( ref $cond eq 'ARRAY' ) {
428 for my $new_cond (@$cond) {
429 return _master_relation_cond( $source, $new_cond, @foreign_ids );
430 }
431 }
432 return;
433 }
434
435 1; # Magic true value required at end of module
436 __END__
437
438 =head1 NAME
439
440 DBIx::Class::ResultSet::RecursiveUpdate - like update_or_create - but recursive
441
442 =head1 SYNOPSIS
443
444 The functional interface:
445
446 my $new_item = DBIx::Class::ResultSet::RecursiveUpdate::Functions::recursive_update({
447 resultset => $schema->resultset( 'Dvd' ),
448 updates => {
449 id => 1,
450 owned_dvds => [
451 {
452 title => 'One Flew Over the Cuckoo's Nest'
453 }
454 ]
455 }
456 });
457
458
459 As ResultSet subclass:
460
461 __PACKAGE__->load_namespaces( default_resultset_class => '+DBIx::Class::ResultSet::RecursiveUpdate' );
462
463 in the Schema file (see t/lib/DBSchema.pm). Or appriopriate 'use base' in the ResultSet classes.
464
465 Then:
466
467 my $user = $user_rs->recursive_update( {
468 id => 1,
469 owned_dvds => [
470 {
471 title => 'One Flew Over the Cuckoo's Nest'
472 }
473 ]
474 }
475 );
476
477
478 =head1 DESCRIPTION
479
480 This is still experimental. I've added a functional interface so that it can be used
481 in Form Processors and not require modification of the model.
482
483 You can feed the ->create method with a recursive datastructure and have the related records
484 created. Unfortunately you cannot do a similar thing with update_or_create - this module
485 tries to fill that void.
486
487 It is a base class for ResultSets providing just one method: recursive_update
488 which works just like update_or_create but can recursively update or create
489 data objects composed of multiple rows. All rows need to be identified by primary keys
490 - so you need to provide them in the update structure (unless they can be deduced from
491 the parent row - for example when you have a belongs_to relationship).
492 If not all colums comprising the primary key are specified - then a new row will be created,
493 with the expectation that the missing columns will be filled by it (as in the case of auto_increment
494 primary keys).
495
496
497 If the resultset itself stores an assignement for the primary key,
498 like in the case of:
499
500 my $restricted_rs = $user_rs->search( { id => 1 } );
501
502 then you need to inform recursive_update about additional predicate with a second argument:
503
504 my $user = $restricted_rs->recursive_update( {
505 owned_dvds => [
506 {
507 title => 'One Flew Over the Cuckoo's Nest'
508 }
509 ]
510 },
511 [ 'id' ]
512 );
513
514 This will work with a new DBIC release.
515
516 For a many_to_many (pseudo) relation you can supply a list of primary keys
517 from the other table - and it will link the record at hand to those and
518 only those records identified by them. This is convenient for handling web
519 forms with check boxes (or a SELECT box with multiple choice) that let you
520 update such (pseudo) relations.
521
522 For a description how to set up base classes for ResultSets see load_namespaces
523 in DBIx::Class::Schema.
524
525 =head1 DESIGN CHOICES
526
527 Columns and relationships which are excluded from the updates hashref aren't
528 touched at all.
529
530 =head2 Treatment of belongs_to relations
531
532 In case the relationship is included but undefined in the updates hashref,
533 all columns forming the relationship will be set to null.
534 If not all of them are nullable, DBIx::Class will throw an error.
535
536 Updating the relationship:
537
538 my $dvd = $dvd_rs->recursive_update( {
539 id => 1,
540 owner => $user->id,
541 });
542
543 Clearing the relationship (only works if cols are nullable!):
544
545 my $dvd = $dvd_rs->recursive_update( {
546 id => 1,
547 owner => undef,
548 });
549
550 =head2 Treatment of might_have relationships
551
552 In case the relationship is included but undefined in the updates hashref,
553 all columns forming the relationship will be set to null.
554
555 Updating the relationship:
556
557 my $user = $user_rs->recursive_update( {
558 id => 1,
559 address => {
560 street => "101 Main Street",
561 city => "Podunk",
562 state => "New York",
563 }
564 });
565
566 Clearing the relationship:
567
568 my $user = $user_rs->recursive_update( {
569 id => 1,
570 address => undef,
571 });
572
573 =head2 Treatment of has_many relations
574
575 If a relationship key is included in the data structure with a value of undef
576 or an empty array, all existing related rows will be deleted, or their foreign
577 key columns will be set to null.
578
579 The exact behaviour depends on the nullability of the foreign key columns and
580 the value of the "if_not_submitted" parameter. The parameter defaults to
581 undefined which neither nullifies nor deletes.
582
583 When the array contains elements they are updated if they exist, created when
584 not and deleted if not included.
585
586 =head3 All foreign table columns are nullable
587
588 In this case recursive_update defaults to nullifying the foreign columns.
589
590 =head3 Not all foreign table columns are nullable
591
592 In this case recursive_update deletes the foreign rows.
593
594 Updating the relationship:
595
596 Passing ids:
597
598 my $dvd = $dvd_rs->recursive_update( {
599 id => 1,
600 tags => [1, 2],
601 });
602
603 Passing hashrefs:
604
605 my $dvd = $dvd_rs->recursive_update( {
606 id => 1,
607 tags => [
608 {
609 id => 1,
610 file => 'file0'
611 },
612 {
613 id => 2,
614 file => 'file1',
615 },
616 ],
617 });
618
619 Passing objects:
620
621 TODO
622
623 You can even mix them:
624
625 my $dvd = $dvd_rs->recursive_update( {
626 id => 1,
627 tags => [ '2', { id => '3' } ],
628 });
629
630 Clearing the relationship:
631
632 my $dvd = $dvd_rs->recursive_update( {
633 id => 1,
634 tags => undef,
635 });
636
637 This is the same as passing an empty array:
638
639 my $dvd = $dvd_rs->recursive_update( {
640 id => 1,
641 tags => [],
642 });
643
644 =head2 Treatment of many-to-many pseudo relations
645
646 The function gets the information about m2m relations from DBIx::Class::IntrospectableM2M.
647 If it isn't loaded in the ResultSource classes the code relies on the fact that:
648
649 if($object->can($name) and
650 !$object->result_source->has_relationship($name) and
651 $object->can( 'set_' . $name )
652 )
653
654 Then $name must be a many to many pseudo relation.
655 And that in a similarly ugly was I find out what is the ResultSource of
656 objects from that many to many pseudo relation.
657
658
659 =head1 INTERFACE
660
661 =head1 METHODS
662
663 =head2 recursive_update
664
665 The method that does the work here.
666
667 =head2 is_m2m
668
669 $self->is_m2m( 'name ' ) - answers the question if 'name' is a many to many
670 (pseudo) relation on $self.
671
672 =head2 get_m2m_source
673
674 $self->get_m2m_source( 'name' ) - returns the ResultSource linked to by the many
675 to many (pseudo) relation 'name' from $self.
676
677
678 =head1 DIAGNOSTICS
679
680
681 =head1 CONFIGURATION AND ENVIRONMENT
682
683 DBIx::Class::RecursiveUpdate requires no configuration files or environment variables.
684
685 =head1 DEPENDENCIES
686
687 DBIx::Class
688
689 =head1 INCOMPATIBILITIES
690
691 None reported.
692
693
694 =head1 BUGS AND LIMITATIONS
695
696 No bugs have been reported.
697
698 Please report any bugs or feature requests to
699 C<bug-dbix-class-recursiveput@rt.cpan.org>, or through the web interface at
700 L<http://rt.cpan.org>.
701
702
703 =head1 AUTHOR
704
705 Zbigniew Lukasiak C<< <zby@cpan.org> >>
706 Influenced by code by Pedro Melo.
707
708 =head1 LICENCE AND COPYRIGHT
709
710 Copyright (c) 2008, Zbigniew Lukasiak C<< <zby@cpan.org> >>. All rights reserved.
711
712 This module is free software; you can redistribute it and/or
713 modify it under the same terms as Perl itself. See L<perlartistic>.
714
715
716 =head1 DISCLAIMER OF WARRANTY
717
718 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
719 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
720 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
721 PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
722 EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
723 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
724 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
725 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
726 NECESSARY SERVICING, REPAIR, OR CORRECTION.
727
728 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
729 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
730 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
731 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
732 OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
733 THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
734 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
735 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
736 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
737 SUCH DAMAGES.
This page took 0.084833 seconds and 4 git commands to generate.