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