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