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