Make POD a little more obvious about component order
[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
103 $obj->update;
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
109=cut
110
111sub update {
112 my ($self, $upd) = @_;
701da8c4 113 $self->throw_exception( "Not in database" ) unless $self->in_storage;
c56897b4 114 my $ident_cond = $self->ident_condition;
115 $self->throw_exception("Cannot safely update a row in a PK-less table")
116 if ! keys %$ident_cond;
5a9e0e60 117 $self->set_columns($upd) if $upd;
118 my %to_update = $self->get_dirty_columns;
119 return $self unless keys %to_update;
88cb6a1d 120 my $rows = $self->result_source->storage->update(
6c299e8b 121 $self->result_source->from, \%to_update, $self->{_orig_ident} || $ident_cond);
7624b19f 122 if ($rows == 0) {
701da8c4 123 $self->throw_exception( "Can't update ${self}: row not found" );
7624b19f 124 } elsif ($rows > 1) {
701da8c4 125 $self->throw_exception("Can't update ${self}: updated more than one row");
7624b19f 126 }
127 $self->{_dirty_columns} = {};
64acc2bc 128 $self->{related_resultsets} = {};
729b29ae 129 undef $self->{_orig_ident};
7624b19f 130 return $self;
131}
132
8091aa91 133=head2 delete
7624b19f 134
135 $obj->delete
136
b8810cc5 137Deletes the object from the database. The object is still perfectly
138usable, but C<-E<gt>in_storage()> will now return 0 and the object must
139reinserted using C<-E<gt>insert()> before C<-E(<gt>update()> can be used
140on it. If you delete an object in a class with a C<has_many>
141relationship, all the related objects will be deleted as well. To turn
142this behavior off, pass C<cascade_delete => 0> in the C<$attr>
143hashref. Any database-level cascade or restrict will take precedence
144over a DBIx-Class-based cascading delete. See also L<DBIx::Class::ResultSet/delete>.
7624b19f 145
146=cut
147
148sub delete {
149 my $self = shift;
150 if (ref $self) {
701da8c4 151 $self->throw_exception( "Not in database" ) unless $self->in_storage;
4b12b3c2 152 my $ident_cond = $self->ident_condition;
153 $self->throw_exception("Cannot safely delete a row in a PK-less table")
154 if ! keys %$ident_cond;
e0f56292 155 foreach my $column (keys %$ident_cond) {
75d07914 156 $self->throw_exception("Can't delete the object unless it has loaded the primary keys")
157 unless exists $self->{_column_data}{$column};
e0f56292 158 }
88cb6a1d 159 $self->result_source->storage->delete(
4b12b3c2 160 $self->result_source->from, $ident_cond);
7624b19f 161 $self->in_storage(undef);
7624b19f 162 } else {
701da8c4 163 $self->throw_exception("Can't do class delete without a ResultSource instance")
097d3227 164 unless $self->can('result_source_instance');
aeb1bf75 165 my $attrs = @_ > 1 && ref $_[$#_] eq 'HASH' ? { %{pop(@_)} } : {};
166 my $query = ref $_[0] eq 'HASH' ? $_[0] : {@_};
097d3227 167 $self->result_source_instance->resultset->search(@_)->delete;
7624b19f 168 }
169 return $self;
170}
171
8091aa91 172=head2 get_column
7624b19f 173
174 my $val = $obj->get_column($col);
175
8091aa91 176Gets a column value from a row object. Currently, does not do
177any queries; the column must have already been fetched from
178the database and stored in the object.
7624b19f 179
180=cut
181
182sub get_column {
183 my ($self, $column) = @_;
701da8c4 184 $self->throw_exception( "Can't fetch data as class method" ) unless ref $self;
aeb1bf75 185 return $self->{_column_data}{$column} if exists $self->{_column_data}{$column};
701da8c4 186 $self->throw_exception( "No such column '${column}'" ) unless $self->has_column($column);
7624b19f 187 return undef;
188}
189
9b83fccd 190=head2 has_column_loaded
191
192 if ( $obj->has_column_loaded($col) ) {
193 print "$col has been loaded from db";
194 }
195
196Returns a true value if the column value has been loaded from the
197database (or set locally).
198
199=cut
200
def81720 201sub has_column_loaded {
202 my ($self, $column) = @_;
203 $self->throw_exception( "Can't call has_column data as class method" ) unless ref $self;
aeb1bf75 204 return exists $self->{_column_data}{$column};
def81720 205}
206
8091aa91 207=head2 get_columns
076a6864 208
209 my %data = $obj->get_columns;
210
8091aa91 211Does C<get_column>, for all column values at once.
076a6864 212
213=cut
214
215sub get_columns {
216 my $self = shift;
cb5f2eea 217 return %{$self->{_column_data}};
d7156e50 218}
219
220=head2 get_dirty_columns
221
222 my %data = $obj->get_dirty_columns;
223
224Identical to get_columns but only returns those that have been changed.
225
226=cut
227
228sub get_dirty_columns {
229 my $self = shift;
230 return map { $_ => $self->{_column_data}{$_} }
231 keys %{$self->{_dirty_columns}};
076a6864 232}
233
8091aa91 234=head2 set_column
7624b19f 235
236 $obj->set_column($col => $val);
237
8091aa91 238Sets a column value. If the new value is different from the old one,
239the column is marked as dirty for when you next call $obj->update.
7624b19f 240
241=cut
242
243sub set_column {
244 my $self = shift;
245 my ($column) = @_;
729b29ae 246 $self->{_orig_ident} ||= $self->ident_condition;
7624b19f 247 my $old = $self->get_column($column);
248 my $ret = $self->store_column(@_);
87772e46 249 $self->{_dirty_columns}{$column} = 1
250 if (defined $old ^ defined $ret) || (defined $old && $old ne $ret);
7624b19f 251 return $ret;
252}
253
8091aa91 254=head2 set_columns
076a6864 255
dc818523 256 my $copy = $orig->set_columns({ $col => $val, ... });
076a6864 257
8091aa91 258Sets more than one column value at once.
076a6864 259
260=cut
261
262sub set_columns {
263 my ($self,$data) = @_;
a2ca474b 264 foreach my $col (keys %$data) {
265 $self->set_column($col,$data->{$col});
076a6864 266 }
c01ab172 267 return $self;
076a6864 268}
269
8091aa91 270=head2 copy
076a6864 271
272 my $copy = $orig->copy({ change => $to, ... });
273
8091aa91 274Inserts a new row with the specified changes.
076a6864 275
276=cut
277
c01ab172 278sub copy {
279 my ($self, $changes) = @_;
333cce60 280 $changes ||= {};
fde6e28e 281 my $col_data = { %{$self->{_column_data}} };
282 foreach my $col (keys %$col_data) {
283 delete $col_data->{$col}
284 if $self->result_source->column_info($col)->{is_auto_increment};
285 }
04786a4c 286
287 my $new = { _column_data => $col_data };
288 bless $new, ref $self;
289
83419ec6 290 $new->result_source($self->result_source);
ecd1f408 291 $new->set_columns($changes);
333cce60 292 $new->insert;
293 foreach my $rel ($self->result_source->relationships) {
294 my $rel_info = $self->result_source->relationship_info($rel);
295 if ($rel_info->{attrs}{cascade_copy}) {
296 my $resolved = $self->result_source->resolve_condition(
297 $rel_info->{cond}, $rel, $new);
298 foreach my $related ($self->search_related($rel)) {
299 $related->copy($resolved);
300 }
301 }
302 }
2c4c67b6 303 return $new;
c01ab172 304}
305
8091aa91 306=head2 store_column
7624b19f 307
308 $obj->store_column($col => $val);
309
8091aa91 310Sets a column value without marking it as dirty.
7624b19f 311
312=cut
313
314sub store_column {
315 my ($self, $column, $value) = @_;
75d07914 316 $self->throw_exception( "No such column '${column}'" )
d7156e50 317 unless exists $self->{_column_data}{$column} || $self->has_column($column);
75d07914 318 $self->throw_exception( "set_column called for ${column} without value" )
7624b19f 319 if @_ < 3;
320 return $self->{_column_data}{$column} = $value;
321}
322
b52e9bf8 323=head2 inflate_result
324
c01ab172 325 Class->inflate_result($result_source, \%me, \%prefetch?)
b52e9bf8 326
327Called by ResultSet to inflate a result from storage
328
329=cut
330
331sub inflate_result {
c01ab172 332 my ($class, $source, $me, $prefetch) = @_;
b52e9bf8 333 #use Data::Dumper; print Dumper(@_);
04786a4c 334 my $new = {
335 result_source => $source,
336 _column_data => $me,
337 _in_storage => 1
338 };
339 bless $new, (ref $class || $class);
340
7fb16f1a 341 my $schema;
64acc2bc 342 foreach my $pre (keys %{$prefetch||{}}) {
343 my $pre_val = $prefetch->{$pre};
f9cc31dd 344 my $pre_source = $source->related_source($pre);
a86b1efe 345 $class->throw_exception("Can't prefetch non-existent relationship ${pre}")
346 unless $pre_source;
0f66a01b 347 if (ref($pre_val->[0]) eq 'ARRAY') { # multi
a86b1efe 348 my @pre_objects;
349 foreach my $pre_rec (@$pre_val) {
75d07914 350 unless ($pre_source->primary_columns == grep { exists $pre_rec->[0]{$_}
5a5bec6c 351 and defined $pre_rec->[0]{$_} } $pre_source->primary_columns) {
a86b1efe 352 next;
353 }
354 push(@pre_objects, $pre_source->result_class->inflate_result(
355 $pre_source, @{$pre_rec}));
356 }
357 $new->related_resultset($pre)->set_cache(\@pre_objects);
62e87ea8 358 } elsif (defined $pre_val->[0]) {
a86b1efe 359 my $fetched;
75d07914 360 unless ($pre_source->primary_columns == grep { exists $pre_val->[0]{$_}
a86b1efe 361 and !defined $pre_val->[0]{$_} } $pre_source->primary_columns)
362 {
363 $fetched = $pre_source->result_class->inflate_result(
75d07914 364 $pre_source, @{$pre_val});
a86b1efe 365 }
366 my $accessor = $source->relationship_info($pre)->{attrs}{accessor};
367 $class->throw_exception("No accessor for prefetched $pre")
368 unless defined $accessor;
369 if ($accessor eq 'single') {
370 $new->{_relationship_data}{$pre} = $fetched;
371 } elsif ($accessor eq 'filter') {
372 $new->{_inflated_column}{$pre} = $fetched;
373 } else {
374 $class->throw_exception("Prefetch not supported with accessor '$accessor'");
375 }
b52e9bf8 376 }
377 }
7624b19f 378 return $new;
379}
380
9b465d00 381=head2 update_or_insert
7624b19f 382
9b465d00 383 $obj->update_or_insert
7624b19f 384
8091aa91 385Updates the object if it's already in the db, else inserts it.
7624b19f 386
9b83fccd 387=head2 insert_or_update
388
389 $obj->insert_or_update
390
391Alias for L</update_or_insert>
392
7624b19f 393=cut
394
9b465d00 395*insert_or_update = \&update_or_insert;
396sub update_or_insert {
7624b19f 397 my $self = shift;
398 return ($self->in_storage ? $self->update : $self->insert);
399}
400
8091aa91 401=head2 is_changed
7624b19f 402
228dbcb4 403 my @changed_col_names = $obj->is_changed();
404 if ($obj->is_changed()) { ... }
7624b19f 405
9b83fccd 406In array context returns a list of columns with uncommited changes, or
407in scalar context returns a true value if there are uncommitted
408changes.
409
7624b19f 410=cut
411
412sub is_changed {
413 return keys %{shift->{_dirty_columns} || {}};
414}
228dbcb4 415
416=head2 is_column_changed
417
418 if ($obj->is_column_changed('col')) { ... }
419
9b83fccd 420Returns a true value if the column has uncommitted changes.
421
228dbcb4 422=cut
423
424sub is_column_changed {
425 my( $self, $col ) = @_;
426 return exists $self->{_dirty_columns}->{$col};
427}
7624b19f 428
097d3227 429=head2 result_source
430
9b83fccd 431 my $resultsource = $object->result_source;
097d3227 432
9b83fccd 433Accessor to the ResultSource this object was created from
87c4e602 434
9b83fccd 435=head2 register_column
27f01d1f 436
9b83fccd 437 $column_info = { .... };
438 $class->register_column($column_name, $column_info);
27f01d1f 439
9b83fccd 440Registers a column on the class. If the column_info has an 'accessor'
441key, creates an accessor named after the value if defined; if there is
442no such key, creates an accessor with the same name as the column
1f23a877 443
9b83fccd 444The column_info attributes are described in
445L<DBIx::Class::ResultSource/add_columns>
1f23a877 446
097d3227 447=cut
448
1f23a877 449sub register_column {
450 my ($class, $col, $info) = @_;
91b0fbd7 451 my $acc = $col;
452 if (exists $info->{accessor}) {
453 return unless defined $info->{accessor};
454 $acc = [ $info->{accessor}, $col ];
455 }
456 $class->mk_group_accessors('column' => $acc);
1f23a877 457}
458
701da8c4 459
5160b401 460=head2 throw_exception
701da8c4 461
462See Schema's throw_exception.
463
464=cut
465
466sub throw_exception {
467 my $self=shift;
468 if (ref $self && ref $self->result_source) {
469 $self->result_source->schema->throw_exception(@_);
470 } else {
471 croak(@_);
472 }
473}
474
7624b19f 4751;
476
7624b19f 477=head1 AUTHORS
478
daec44b8 479Matt S. Trout <mst@shadowcatsystems.co.uk>
7624b19f 480
481=head1 LICENSE
482
483You may distribute this code under the same terms as Perl itself.
484
485=cut