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