test fixups
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Row.pm
CommitLineData
7624b19f 1package DBIx::Class::Row;
2
3use strict;
4use warnings;
5
1edd1722 6use base qw/DBIx::Class/;
701da8c4 7use Carp::Clan qw/^DBIx::Class/;
1edd1722 8
097d3227 9__PACKAGE__->load_components(qw/AccessorGroup/);
10
11__PACKAGE__->mk_group_accessors('simple' => 'result_source');
8c49f629 12
75d07914 13=head1 NAME
7624b19f 14
15DBIx::Class::Row - Basic row methods
16
17=head1 SYNOPSIS
18
19=head1 DESCRIPTION
20
21This class is responsible for defining and doing basic operations on rows
1ea77c14 22derived from L<DBIx::Class::ResultSource> objects.
7624b19f 23
24=head1 METHODS
25
8091aa91 26=head2 new
7624b19f 27
28 my $obj = My::Class->new($attrs);
29
30Creates a new row object from column => value mappings passed as a hash ref
31
32=cut
33
34sub new {
35 my ($class, $attrs) = @_;
36 $class = ref $class if ref $class;
04786a4c 37
38 my $new = { _column_data => {} };
39 bless $new, $class;
40
7624b19f 41 if ($attrs) {
27f01d1f 42 $new->throw_exception("attrs must be a hashref")
43 unless ref($attrs) eq 'HASH';
096f4212 44 if (my $source = delete $attrs->{-result_source}) {
45 $new->result_source($source);
46 }
a2ca474b 47 foreach my $k (keys %$attrs) {
27f01d1f 48 $new->throw_exception("No such column $k on $class")
75d07914 49 unless $class->has_column($k);
a2ca474b 50 $new->store_column($k => $attrs->{$k});
7624b19f 51 }
52 }
04786a4c 53
7624b19f 54 return $new;
55}
56
8091aa91 57=head2 insert
7624b19f 58
59 $obj->insert;
60
b8810cc5 61Inserts an object into the database if it isn't already in
62there. Returns the object itself. Requires the object's result source to
63be set, or the class to have a result_source_instance method. To insert
64an entirely new object into the database, use C<create> (see
65L<DBIx::Class::ResultSet/create>).
7624b19f 66
67=cut
68
69sub insert {
70 my ($self) = @_;
71 return $self if $self->in_storage;
097d3227 72 $self->{result_source} ||= $self->result_source_instance
73 if $self->can('result_source_instance');
74 my $source = $self->{result_source};
aeb1bf75 75 $self->throw_exception("No result_source set on this object; can't insert")
76 unless $source;
7624b19f 77 #use Data::Dumper; warn Dumper($self);
097d3227 78 $source->storage->insert($source->from, { $self->get_columns });
7624b19f 79 $self->in_storage(1);
80 $self->{_dirty_columns} = {};
64acc2bc 81 $self->{related_resultsets} = {};
729b29ae 82 undef $self->{_orig_ident};
7624b19f 83 return $self;
84}
85
8091aa91 86=head2 in_storage
7624b19f 87
88 $obj->in_storage; # Get value
89 $obj->in_storage(1); # Set value
90
91Indicated whether the object exists as a row in the database or not
92
93=cut
94
95sub in_storage {
96 my ($self, $val) = @_;
97 $self->{_in_storage} = $val if @_ > 1;
98 return $self->{_in_storage};
99}
100
8091aa91 101=head2 update
7624b19f 102
d5d833d9 103 $obj->update \%columns?;
7624b19f 104
105Must be run on an object that is already in the database; issues an SQL
d3b0e369 106UPDATE query to commit any changes to the object to the database if
107required.
7624b19f 108
d5d833d9 109Also takes an options hashref of C<< column_name => value> pairs >> to update
110first. But be aware that this hashref might be edited in place, so dont rely on
8b621a87 111it being the same after a call to C<update>. If you need to preserve the hashref,
112it is sufficient to pass a shallow copy to C<update>, e.g. ( { %{ $href } } )
d5d833d9 113
7624b19f 114=cut
115
116sub update {
117 my ($self, $upd) = @_;
701da8c4 118 $self->throw_exception( "Not in database" ) unless $self->in_storage;
c56897b4 119 my $ident_cond = $self->ident_condition;
120 $self->throw_exception("Cannot safely update a row in a PK-less table")
121 if ! keys %$ident_cond;
5a9e0e60 122 $self->set_columns($upd) if $upd;
123 my %to_update = $self->get_dirty_columns;
124 return $self unless keys %to_update;
88cb6a1d 125 my $rows = $self->result_source->storage->update(
6c299e8b 126 $self->result_source->from, \%to_update, $self->{_orig_ident} || $ident_cond);
7624b19f 127 if ($rows == 0) {
701da8c4 128 $self->throw_exception( "Can't update ${self}: row not found" );
7624b19f 129 } elsif ($rows > 1) {
701da8c4 130 $self->throw_exception("Can't update ${self}: updated more than one row");
7624b19f 131 }
132 $self->{_dirty_columns} = {};
64acc2bc 133 $self->{related_resultsets} = {};
729b29ae 134 undef $self->{_orig_ident};
7624b19f 135 return $self;
136}
137
8091aa91 138=head2 delete
7624b19f 139
140 $obj->delete
141
b8810cc5 142Deletes the object from the database. The object is still perfectly
143usable, but C<-E<gt>in_storage()> will now return 0 and the object must
144reinserted using C<-E<gt>insert()> before C<-E(<gt>update()> can be used
145on it. If you delete an object in a class with a C<has_many>
146relationship, all the related objects will be deleted as well. To turn
147this behavior off, pass C<cascade_delete => 0> in the C<$attr>
148hashref. Any database-level cascade or restrict will take precedence
149over a DBIx-Class-based cascading delete. See also L<DBIx::Class::ResultSet/delete>.
7624b19f 150
151=cut
152
153sub delete {
154 my $self = shift;
155 if (ref $self) {
701da8c4 156 $self->throw_exception( "Not in database" ) unless $self->in_storage;
4b12b3c2 157 my $ident_cond = $self->ident_condition;
158 $self->throw_exception("Cannot safely delete a row in a PK-less table")
159 if ! keys %$ident_cond;
e0f56292 160 foreach my $column (keys %$ident_cond) {
75d07914 161 $self->throw_exception("Can't delete the object unless it has loaded the primary keys")
162 unless exists $self->{_column_data}{$column};
e0f56292 163 }
88cb6a1d 164 $self->result_source->storage->delete(
4b12b3c2 165 $self->result_source->from, $ident_cond);
7624b19f 166 $self->in_storage(undef);
7624b19f 167 } else {
701da8c4 168 $self->throw_exception("Can't do class delete without a ResultSource instance")
097d3227 169 unless $self->can('result_source_instance');
aeb1bf75 170 my $attrs = @_ > 1 && ref $_[$#_] eq 'HASH' ? { %{pop(@_)} } : {};
171 my $query = ref $_[0] eq 'HASH' ? $_[0] : {@_};
097d3227 172 $self->result_source_instance->resultset->search(@_)->delete;
7624b19f 173 }
174 return $self;
175}
176
8091aa91 177=head2 get_column
7624b19f 178
179 my $val = $obj->get_column($col);
180
8091aa91 181Gets a column value from a row object. Currently, does not do
182any queries; the column must have already been fetched from
183the database and stored in the object.
7624b19f 184
185=cut
186
187sub get_column {
188 my ($self, $column) = @_;
701da8c4 189 $self->throw_exception( "Can't fetch data as class method" ) unless ref $self;
aeb1bf75 190 return $self->{_column_data}{$column} if exists $self->{_column_data}{$column};
701da8c4 191 $self->throw_exception( "No such column '${column}'" ) unless $self->has_column($column);
7624b19f 192 return undef;
193}
194
9b83fccd 195=head2 has_column_loaded
196
197 if ( $obj->has_column_loaded($col) ) {
198 print "$col has been loaded from db";
199 }
200
201Returns a true value if the column value has been loaded from the
202database (or set locally).
203
204=cut
205
def81720 206sub has_column_loaded {
207 my ($self, $column) = @_;
208 $self->throw_exception( "Can't call has_column data as class method" ) unless ref $self;
aeb1bf75 209 return exists $self->{_column_data}{$column};
def81720 210}
211
8091aa91 212=head2 get_columns
076a6864 213
214 my %data = $obj->get_columns;
215
8091aa91 216Does C<get_column>, for all column values at once.
076a6864 217
218=cut
219
220sub get_columns {
221 my $self = shift;
cb5f2eea 222 return %{$self->{_column_data}};
d7156e50 223}
224
225=head2 get_dirty_columns
226
227 my %data = $obj->get_dirty_columns;
228
229Identical to get_columns but only returns those that have been changed.
230
231=cut
232
233sub get_dirty_columns {
234 my $self = shift;
235 return map { $_ => $self->{_column_data}{$_} }
236 keys %{$self->{_dirty_columns}};
076a6864 237}
238
8091aa91 239=head2 set_column
7624b19f 240
241 $obj->set_column($col => $val);
242
8091aa91 243Sets a column value. If the new value is different from the old one,
244the column is marked as dirty for when you next call $obj->update.
7624b19f 245
246=cut
247
248sub set_column {
249 my $self = shift;
250 my ($column) = @_;
729b29ae 251 $self->{_orig_ident} ||= $self->ident_condition;
7624b19f 252 my $old = $self->get_column($column);
253 my $ret = $self->store_column(@_);
87772e46 254 $self->{_dirty_columns}{$column} = 1
255 if (defined $old ^ defined $ret) || (defined $old && $old ne $ret);
7624b19f 256 return $ret;
257}
258
8091aa91 259=head2 set_columns
076a6864 260
dc818523 261 my $copy = $orig->set_columns({ $col => $val, ... });
076a6864 262
8091aa91 263Sets more than one column value at once.
076a6864 264
265=cut
266
267sub set_columns {
268 my ($self,$data) = @_;
a2ca474b 269 foreach my $col (keys %$data) {
270 $self->set_column($col,$data->{$col});
076a6864 271 }
c01ab172 272 return $self;
076a6864 273}
274
8091aa91 275=head2 copy
076a6864 276
277 my $copy = $orig->copy({ change => $to, ... });
278
8091aa91 279Inserts a new row with the specified changes.
076a6864 280
281=cut
282
c01ab172 283sub copy {
284 my ($self, $changes) = @_;
333cce60 285 $changes ||= {};
fde6e28e 286 my $col_data = { %{$self->{_column_data}} };
287 foreach my $col (keys %$col_data) {
288 delete $col_data->{$col}
289 if $self->result_source->column_info($col)->{is_auto_increment};
290 }
04786a4c 291
292 my $new = { _column_data => $col_data };
293 bless $new, ref $self;
294
83419ec6 295 $new->result_source($self->result_source);
ecd1f408 296 $new->set_columns($changes);
333cce60 297 $new->insert;
298 foreach my $rel ($self->result_source->relationships) {
299 my $rel_info = $self->result_source->relationship_info($rel);
300 if ($rel_info->{attrs}{cascade_copy}) {
301 my $resolved = $self->result_source->resolve_condition(
302 $rel_info->{cond}, $rel, $new);
303 foreach my $related ($self->search_related($rel)) {
304 $related->copy($resolved);
305 }
306 }
307 }
2c4c67b6 308 return $new;
c01ab172 309}
310
8091aa91 311=head2 store_column
7624b19f 312
313 $obj->store_column($col => $val);
314
8091aa91 315Sets a column value without marking it as dirty.
7624b19f 316
317=cut
318
319sub store_column {
320 my ($self, $column, $value) = @_;
75d07914 321 $self->throw_exception( "No such column '${column}'" )
d7156e50 322 unless exists $self->{_column_data}{$column} || $self->has_column($column);
75d07914 323 $self->throw_exception( "set_column called for ${column} without value" )
7624b19f 324 if @_ < 3;
325 return $self->{_column_data}{$column} = $value;
326}
327
b52e9bf8 328=head2 inflate_result
329
c01ab172 330 Class->inflate_result($result_source, \%me, \%prefetch?)
b52e9bf8 331
332Called by ResultSet to inflate a result from storage
333
334=cut
335
336sub inflate_result {
c01ab172 337 my ($class, $source, $me, $prefetch) = @_;
b52e9bf8 338 #use Data::Dumper; print Dumper(@_);
04786a4c 339 my $new = {
340 result_source => $source,
341 _column_data => $me,
342 _in_storage => 1
343 };
344 bless $new, (ref $class || $class);
345
7fb16f1a 346 my $schema;
64acc2bc 347 foreach my $pre (keys %{$prefetch||{}}) {
348 my $pre_val = $prefetch->{$pre};
f9cc31dd 349 my $pre_source = $source->related_source($pre);
a86b1efe 350 $class->throw_exception("Can't prefetch non-existent relationship ${pre}")
351 unless $pre_source;
0f66a01b 352 if (ref($pre_val->[0]) eq 'ARRAY') { # multi
a86b1efe 353 my @pre_objects;
354 foreach my $pre_rec (@$pre_val) {
75d07914 355 unless ($pre_source->primary_columns == grep { exists $pre_rec->[0]{$_}
5a5bec6c 356 and defined $pre_rec->[0]{$_} } $pre_source->primary_columns) {
a86b1efe 357 next;
358 }
359 push(@pre_objects, $pre_source->result_class->inflate_result(
360 $pre_source, @{$pre_rec}));
361 }
362 $new->related_resultset($pre)->set_cache(\@pre_objects);
62e87ea8 363 } elsif (defined $pre_val->[0]) {
a86b1efe 364 my $fetched;
75d07914 365 unless ($pre_source->primary_columns == grep { exists $pre_val->[0]{$_}
a86b1efe 366 and !defined $pre_val->[0]{$_} } $pre_source->primary_columns)
367 {
368 $fetched = $pre_source->result_class->inflate_result(
75d07914 369 $pre_source, @{$pre_val});
a86b1efe 370 }
371 my $accessor = $source->relationship_info($pre)->{attrs}{accessor};
372 $class->throw_exception("No accessor for prefetched $pre")
373 unless defined $accessor;
374 if ($accessor eq 'single') {
375 $new->{_relationship_data}{$pre} = $fetched;
376 } elsif ($accessor eq 'filter') {
377 $new->{_inflated_column}{$pre} = $fetched;
378 } else {
379 $class->throw_exception("Prefetch not supported with accessor '$accessor'");
380 }
b52e9bf8 381 }
382 }
7624b19f 383 return $new;
384}
385
9b465d00 386=head2 update_or_insert
7624b19f 387
9b465d00 388 $obj->update_or_insert
7624b19f 389
8091aa91 390Updates the object if it's already in the db, else inserts it.
7624b19f 391
9b83fccd 392=head2 insert_or_update
393
394 $obj->insert_or_update
395
396Alias for L</update_or_insert>
397
7624b19f 398=cut
399
9b465d00 400*insert_or_update = \&update_or_insert;
401sub update_or_insert {
7624b19f 402 my $self = shift;
403 return ($self->in_storage ? $self->update : $self->insert);
404}
405
8091aa91 406=head2 is_changed
7624b19f 407
228dbcb4 408 my @changed_col_names = $obj->is_changed();
409 if ($obj->is_changed()) { ... }
7624b19f 410
9b83fccd 411In array context returns a list of columns with uncommited changes, or
412in scalar context returns a true value if there are uncommitted
413changes.
414
7624b19f 415=cut
416
417sub is_changed {
418 return keys %{shift->{_dirty_columns} || {}};
419}
228dbcb4 420
421=head2 is_column_changed
422
423 if ($obj->is_column_changed('col')) { ... }
424
9b83fccd 425Returns a true value if the column has uncommitted changes.
426
228dbcb4 427=cut
428
429sub is_column_changed {
430 my( $self, $col ) = @_;
431 return exists $self->{_dirty_columns}->{$col};
432}
7624b19f 433
097d3227 434=head2 result_source
435
9b83fccd 436 my $resultsource = $object->result_source;
097d3227 437
9b83fccd 438Accessor to the ResultSource this object was created from
87c4e602 439
9b83fccd 440=head2 register_column
27f01d1f 441
9b83fccd 442 $column_info = { .... };
443 $class->register_column($column_name, $column_info);
27f01d1f 444
9b83fccd 445Registers a column on the class. If the column_info has an 'accessor'
446key, creates an accessor named after the value if defined; if there is
447no such key, creates an accessor with the same name as the column
1f23a877 448
9b83fccd 449The column_info attributes are described in
450L<DBIx::Class::ResultSource/add_columns>
1f23a877 451
097d3227 452=cut
453
1f23a877 454sub register_column {
455 my ($class, $col, $info) = @_;
91b0fbd7 456 my $acc = $col;
457 if (exists $info->{accessor}) {
458 return unless defined $info->{accessor};
459 $acc = [ $info->{accessor}, $col ];
460 }
461 $class->mk_group_accessors('column' => $acc);
1f23a877 462}
463
701da8c4 464
5160b401 465=head2 throw_exception
701da8c4 466
467See Schema's throw_exception.
468
469=cut
470
471sub throw_exception {
472 my $self=shift;
473 if (ref $self && ref $self->result_source) {
474 $self->result_source->schema->throw_exception(@_);
475 } else {
476 croak(@_);
477 }
478}
479
7624b19f 4801;
481
7624b19f 482=head1 AUTHORS
483
daec44b8 484Matt S. Trout <mst@shadowcatsystems.co.uk>
7624b19f 485
486=head1 LICENSE
487
488You may distribute this code under the same terms as Perl itself.
489
490=cut