Reorder prefetch logic for optimal execution (no functional changes)
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Row.pm
1 package DBIx::Class::Row;
2
3 use strict;
4 use warnings;
5
6 use base qw/DBIx::Class/;
7
8 use Scalar::Util 'blessed';
9 use List::Util 'first';
10 use Try::Tiny;
11
12 ###
13 ### Internal method
14 ### Do not use
15 ###
16 BEGIN {
17   *MULTICREATE_DEBUG =
18     $ENV{DBIC_MULTICREATE_DEBUG}
19       ? sub () { 1 }
20       : sub () { 0 };
21 }
22
23 use namespace::clean;
24
25 __PACKAGE__->mk_group_accessors ( simple => [ in_storage => '_in_storage' ] );
26
27 =head1 NAME
28
29 DBIx::Class::Row - Basic row methods
30
31 =head1 SYNOPSIS
32
33 =head1 DESCRIPTION
34
35 This class is responsible for defining and doing basic operations on rows
36 derived from L<DBIx::Class::ResultSource> objects.
37
38 Result objects are returned from L<DBIx::Class::ResultSet>s using the
39 L<create|DBIx::Class::ResultSet/create>, L<find|DBIx::Class::ResultSet/find>,
40 L<next|DBIx::Class::ResultSet/next> and L<all|DBIx::Class::ResultSet/all> methods,
41 as well as invocations of 'single' (
42 L<belongs_to|DBIx::Class::Relationship/belongs_to>,
43 L<has_one|DBIx::Class::Relationship/has_one> or
44 L<might_have|DBIx::Class::Relationship/might_have>)
45 relationship accessors of L<Result|DBIx::Class::Manual::ResultClass> objects.
46
47 =head1 NOTE
48
49 All "Row objects" derived from a Schema-attached L<DBIx::Class::ResultSet>
50 object (such as a typical C<< L<search|DBIx::Class::ResultSet/search
51 >->L<next|DBIx::Class::ResultSet/next> >> call) are actually Result
52 instances, based on your application's
53 L<Result class|DBIx::Class::Manual::Glossary/Result_class>.
54
55 L<DBIx::Class::Row> implements most of the row-based communication with the
56 underlying storage, but a Result class B<should not inherit from it directly>.
57 Usually, Result classes inherit from L<DBIx::Class::Core>, which in turn
58 combines the methods from several classes, one of them being
59 L<DBIx::Class::Row>.  Therefore, while many of the methods available to a
60 L<DBIx::Class::Core>-derived Result class are described in the following
61 documentation, it does not detail all of the methods available to Result
62 objects.  Refer to L<DBIx::Class::Manual::ResultClass> for more info.
63
64 =head1 METHODS
65
66 =head2 new
67
68   my $row = My::Class->new(\%attrs);
69
70   my $row = $schema->resultset('MySource')->new(\%colsandvalues);
71
72 =over
73
74 =item Arguments: \%attrs or \%colsandvalues
75
76 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
77
78 =back
79
80 While you can create a new result object by calling C<new> directly on
81 this class, you are better off calling it on a
82 L<DBIx::Class::ResultSet> object.
83
84 When calling it directly, you will not get a complete, usable row
85 object until you pass or set the C<result_source> attribute, to a
86 L<DBIx::Class::ResultSource> instance that is attached to a
87 L<DBIx::Class::Schema> with a valid connection.
88
89 C<$attrs> is a hashref of column name, value data. It can also contain
90 some other attributes such as the C<result_source>.
91
92 Passing an object, or an arrayref of objects as a value will call
93 L<DBIx::Class::Relationship::Base/set_from_related> for you. When
94 passed a hashref or an arrayref of hashrefs as the value, these will
95 be turned into objects via new_related, and treated as if you had
96 passed objects.
97
98 For a more involved explanation, see L<DBIx::Class::ResultSet/create>.
99
100 Please note that if a value is not passed to new, no value will be sent
101 in the SQL INSERT call, and the column will therefore assume whatever
102 default value was specified in your database. While DBIC will retrieve the
103 value of autoincrement columns, it will never make an explicit database
104 trip to retrieve default values assigned by the RDBMS. You can explicitly
105 request that all values be fetched back from the database by calling
106 L</discard_changes>, or you can supply an explicit C<undef> to columns
107 with NULL as the default, and save yourself a SELECT.
108
109  CAVEAT:
110
111  The behavior described above will backfire if you use a foreign key column
112  with a database-defined default. If you call the relationship accessor on
113  an object that doesn't have a set value for the FK column, DBIC will throw
114  an exception, as it has no way of knowing the PK of the related object (if
115  there is one).
116
117 =cut
118
119 ## It needs to store the new objects somewhere, and call insert on that list later when insert is called on this object. We may need an accessor for these so the user can retrieve them, if just doing ->new().
120 ## This only works because DBIC doesnt yet care to check whether the new_related objects have been passed all their mandatory columns
121 ## When doing the later insert, we need to make sure the PKs are set.
122 ## using _relationship_data in new and funky ways..
123 ## check Relationship::CascadeActions and Relationship::Accessor for compat
124 ## tests!
125
126 sub __new_related_find_or_new_helper {
127   my ($self, $relname, $values) = @_;
128
129   my $rsrc = $self->result_source;
130
131   # create a mock-object so all new/set_column component overrides will run:
132   my $rel_rs = $rsrc->related_source($relname)->resultset;
133   my $new_rel_obj = $rel_rs->new_result($values);
134   my $proc_data = { $new_rel_obj->get_columns };
135
136   if ($self->__their_pk_needs_us($relname)) {
137     MULTICREATE_DEBUG and print STDERR "MC $self constructing $relname via new_result\n";
138     return $new_rel_obj;
139   }
140   elsif ($rsrc->_pk_depends_on($relname, $proc_data )) {
141     if (! keys %$proc_data) {
142       # there is nothing to search for - blind create
143       MULTICREATE_DEBUG and print STDERR "MC $self constructing default-insert $relname\n";
144     }
145     else {
146       MULTICREATE_DEBUG and print STDERR "MC $self constructing $relname via find_or_new\n";
147       # this is not *really* find or new, as we don't want to double-new the
148       # data (thus potentially double encoding or whatever)
149       my $exists = $rel_rs->find ($proc_data);
150       return $exists if $exists;
151     }
152     return $new_rel_obj;
153   }
154   else {
155     my $us = $rsrc->source_name;
156     $self->throw_exception (
157       "Unable to determine relationship '$relname' direction from '$us', "
158     . "possibly due to a missing reverse-relationship on '$relname' to '$us'."
159     );
160   }
161 }
162
163 sub __their_pk_needs_us { # this should maybe be in resultsource.
164   my ($self, $relname) = @_;
165   my $rsrc = $self->result_source;
166   my $reverse = $rsrc->reverse_relationship_info($relname);
167   my $rel_source = $rsrc->related_source($relname);
168   my $us = { $self->get_columns };
169   foreach my $key (keys %$reverse) {
170     # if their primary key depends on us, then we have to
171     # just create a result and we'll fill it out afterwards
172     return 1 if $rel_source->_pk_depends_on($key, $us);
173   }
174   return 0;
175 }
176
177 sub new {
178   my ($class, $attrs) = @_;
179   $class = ref $class if ref $class;
180
181   my $new = bless { _column_data => {}, _in_storage => 0 }, $class;
182
183   if ($attrs) {
184     $new->throw_exception("attrs must be a hashref")
185       unless ref($attrs) eq 'HASH';
186
187     my $rsrc = delete $attrs->{-result_source};
188     if ( my $h = delete $attrs->{-source_handle} ) {
189       $rsrc ||= $h->resolve;
190     }
191
192     $new->result_source($rsrc) if $rsrc;
193
194     if (my $col_from_rel = delete $attrs->{-cols_from_relations}) {
195       @{$new->{_ignore_at_insert}={}}{@$col_from_rel} = ();
196     }
197
198     my ($related,$inflated);
199
200     foreach my $key (keys %$attrs) {
201       if (ref $attrs->{$key}) {
202         ## Can we extract this lot to use with update(_or .. ) ?
203         $new->throw_exception("Can't do multi-create without result source")
204           unless $rsrc;
205         my $info = $rsrc->relationship_info($key);
206         my $acc_type = $info->{attrs}{accessor} || '';
207         if ($acc_type eq 'single') {
208           my $rel_obj = delete $attrs->{$key};
209           if(!blessed $rel_obj) {
210             $rel_obj = $new->__new_related_find_or_new_helper($key, $rel_obj);
211           }
212
213           if ($rel_obj->in_storage) {
214             $new->{_rel_in_storage}{$key} = 1;
215             $new->set_from_related($key, $rel_obj);
216           } else {
217             MULTICREATE_DEBUG and print STDERR "MC $new uninserted $key $rel_obj\n";
218           }
219
220           $related->{$key} = $rel_obj;
221           next;
222         }
223         elsif ($acc_type eq 'multi' && ref $attrs->{$key} eq 'ARRAY' ) {
224           my $others = delete $attrs->{$key};
225           my $total = @$others;
226           my @objects;
227           foreach my $idx (0 .. $#$others) {
228             my $rel_obj = $others->[$idx];
229             if(!blessed $rel_obj) {
230               $rel_obj = $new->__new_related_find_or_new_helper($key, $rel_obj);
231             }
232
233             if ($rel_obj->in_storage) {
234               $rel_obj->throw_exception ('A multi relationship can not be pre-existing when doing multicreate. Something went wrong');
235             } else {
236               MULTICREATE_DEBUG and
237                 print STDERR "MC $new uninserted $key $rel_obj (${\($idx+1)} of $total)\n";
238             }
239             push(@objects, $rel_obj);
240           }
241           $related->{$key} = \@objects;
242           next;
243         }
244         elsif ($acc_type eq 'filter') {
245           ## 'filter' should disappear and get merged in with 'single' above!
246           my $rel_obj = delete $attrs->{$key};
247           if(!blessed $rel_obj) {
248             $rel_obj = $new->__new_related_find_or_new_helper($key, $rel_obj);
249           }
250           if ($rel_obj->in_storage) {
251             $new->{_rel_in_storage}{$key} = 1;
252           }
253           else {
254             MULTICREATE_DEBUG and print STDERR "MC $new uninserted $key $rel_obj\n";
255           }
256           $inflated->{$key} = $rel_obj;
257           next;
258         } elsif ($class->has_column($key)
259             && $class->column_info($key)->{_inflate_info}) {
260           $inflated->{$key} = $attrs->{$key};
261           next;
262         }
263       }
264       $new->throw_exception("No such column '$key' on $class")
265         unless $class->has_column($key);
266       $new->store_column($key => $attrs->{$key});
267     }
268
269     $new->{_relationship_data} = $related if $related;
270     $new->{_inflated_column} = $inflated if $inflated;
271   }
272
273   return $new;
274 }
275
276 =head2 $column_accessor
277
278   # Each pair does the same thing
279
280   # (un-inflated, regular column)
281   my $val = $row->get_column('first_name');
282   my $val = $row->first_name;
283
284   $row->set_column('first_name' => $val);
285   $row->first_name($val);
286
287   # (inflated column via DBIx::Class::InflateColumn::DateTime)
288   my $val = $row->get_inflated_column('last_modified');
289   my $val = $row->last_modified;
290
291   $row->set_inflated_column('last_modified' => $val);
292   $row->last_modified($val);
293
294 =over
295
296 =item Arguments: $value?
297
298 =item Return Value: $value
299
300 =back
301
302 A column accessor method is created for each column, which is used for
303 getting/setting the value for that column.
304
305 The actual method name is based on the
306 L<accessor|DBIx::Class::ResultSource/accessor> name given during the
307 L<Result Class|DBIx::Class::Manual::ResultClass> L<column definition
308 |DBIx::Class::ResultSource/add_columns>. Like L</set_column>, this
309 will not store the data in the database until L</insert> or L</update>
310 is called on the row.
311
312 =head2 insert
313
314   $row->insert;
315
316 =over
317
318 =item Arguments: none
319
320 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
321
322 =back
323
324 Inserts an object previously created by L</new> into the database if
325 it isn't already in there. Returns the object itself. To insert an
326 entirely new row into the database, use L<DBIx::Class::ResultSet/create>.
327
328 To fetch an uninserted result object, call
329 L<new_result|DBIx::Class::ResultSet/new_result> on a resultset.
330
331 This will also insert any uninserted, related objects held inside this
332 one, see L<DBIx::Class::ResultSet/create> for more details.
333
334 =cut
335
336 sub insert {
337   my ($self) = @_;
338   return $self if $self->in_storage;
339   my $rsrc = $self->result_source;
340   $self->throw_exception("No result_source set on this object; can't insert")
341     unless $rsrc;
342
343   my $storage = $rsrc->storage;
344
345   my $rollback_guard;
346
347   # Check if we stored uninserted relobjs here in new()
348   my %related_stuff = (%{$self->{_relationship_data} || {}},
349                        %{$self->{_inflated_column} || {}});
350
351   # insert what needs to be inserted before us
352   my %pre_insert;
353   for my $relname (keys %related_stuff) {
354     my $rel_obj = $related_stuff{$relname};
355
356     if (! $self->{_rel_in_storage}{$relname}) {
357       next unless (blessed $rel_obj && $rel_obj->isa('DBIx::Class::Row'));
358
359       next unless $rsrc->_pk_depends_on(
360                     $relname, { $rel_obj->get_columns }
361                   );
362
363       # The guard will save us if we blow out of this scope via die
364       $rollback_guard ||= $storage->txn_scope_guard;
365
366       MULTICREATE_DEBUG and print STDERR "MC $self pre-reconstructing $relname $rel_obj\n";
367
368       my $them = { %{$rel_obj->{_relationship_data} || {} }, $rel_obj->get_columns };
369       my $existing;
370
371       # if there are no keys - nothing to search for
372       if (keys %$them and $existing = $self->result_source
373                                            ->related_source($relname)
374                                            ->resultset
375                                            ->find($them)
376       ) {
377         %{$rel_obj} = %{$existing};
378       }
379       else {
380         $rel_obj->insert;
381       }
382
383       $self->{_rel_in_storage}{$relname} = 1;
384     }
385
386     $self->set_from_related($relname, $rel_obj);
387     delete $related_stuff{$relname};
388   }
389
390   # start a transaction here if not started yet and there is more stuff
391   # to insert after us
392   if (keys %related_stuff) {
393     $rollback_guard ||= $storage->txn_scope_guard
394   }
395
396   MULTICREATE_DEBUG and do {
397     no warnings 'uninitialized';
398     print STDERR "MC $self inserting (".join(', ', $self->get_columns).")\n";
399   };
400
401   # perform the insert - the storage will return everything it is asked to
402   # (autoinc primary columns and any retrieve_on_insert columns)
403   my %current_rowdata = $self->get_columns;
404   my $returned_cols = $storage->insert(
405     $rsrc,
406     { %current_rowdata }, # what to insert, copy because the storage *will* change it
407   );
408
409   for (keys %$returned_cols) {
410     $self->store_column($_, $returned_cols->{$_})
411       # this ensures we fire store_column only once
412       # (some asshats like overriding it)
413       if (
414         (!exists $current_rowdata{$_})
415           or
416         (defined $current_rowdata{$_} xor defined $returned_cols->{$_})
417           or
418         (defined $current_rowdata{$_} and $current_rowdata{$_} ne $returned_cols->{$_})
419       );
420   }
421
422   delete $self->{_column_data_in_storage};
423   $self->in_storage(1);
424
425   $self->{_dirty_columns} = {};
426   $self->{related_resultsets} = {};
427
428   foreach my $relname (keys %related_stuff) {
429     next unless $rsrc->has_relationship ($relname);
430
431     my @cands = ref $related_stuff{$relname} eq 'ARRAY'
432       ? @{$related_stuff{$relname}}
433       : $related_stuff{$relname}
434     ;
435
436     if (@cands && blessed $cands[0] && $cands[0]->isa('DBIx::Class::Row')
437     ) {
438       my $reverse = $rsrc->reverse_relationship_info($relname);
439       foreach my $obj (@cands) {
440         $obj->set_from_related($_, $self) for keys %$reverse;
441         if ($self->__their_pk_needs_us($relname)) {
442           if (exists $self->{_ignore_at_insert}{$relname}) {
443             MULTICREATE_DEBUG and print STDERR "MC $self skipping post-insert on $relname\n";
444           }
445           else {
446             MULTICREATE_DEBUG and print STDERR "MC $self inserting $relname $obj\n";
447             $obj->insert;
448           }
449         } else {
450           MULTICREATE_DEBUG and print STDERR "MC $self post-inserting $obj\n";
451           $obj->insert();
452         }
453       }
454     }
455   }
456
457   delete $self->{_ignore_at_insert};
458
459   $rollback_guard->commit if $rollback_guard;
460
461   return $self;
462 }
463
464 =head2 in_storage
465
466   $row->in_storage; # Get value
467   $row->in_storage(1); # Set value
468
469 =over
470
471 =item Arguments: none or 1|0
472
473 =item Return Value: 1|0
474
475 =back
476
477 Indicates whether the object exists as a row in the database or
478 not. This is set to true when L<DBIx::Class::ResultSet/find>,
479 L<DBIx::Class::ResultSet/create> or L<DBIx::Class::ResultSet/insert>
480 are used.
481
482 Creating a result object using L<DBIx::Class::ResultSet/new_result>, or
483 calling L</delete> on one, sets it to false.
484
485
486 =head2 update
487
488   $row->update(\%columns?)
489
490 =over
491
492 =item Arguments: none or a hashref
493
494 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
495
496 =back
497
498 Throws an exception if the result object is not yet in the database,
499 according to L</in_storage>.
500
501 This method issues an SQL UPDATE query to commit any changes to the
502 object to the database if required (see L</get_dirty_columns>).
503 It throws an exception if a proper WHERE clause uniquely identifying
504 the database row can not be constructed (see
505 L<significance of primary keys|DBIx::Class::Manual::Intro/The Significance and Importance of Primary Keys>
506 for more details).
507
508 Also takes an optional hashref of C<< column_name => value >> pairs
509 to update on the object first. Be aware that the hashref will be
510 passed to C<set_inflated_columns>, which might edit it in place, so
511 don't rely on it being the same after a call to C<update>.  If you
512 need to preserve the hashref, it is sufficient to pass a shallow copy
513 to C<update>, e.g. ( { %{ $href } } )
514
515 If the values passed or any of the column values set on the object
516 contain scalar references, e.g.:
517
518   $row->last_modified(\'NOW()')->update();
519   # OR
520   $row->update({ last_modified => \'NOW()' });
521
522 The update will pass the values verbatim into SQL. (See
523 L<SQL::Abstract> docs).  The values in your Result object will NOT change
524 as a result of the update call, if you want the object to be updated
525 with the actual values from the database, call L</discard_changes>
526 after the update.
527
528   $row->update()->discard_changes();
529
530 To determine before calling this method, which column values have
531 changed and will be updated, call L</get_dirty_columns>.
532
533 To check if any columns will be updated, call L</is_changed>.
534
535 To force a column to be updated, call L</make_column_dirty> before
536 this method.
537
538 =cut
539
540 sub update {
541   my ($self, $upd) = @_;
542
543   $self->set_inflated_columns($upd) if $upd;
544
545   my %to_update = $self->get_dirty_columns
546     or return $self;
547
548   $self->throw_exception( "Not in database" ) unless $self->in_storage;
549
550   my $rows = $self->result_source->storage->update(
551     $self->result_source, \%to_update, $self->_storage_ident_condition
552   );
553   if ($rows == 0) {
554     $self->throw_exception( "Can't update ${self}: row not found" );
555   } elsif ($rows > 1) {
556     $self->throw_exception("Can't update ${self}: updated more than one row");
557   }
558   $self->{_dirty_columns} = {};
559   $self->{related_resultsets} = {};
560   delete $self->{_column_data_in_storage};
561   return $self;
562 }
563
564 =head2 delete
565
566   $row->delete
567
568 =over
569
570 =item Arguments: none
571
572 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
573
574 =back
575
576 Throws an exception if the object is not in the database according to
577 L</in_storage>. Also throws an exception if a proper WHERE clause
578 uniquely identifying the database row can not be constructed (see
579 L<significance of primary keys|DBIx::Class::Manual::Intro/The Significance and Importance of Primary Keys>
580 for more details).
581
582 The object is still perfectly usable, but L</in_storage> will
583 now return 0 and the object must be reinserted using L</insert>
584 before it can be used to L</update> the row again.
585
586 If you delete an object in a class with a C<has_many> relationship, an
587 attempt is made to delete all the related objects as well. To turn
588 this behaviour off, pass C<< cascade_delete => 0 >> in the C<$attr>
589 hashref of the relationship, see L<DBIx::Class::Relationship>. Any
590 database-level cascade or restrict will take precedence over a
591 DBIx-Class-based cascading delete, since DBIx-Class B<deletes the
592 main row first> and only then attempts to delete any remaining related
593 rows.
594
595 If you delete an object within a txn_do() (see L<DBIx::Class::Storage/txn_do>)
596 and the transaction subsequently fails, the result object will remain marked as
597 not being in storage. If you know for a fact that the object is still in
598 storage (i.e. by inspecting the cause of the transaction's failure), you can
599 use C<< $obj->in_storage(1) >> to restore consistency between the object and
600 the database. This would allow a subsequent C<< $obj->delete >> to work
601 as expected.
602
603 See also L<DBIx::Class::ResultSet/delete>.
604
605 =cut
606
607 sub delete {
608   my $self = shift;
609   if (ref $self) {
610     $self->throw_exception( "Not in database" ) unless $self->in_storage;
611
612     $self->result_source->storage->delete(
613       $self->result_source, $self->_storage_ident_condition
614     );
615
616     delete $self->{_column_data_in_storage};
617     $self->in_storage(0);
618   }
619   else {
620     my $rsrc = try { $self->result_source_instance }
621       or $self->throw_exception("Can't do class delete without a ResultSource instance");
622
623     my $attrs = @_ > 1 && ref $_[$#_] eq 'HASH' ? { %{pop(@_)} } : {};
624     my $query = ref $_[0] eq 'HASH' ? $_[0] : {@_};
625     $rsrc->resultset->search(@_)->delete;
626   }
627   return $self;
628 }
629
630 =head2 get_column
631
632   my $val = $row->get_column($col);
633
634 =over
635
636 =item Arguments: $columnname
637
638 =item Return Value: The value of the column
639
640 =back
641
642 Throws an exception if the column name given doesn't exist according
643 to L<has_column|DBIx::Class::ResultSource/has_column>.
644
645 Returns a raw column value from the result object, if it has already
646 been fetched from the database or set by an accessor.
647
648 If an L<inflated value|DBIx::Class::InflateColumn> has been set, it
649 will be deflated and returned.
650
651 Note that if you used the C<columns> or the C<select/as>
652 L<search attributes|DBIx::Class::ResultSet/ATTRIBUTES> on the resultset from
653 which C<$row> was derived, and B<did not include> C<$columnname> in the list,
654 this method will return C<undef> even if the database contains some value.
655
656 To retrieve all loaded column values as a hash, use L</get_columns>.
657
658 =cut
659
660 sub get_column {
661   my ($self, $column) = @_;
662   $self->throw_exception( "Can't fetch data as class method" ) unless ref $self;
663   return $self->{_column_data}{$column} if exists $self->{_column_data}{$column};
664   if (exists $self->{_inflated_column}{$column}) {
665     return $self->store_column($column,
666       $self->_deflated_column($column, $self->{_inflated_column}{$column}));
667   }
668   $self->throw_exception( "No such column '${column}'" ) unless $self->has_column($column);
669   return undef;
670 }
671
672 =head2 has_column_loaded
673
674   if ( $row->has_column_loaded($col) ) {
675      print "$col has been loaded from db";
676   }
677
678 =over
679
680 =item Arguments: $columnname
681
682 =item Return Value: 0|1
683
684 =back
685
686 Returns a true value if the column value has been loaded from the
687 database (or set locally).
688
689 =cut
690
691 sub has_column_loaded {
692   my ($self, $column) = @_;
693   $self->throw_exception( "Can't call has_column data as class method" ) unless ref $self;
694   return 1 if exists $self->{_inflated_column}{$column};
695   return exists $self->{_column_data}{$column};
696 }
697
698 =head2 get_columns
699
700   my %data = $row->get_columns;
701
702 =over
703
704 =item Arguments: none
705
706 =item Return Value: A hash of columnname, value pairs.
707
708 =back
709
710 Returns all loaded column data as a hash, containing raw values. To
711 get just one value for a particular column, use L</get_column>.
712
713 See L</get_inflated_columns> to get the inflated values.
714
715 =cut
716
717 sub get_columns {
718   my $self = shift;
719   if (exists $self->{_inflated_column}) {
720     foreach my $col (keys %{$self->{_inflated_column}}) {
721       $self->store_column($col, $self->_deflated_column($col, $self->{_inflated_column}{$col}))
722         unless exists $self->{_column_data}{$col};
723     }
724   }
725   return %{$self->{_column_data}};
726 }
727
728 =head2 get_dirty_columns
729
730   my %data = $row->get_dirty_columns;
731
732 =over
733
734 =item Arguments: none
735
736 =item Return Value: A hash of column, value pairs
737
738 =back
739
740 Only returns the column, value pairs for those columns that have been
741 changed on this object since the last L</update> or L</insert> call.
742
743 See L</get_columns> to fetch all column/value pairs.
744
745 =cut
746
747 sub get_dirty_columns {
748   my $self = shift;
749   return map { $_ => $self->{_column_data}{$_} }
750            keys %{$self->{_dirty_columns}};
751 }
752
753 =head2 make_column_dirty
754
755   $row->make_column_dirty($col)
756
757 =over
758
759 =item Arguments: $columnname
760
761 =item Return Value: not defined
762
763 =back
764
765 Throws an exception if the column does not exist.
766
767 Marks a column as having been changed regardless of whether it has
768 really changed.
769
770 =cut
771
772 sub make_column_dirty {
773   my ($self, $column) = @_;
774
775   $self->throw_exception( "No such column '${column}'" )
776     unless exists $self->{_column_data}{$column} || $self->has_column($column);
777
778   # the entire clean/dirty code relies on exists, not on true/false
779   return 1 if exists $self->{_dirty_columns}{$column};
780
781   $self->{_dirty_columns}{$column} = 1;
782
783   # if we are just now making the column dirty, and if there is an inflated
784   # value, force it over the deflated one
785   if (exists $self->{_inflated_column}{$column}) {
786     $self->store_column($column,
787       $self->_deflated_column(
788         $column, $self->{_inflated_column}{$column}
789       )
790     );
791   }
792 }
793
794 =head2 get_inflated_columns
795
796   my %inflated_data = $obj->get_inflated_columns;
797
798 =over
799
800 =item Arguments: none
801
802 =item Return Value: A hash of column, object|value pairs
803
804 =back
805
806 Returns a hash of all column keys and associated values. Values for any
807 columns set to use inflation will be inflated and returns as objects.
808
809 See L</get_columns> to get the uninflated values.
810
811 See L<DBIx::Class::InflateColumn> for how to setup inflation.
812
813 =cut
814
815 sub get_inflated_columns {
816   my $self = shift;
817
818   my $loaded_colinfo = $self->columns_info ([
819     grep { $self->has_column_loaded($_) } $self->columns
820   ]);
821
822   my %inflated;
823   for my $col (keys %$loaded_colinfo) {
824     if (exists $loaded_colinfo->{$col}{accessor}) {
825       my $acc = $loaded_colinfo->{$col}{accessor};
826       $inflated{$col} = $self->$acc if defined $acc;
827     }
828     else {
829       $inflated{$col} = $self->$col;
830     }
831   }
832
833   # return all loaded columns with the inflations overlayed on top
834   return %{ { $self->get_columns, %inflated } };
835 }
836
837 sub _is_column_numeric {
838    my ($self, $column) = @_;
839     my $colinfo = $self->column_info ($column);
840
841     # cache for speed (the object may *not* have a resultsource instance)
842     if (
843       ! defined $colinfo->{is_numeric}
844         and
845       my $storage = try { $self->result_source->schema->storage }
846     ) {
847       $colinfo->{is_numeric} =
848         $storage->is_datatype_numeric ($colinfo->{data_type})
849           ? 1
850           : 0
851         ;
852     }
853
854     return $colinfo->{is_numeric};
855 }
856
857 =head2 set_column
858
859   $row->set_column($col => $val);
860
861 =over
862
863 =item Arguments: $columnname, $value
864
865 =item Return Value: $value
866
867 =back
868
869 Sets a raw column value. If the new value is different from the old one,
870 the column is marked as dirty for when you next call L</update>.
871
872 If passed an object or reference as a value, this method will happily
873 attempt to store it, and a later L</insert> or L</update> will try and
874 stringify/numify as appropriate. To set an object to be deflated
875 instead, see L</set_inflated_columns>, or better yet, use L</$column_accessor>.
876
877 =cut
878
879 sub set_column {
880   my ($self, $column, $new_value) = @_;
881
882   my $had_value = $self->has_column_loaded($column);
883   my ($old_value, $in_storage) = ($self->get_column($column), $self->in_storage)
884     if $had_value;
885
886   $new_value = $self->store_column($column, $new_value);
887
888   my $dirty =
889     $self->{_dirty_columns}{$column}
890       ||
891     $in_storage # no point tracking dirtyness on uninserted data
892       ? ! $self->_eq_column_values ($column, $old_value, $new_value)
893       : 1
894   ;
895
896   if ($dirty) {
897     # FIXME sadly the update code just checks for keys, not for their value
898     $self->{_dirty_columns}{$column} = 1;
899
900     # Clear out the relation/inflation cache related to this column
901     #
902     # FIXME - this is a quick *largely incorrect* hack, pending a more
903     # serious rework during the merge of single and filter rels
904     my $relnames = $self->result_source->{_relationships};
905     for my $relname (keys %$relnames) {
906
907       my $acc = $relnames->{$relname}{attrs}{accessor} || '';
908
909       if ( $acc eq 'single' and $relnames->{$relname}{attrs}{fk_columns}{$column} ) {
910         delete $self->{related_resultsets}{$relname};
911         delete $self->{_relationship_data}{$relname};
912         #delete $self->{_inflated_column}{$relname};
913       }
914       elsif ( $acc eq 'filter' and $relname eq $column) {
915         delete $self->{related_resultsets}{$relname};
916         #delete $self->{_relationship_data}{$relname};
917         delete $self->{_inflated_column}{$relname};
918       }
919     }
920
921     if (
922       # value change from something (even if NULL)
923       $had_value
924         and
925       # no storage - no storage-value
926       $in_storage
927         and
928       # no value already stored (multiple changes before commit to storage)
929       ! exists $self->{_column_data_in_storage}{$column}
930         and
931       $self->_track_storage_value($column)
932     ) {
933       $self->{_column_data_in_storage}{$column} = $old_value;
934     }
935   }
936
937   return $new_value;
938 }
939
940 sub _eq_column_values {
941   my ($self, $col, $old, $new) = @_;
942
943   if (defined $old xor defined $new) {
944     return 0;
945   }
946   elsif (not defined $old) {  # both undef
947     return 1;
948   }
949   elsif ($old eq $new) {
950     return 1;
951   }
952   elsif ($self->_is_column_numeric($col)) {  # do a numeric comparison if datatype allows it
953     return $old == $new;
954   }
955   else {
956     return 0;
957   }
958 }
959
960 # returns a boolean indicating if the passed column should have its original
961 # value tracked between column changes and commitment to storage
962 sub _track_storage_value {
963   my ($self, $col) = @_;
964   return defined first { $col eq $_ } ($self->primary_columns);
965 }
966
967 =head2 set_columns
968
969   $row->set_columns({ $col => $val, ... });
970
971 =over
972
973 =item Arguments: \%columndata
974
975 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
976
977 =back
978
979 Sets multiple column, raw value pairs at once.
980
981 Works as L</set_column>.
982
983 =cut
984
985 sub set_columns {
986   my ($self, $values) = @_;
987   $self->set_column( $_, $values->{$_} ) for keys %$values;
988   return $self;
989 }
990
991 =head2 set_inflated_columns
992
993   $row->set_inflated_columns({ $col => $val, $relname => $obj, ... });
994
995 =over
996
997 =item Arguments: \%columndata
998
999 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
1000
1001 =back
1002
1003 Sets more than one column value at once. Any inflated values are
1004 deflated and the raw values stored.
1005
1006 Any related values passed as Result objects, using the relation name as a
1007 key, are reduced to the appropriate foreign key values and stored. If
1008 instead of related result objects, a hashref of column, value data is
1009 passed, will create the related object first then store.
1010
1011 Will even accept arrayrefs of data as a value to a
1012 L<DBIx::Class::Relationship/has_many> key, and create the related
1013 objects if necessary.
1014
1015 Be aware that the input hashref might be edited in place, so don't rely
1016 on it being the same after a call to C<set_inflated_columns>. If you
1017 need to preserve the hashref, it is sufficient to pass a shallow copy
1018 to C<set_inflated_columns>, e.g. ( { %{ $href } } )
1019
1020 See also L<DBIx::Class::Relationship::Base/set_from_related>.
1021
1022 =cut
1023
1024 sub set_inflated_columns {
1025   my ( $self, $upd ) = @_;
1026   foreach my $key (keys %$upd) {
1027     if (ref $upd->{$key}) {
1028       my $info = $self->relationship_info($key);
1029       my $acc_type = $info->{attrs}{accessor} || '';
1030       if ($acc_type eq 'single') {
1031         my $rel_obj = delete $upd->{$key};
1032         $self->set_from_related($key => $rel_obj);
1033         $self->{_relationship_data}{$key} = $rel_obj;
1034       }
1035       elsif ($acc_type eq 'multi') {
1036         $self->throw_exception(
1037           "Recursive update is not supported over relationships of type '$acc_type' ($key)"
1038         );
1039       }
1040       elsif ($self->has_column($key) && exists $self->column_info($key)->{_inflate_info}) {
1041         $self->set_inflated_column($key, delete $upd->{$key});
1042       }
1043     }
1044   }
1045   $self->set_columns($upd);
1046 }
1047
1048 =head2 copy
1049
1050   my $copy = $orig->copy({ change => $to, ... });
1051
1052 =over
1053
1054 =item Arguments: \%replacementdata
1055
1056 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> copy
1057
1058 =back
1059
1060 Inserts a new row into the database, as a copy of the original
1061 object. If a hashref of replacement data is supplied, these will take
1062 precedence over data in the original. Also any columns which have
1063 the L<column info attribute|DBIx::Class::ResultSource/add_columns>
1064 C<< is_auto_increment => 1 >> are explicitly removed before the copy,
1065 so that the database can insert its own autoincremented values into
1066 the new object.
1067
1068 Relationships will be followed by the copy procedure B<only> if the
1069 relationship specifies a true value for its
1070 L<cascade_copy|DBIx::Class::Relationship::Base> attribute. C<cascade_copy>
1071 is set by default on C<has_many> relationships and unset on all others.
1072
1073 =cut
1074
1075 sub copy {
1076   my ($self, $changes) = @_;
1077   $changes ||= {};
1078   my $col_data = { %{$self->{_column_data}} };
1079
1080   my $colinfo = $self->columns_info([ keys %$col_data ]);
1081   foreach my $col (keys %$col_data) {
1082     delete $col_data->{$col}
1083       if $colinfo->{$col}{is_auto_increment};
1084   }
1085
1086   my $new = { _column_data => $col_data };
1087   bless $new, ref $self;
1088
1089   $new->result_source($self->result_source);
1090   $new->set_inflated_columns($changes);
1091   $new->insert;
1092
1093   # Its possible we'll have 2 relations to the same Source. We need to make
1094   # sure we don't try to insert the same row twice else we'll violate unique
1095   # constraints
1096   my $relnames_copied = {};
1097
1098   foreach my $relname ($self->result_source->relationships) {
1099     my $rel_info = $self->result_source->relationship_info($relname);
1100
1101     next unless $rel_info->{attrs}{cascade_copy};
1102
1103     my $resolved = $self->result_source->_resolve_condition(
1104       $rel_info->{cond}, $relname, $new, $relname
1105     );
1106
1107     my $copied = $relnames_copied->{ $rel_info->{source} } ||= {};
1108     foreach my $related ($self->search_related($relname)) {
1109       my $id_str = join("\0", $related->id);
1110       next if $copied->{$id_str};
1111       $copied->{$id_str} = 1;
1112       my $rel_copy = $related->copy($resolved);
1113     }
1114
1115   }
1116   return $new;
1117 }
1118
1119 =head2 store_column
1120
1121   $row->store_column($col => $val);
1122
1123 =over
1124
1125 =item Arguments: $columnname, $value
1126
1127 =item Return Value: The value sent to storage
1128
1129 =back
1130
1131 Set a raw value for a column without marking it as changed. This
1132 method is used internally by L</set_column> which you should probably
1133 be using.
1134
1135 This is the lowest level at which data is set on a result object,
1136 extend this method to catch all data setting methods.
1137
1138 =cut
1139
1140 sub store_column {
1141   my ($self, $column, $value) = @_;
1142   $self->throw_exception( "No such column '${column}'" )
1143     unless exists $self->{_column_data}{$column} || $self->has_column($column);
1144   $self->throw_exception( "set_column called for ${column} without value" )
1145     if @_ < 3;
1146   return $self->{_column_data}{$column} = $value;
1147 }
1148
1149 =head2 inflate_result
1150
1151   Class->inflate_result($result_source, \%me, \%prefetch?)
1152
1153 =over
1154
1155 =item Arguments: L<$result_source|DBIx::Class::ResultSource>, \%columndata, \%prefetcheddata
1156
1157 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
1158
1159 =back
1160
1161 All L<DBIx::Class::ResultSet> methods that retrieve data from the
1162 database and turn it into result objects call this method.
1163
1164 Extend this method in your Result classes to hook into this process,
1165 for example to rebless the result into a different class.
1166
1167 Reblessing can also be done more easily by setting C<result_class> in
1168 your Result class. See L<DBIx::Class::ResultSource/result_class>.
1169
1170 Different types of results can also be created from a particular
1171 L<DBIx::Class::ResultSet>, see L<DBIx::Class::ResultSet/result_class>.
1172
1173 =cut
1174
1175 sub inflate_result {
1176   my ($class, $rsrc, $me, $prefetch) = @_;
1177
1178   my $new = bless
1179     { _column_data => $me, _result_source => $rsrc },
1180     ref $class || $class
1181   ;
1182
1183   if ($prefetch) {
1184     for my $relname ( keys %$prefetch ) {
1185
1186       my $relinfo = $rsrc->relationship_info($relname) or do {
1187         my $err = sprintf
1188           "Inflation into non-existent relationship '%s' of '%s' requested",
1189           $relname,
1190           $rsrc->source_name,
1191         ;
1192         if (my ($colname) = sort { length($a) <=> length ($b) } keys %{$prefetch->{$relname}[0] || {}} ) {
1193           $err .= sprintf ", check the inflation specification (columns/as) ending in '...%s.%s'",
1194           $relname,
1195           $colname,
1196         }
1197
1198         $rsrc->throw_exception($err);
1199       };
1200
1201       $class->throw_exception("No accessor type declared for prefetched relationship '$relname'")
1202         unless $relinfo->{attrs}{accessor};
1203
1204       my @rel_objects;
1205       if (
1206         $prefetch->{$relname}
1207           and
1208         @{$prefetch->{$relname}}
1209           and
1210         ref($prefetch->{$relname}) ne $DBIx::Class::ResultSource::RowParser::Util::null_branch_class
1211       ) {
1212
1213         my $rel_rs = $new->related_resultset($relname);
1214
1215         if (ref $prefetch->{$relname}[0] eq 'ARRAY') {
1216           my $rel_rsrc = $rel_rs->result_source;
1217           my $rel_class = $rel_rs->result_class;
1218           my $rel_inflator = $rel_class->can('inflate_result');
1219           @rel_objects = map
1220             { $rel_class->$rel_inflator ( $rel_rsrc, @$_ ) }
1221             @{$prefetch->{$relname}}
1222           ;
1223         }
1224         else {
1225           @rel_objects = $rel_rs->result_class->inflate_result(
1226             $rel_rs->result_source, @{$prefetch->{$relname}}
1227           );
1228         }
1229       }
1230
1231       if ($relinfo->{attrs}{accessor} eq 'single') {
1232         $new->{_relationship_data}{$relname} = $rel_objects[0];
1233       }
1234       elsif ($relinfo->{attrs}{accessor} eq 'filter') {
1235         $new->{_inflated_column}{$relname} = $rel_objects[0];
1236       }
1237
1238       $new->related_resultset($relname)->set_cache(\@rel_objects);
1239     }
1240   }
1241
1242   $new->in_storage (1);
1243   return $new;
1244 }
1245
1246 =head2 update_or_insert
1247
1248   $row->update_or_insert
1249
1250 =over
1251
1252 =item Arguments: none
1253
1254 =item Return Value: Result of update or insert operation
1255
1256 =back
1257
1258 L</Update>s the object if it's already in the database, according to
1259 L</in_storage>, else L</insert>s it.
1260
1261 =head2 insert_or_update
1262
1263   $obj->insert_or_update
1264
1265 Alias for L</update_or_insert>
1266
1267 =cut
1268
1269 sub insert_or_update { shift->update_or_insert(@_) }
1270
1271 sub update_or_insert {
1272   my $self = shift;
1273   return ($self->in_storage ? $self->update : $self->insert);
1274 }
1275
1276 =head2 is_changed
1277
1278   my @changed_col_names = $row->is_changed();
1279   if ($row->is_changed()) { ... }
1280
1281 =over
1282
1283 =item Arguments: none
1284
1285 =item Return Value: 0|1 or @columnnames
1286
1287 =back
1288
1289 In list context returns a list of columns with uncommited changes, or
1290 in scalar context returns a true value if there are uncommitted
1291 changes.
1292
1293 =cut
1294
1295 sub is_changed {
1296   return keys %{shift->{_dirty_columns} || {}};
1297 }
1298
1299 =head2 is_column_changed
1300
1301   if ($row->is_column_changed('col')) { ... }
1302
1303 =over
1304
1305 =item Arguments: $columname
1306
1307 =item Return Value: 0|1
1308
1309 =back
1310
1311 Returns a true value if the column has uncommitted changes.
1312
1313 =cut
1314
1315 sub is_column_changed {
1316   my( $self, $col ) = @_;
1317   return exists $self->{_dirty_columns}->{$col};
1318 }
1319
1320 =head2 result_source
1321
1322   my $resultsource = $row->result_source;
1323
1324 =over
1325
1326 =item Arguments: L<$result_source?|DBIx::Class::ResultSource>
1327
1328 =item Return Value: L<$result_source|DBIx::Class::ResultSource>
1329
1330 =back
1331
1332 Accessor to the L<DBIx::Class::ResultSource> this object was created from.
1333
1334 =cut
1335
1336 sub result_source {
1337   $_[0]->throw_exception( 'result_source can be called on instances only' )
1338     unless ref $_[0];
1339
1340   @_ > 1
1341     ? $_[0]->{_result_source} = $_[1]
1342
1343     # note this is a || not a ||=, the difference is important
1344     : $_[0]->{_result_source} || do {
1345         my $class = ref $_[0];
1346         $_[0]->can('result_source_instance')
1347           ? $_[0]->result_source_instance
1348           : $_[0]->throw_exception(
1349             "No result source instance registered for $class, did you forget to call $class->table(...) ?"
1350           )
1351       }
1352   ;
1353 }
1354
1355 =head2 register_column
1356
1357   $column_info = { .... };
1358   $class->register_column($column_name, $column_info);
1359
1360 =over
1361
1362 =item Arguments: $columnname, \%columninfo
1363
1364 =item Return Value: not defined
1365
1366 =back
1367
1368 Registers a column on the class. If the column_info has an 'accessor'
1369 key, creates an accessor named after the value if defined; if there is
1370 no such key, creates an accessor with the same name as the column
1371
1372 The column_info attributes are described in
1373 L<DBIx::Class::ResultSource/add_columns>
1374
1375 =cut
1376
1377 sub register_column {
1378   my ($class, $col, $info) = @_;
1379   my $acc = $col;
1380   if (exists $info->{accessor}) {
1381     return unless defined $info->{accessor};
1382     $acc = [ $info->{accessor}, $col ];
1383   }
1384   $class->mk_group_accessors('column' => $acc);
1385 }
1386
1387 =head2 get_from_storage
1388
1389   my $copy = $row->get_from_storage($attrs)
1390
1391 =over
1392
1393 =item Arguments: \%attrs
1394
1395 =item Return Value: A Result object
1396
1397 =back
1398
1399 Fetches a fresh copy of the Result object from the database and returns it.
1400 Throws an exception if a proper WHERE clause identifying the database row
1401 can not be constructed (i.e. if the original object does not contain its
1402 entire
1403  L<primary key|DBIx::Class::Manual::Intro/The Significance and Importance of Primary Keys>
1404 ). If passed the \%attrs argument, will first apply these attributes to
1405 the resultset used to find the row.
1406
1407 This copy can then be used to compare to an existing result object, to
1408 determine if any changes have been made in the database since it was
1409 created.
1410
1411 To just update your Result object with any latest changes from the
1412 database, use L</discard_changes> instead.
1413
1414 The \%attrs argument should be compatible with
1415 L<DBIx::Class::ResultSet/ATTRIBUTES>.
1416
1417 =cut
1418
1419 sub get_from_storage {
1420     my $self = shift @_;
1421     my $attrs = shift @_;
1422     my $resultset = $self->result_source->resultset;
1423
1424     if(defined $attrs) {
1425       $resultset = $resultset->search(undef, $attrs);
1426     }
1427
1428     return $resultset->find($self->_storage_ident_condition);
1429 }
1430
1431 =head2 discard_changes
1432
1433   $row->discard_changes
1434
1435 =over
1436
1437 =item Arguments: none or $attrs
1438
1439 =item Return Value: self (updates object in-place)
1440
1441 =back
1442
1443 Re-selects the row from the database, losing any changes that had
1444 been made. Throws an exception if a proper C<WHERE> clause identifying
1445 the database row can not be constructed (i.e. if the original object
1446 does not contain its entire
1447 L<primary key|DBIx::Class::Manual::Intro/The Significance and Importance of Primary Keys>).
1448
1449 This method can also be used to refresh from storage, retrieving any
1450 changes made since the row was last read from storage.
1451
1452 $attrs, if supplied, is expected to be a hashref of attributes suitable for passing as the
1453 second argument to C<< $resultset->search($cond, $attrs) >>;
1454
1455 Note: If you are using L<DBIx::Class::Storage::DBI::Replicated> as your
1456 storage, please kept in mind that if you L</discard_changes> on a row that you
1457 just updated or created, you should wrap the entire bit inside a transaction.
1458 Otherwise you run the risk that you insert or update to the master database
1459 but read from a replicant database that has not yet been updated from the
1460 master.  This will result in unexpected results.
1461
1462 =cut
1463
1464 sub discard_changes {
1465   my ($self, $attrs) = @_;
1466   return unless $self->in_storage; # Don't reload if we aren't real!
1467
1468   # add a replication default to read from the master only
1469   $attrs = { force_pool => 'master', %{$attrs||{}} };
1470
1471   if( my $current_storage = $self->get_from_storage($attrs)) {
1472
1473     # Set $self to the current.
1474     %$self = %$current_storage;
1475
1476     # Avoid a possible infinite loop with
1477     # sub DESTROY { $_[0]->discard_changes }
1478     bless $current_storage, 'Do::Not::Exist';
1479
1480     return $self;
1481   }
1482   else {
1483     $self->in_storage(0);
1484     return $self;
1485   }
1486 }
1487
1488 =head2 throw_exception
1489
1490 See L<DBIx::Class::Schema/throw_exception>.
1491
1492 =cut
1493
1494 sub throw_exception {
1495   my $self=shift;
1496
1497   if (ref $self && ref $self->result_source ) {
1498     $self->result_source->throw_exception(@_)
1499   }
1500   else {
1501     DBIx::Class::Exception->throw(@_);
1502   }
1503 }
1504
1505 =head2 id
1506
1507   my @pk = $row->id;
1508
1509 =over
1510
1511 =item Arguments: none
1512
1513 =item Returns: A list of primary key values
1514
1515 =back
1516
1517 Returns the primary key(s) for a row. Can't be called as a class method.
1518 Actually implemented in L<DBIx::Class::PK>
1519
1520 =head1 AUTHOR AND CONTRIBUTORS
1521
1522 See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class
1523
1524 =head1 LICENSE
1525
1526 You may distribute this code under the same terms as Perl itself.
1527
1528 =cut
1529
1530 1;