cleanup ResultSource a bit, plus a couple trivial cleanups
[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
7624b19f 13=head1 NAME
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;
37 my $new = bless({ _column_data => { } }, $class);
38 if ($attrs) {
701da8c4 39 $new->throw_exception("attrs must be a hashref" ) unless ref($attrs) eq 'HASH';
7624b19f 40 while (my ($k, $v) = each %{$attrs}) {
701da8c4 41 $new->throw_exception("No such column $k on $class") unless $class->has_column($k);
484c9dda 42 $new->store_column($k => $v);
7624b19f 43 }
44 }
45 return $new;
46}
47
8091aa91 48=head2 insert
7624b19f 49
50 $obj->insert;
51
52Inserts an object into the database if it isn't already in there. Returns
097d3227 53the object itself. Requires the object's result source to be set, or the
54class to have a result_source_instance method.
7624b19f 55
56=cut
57
58sub insert {
59 my ($self) = @_;
60 return $self if $self->in_storage;
097d3227 61 $self->{result_source} ||= $self->result_source_instance
62 if $self->can('result_source_instance');
63 my $source = $self->{result_source};
701da8c4 64 $self->throw_exception("No result_source set on this object; can't insert") unless $source;
7624b19f 65 #use Data::Dumper; warn Dumper($self);
097d3227 66 $source->storage->insert($source->from, { $self->get_columns });
7624b19f 67 $self->in_storage(1);
68 $self->{_dirty_columns} = {};
64acc2bc 69 $self->{related_resultsets} = {};
7624b19f 70 return $self;
71}
72
8091aa91 73=head2 in_storage
7624b19f 74
75 $obj->in_storage; # Get value
76 $obj->in_storage(1); # Set value
77
78Indicated whether the object exists as a row in the database or not
79
80=cut
81
82sub in_storage {
83 my ($self, $val) = @_;
84 $self->{_in_storage} = $val if @_ > 1;
85 return $self->{_in_storage};
86}
87
8091aa91 88=head2 update
7624b19f 89
90 $obj->update;
91
92Must be run on an object that is already in the database; issues an SQL
93UPDATE query to commit any changes to the object to the db if required.
94
95=cut
96
97sub update {
98 my ($self, $upd) = @_;
701da8c4 99 $self->throw_exception( "Not in database" ) unless $self->in_storage;
fc27a867 100 $self->set_columns($upd) if $upd;
d7156e50 101 my %to_update = $self->get_dirty_columns;
c01ab172 102 return $self unless keys %to_update;
4b12b3c2 103 my $ident_cond = $self->ident_condition;
104 $self->throw_exception("Cannot safely update a row in a PK-less table")
105 if ! keys %$ident_cond;
88cb6a1d 106 my $rows = $self->result_source->storage->update(
4b12b3c2 107 $self->result_source->from, \%to_update, $ident_cond);
7624b19f 108 if ($rows == 0) {
701da8c4 109 $self->throw_exception( "Can't update ${self}: row not found" );
7624b19f 110 } elsif ($rows > 1) {
701da8c4 111 $self->throw_exception("Can't update ${self}: updated more than one row");
7624b19f 112 }
113 $self->{_dirty_columns} = {};
64acc2bc 114 $self->{related_resultsets} = {};
7624b19f 115 return $self;
116}
117
8091aa91 118=head2 delete
7624b19f 119
120 $obj->delete
121
122Deletes the object from the database. The object is still perfectly usable
123accessor-wise etc. but ->in_storage will now return 0 and the object must
124be re ->insert'ed before it can be ->update'ed
125
126=cut
127
128sub delete {
129 my $self = shift;
130 if (ref $self) {
701da8c4 131 $self->throw_exception( "Not in database" ) unless $self->in_storage;
4b12b3c2 132 my $ident_cond = $self->ident_condition;
133 $self->throw_exception("Cannot safely delete a row in a PK-less table")
134 if ! keys %$ident_cond;
e0f56292 135 foreach my $column (keys %$ident_cond) {
136 $self->throw_exception("Can't delete the object unless it has loaded the primary keys")
137 unless exists $self->{_column_data}{$column};
138 }
88cb6a1d 139 $self->result_source->storage->delete(
4b12b3c2 140 $self->result_source->from, $ident_cond);
7624b19f 141 $self->in_storage(undef);
7624b19f 142 } else {
701da8c4 143 $self->throw_exception("Can't do class delete without a ResultSource instance")
097d3227 144 unless $self->can('result_source_instance');
7624b19f 145 my $attrs = { };
146 if (@_ > 1 && ref $_[$#_] eq 'HASH') {
147 $attrs = { %{ pop(@_) } };
148 }
149 my $query = (ref $_[0] eq 'HASH' ? $_[0] : {@_});
097d3227 150 $self->result_source_instance->resultset->search(@_)->delete;
7624b19f 151 }
152 return $self;
153}
154
8091aa91 155=head2 get_column
7624b19f 156
157 my $val = $obj->get_column($col);
158
8091aa91 159Gets a column value from a row object. Currently, does not do
160any queries; the column must have already been fetched from
161the database and stored in the object.
7624b19f 162
163=cut
164
165sub get_column {
166 my ($self, $column) = @_;
701da8c4 167 $self->throw_exception( "Can't fetch data as class method" ) unless ref $self;
7624b19f 168 return $self->{_column_data}{$column}
169 if exists $self->{_column_data}{$column};
701da8c4 170 $self->throw_exception( "No such column '${column}'" ) unless $self->has_column($column);
7624b19f 171 return undef;
172}
173
def81720 174sub has_column_loaded {
175 my ($self, $column) = @_;
176 $self->throw_exception( "Can't call has_column data as class method" ) unless ref $self;
177 return 1
178 if exists $self->{_column_data}{$column};
179 return 0;
180}
181
8091aa91 182=head2 get_columns
076a6864 183
184 my %data = $obj->get_columns;
185
8091aa91 186Does C<get_column>, for all column values at once.
076a6864 187
188=cut
189
190sub get_columns {
191 my $self = shift;
cb5f2eea 192 return %{$self->{_column_data}};
d7156e50 193}
194
195=head2 get_dirty_columns
196
197 my %data = $obj->get_dirty_columns;
198
199Identical to get_columns but only returns those that have been changed.
200
201=cut
202
203sub get_dirty_columns {
204 my $self = shift;
205 return map { $_ => $self->{_column_data}{$_} }
206 keys %{$self->{_dirty_columns}};
076a6864 207}
208
8091aa91 209=head2 set_column
7624b19f 210
211 $obj->set_column($col => $val);
212
8091aa91 213Sets a column value. If the new value is different from the old one,
214the column is marked as dirty for when you next call $obj->update.
7624b19f 215
216=cut
217
218sub set_column {
219 my $self = shift;
220 my ($column) = @_;
221 my $old = $self->get_column($column);
222 my $ret = $self->store_column(@_);
87772e46 223 $self->{_dirty_columns}{$column} = 1
224 if (defined $old ^ defined $ret) || (defined $old && $old ne $ret);
7624b19f 225 return $ret;
226}
227
8091aa91 228=head2 set_columns
076a6864 229
dc818523 230 my $copy = $orig->set_columns({ $col => $val, ... });
076a6864 231
8091aa91 232Sets more than one column value at once.
076a6864 233
234=cut
235
236sub set_columns {
237 my ($self,$data) = @_;
238 while (my ($col,$val) = each %$data) {
239 $self->set_column($col,$val);
240 }
c01ab172 241 return $self;
076a6864 242}
243
8091aa91 244=head2 copy
076a6864 245
246 my $copy = $orig->copy({ change => $to, ... });
247
8091aa91 248Inserts a new row with the specified changes.
076a6864 249
250=cut
251
c01ab172 252sub copy {
253 my ($self, $changes) = @_;
333cce60 254 $changes ||= {};
fde6e28e 255 my $col_data = { %{$self->{_column_data}} };
256 foreach my $col (keys %$col_data) {
257 delete $col_data->{$col}
258 if $self->result_source->column_info($col)->{is_auto_increment};
259 }
260 my $new = bless({ _column_data => $col_data }, ref $self);
ecd1f408 261 $new->set_columns($changes);
333cce60 262 $new->insert;
263 foreach my $rel ($self->result_source->relationships) {
264 my $rel_info = $self->result_source->relationship_info($rel);
265 if ($rel_info->{attrs}{cascade_copy}) {
266 my $resolved = $self->result_source->resolve_condition(
267 $rel_info->{cond}, $rel, $new);
268 foreach my $related ($self->search_related($rel)) {
269 $related->copy($resolved);
270 }
271 }
272 }
2c4c67b6 273 return $new;
c01ab172 274}
275
8091aa91 276=head2 store_column
7624b19f 277
278 $obj->store_column($col => $val);
279
8091aa91 280Sets a column value without marking it as dirty.
7624b19f 281
282=cut
283
284sub store_column {
285 my ($self, $column, $value) = @_;
701da8c4 286 $self->throw_exception( "No such column '${column}'" )
d7156e50 287 unless exists $self->{_column_data}{$column} || $self->has_column($column);
701da8c4 288 $self->throw_exception( "set_column called for ${column} without value" )
7624b19f 289 if @_ < 3;
290 return $self->{_column_data}{$column} = $value;
291}
292
b52e9bf8 293=head2 inflate_result
294
c01ab172 295 Class->inflate_result($result_source, \%me, \%prefetch?)
b52e9bf8 296
297Called by ResultSet to inflate a result from storage
298
299=cut
300
301sub inflate_result {
c01ab172 302 my ($class, $source, $me, $prefetch) = @_;
b52e9bf8 303 #use Data::Dumper; print Dumper(@_);
c01ab172 304 my $new = bless({ result_source => $source,
305 _column_data => $me,
306 _in_storage => 1
307 },
308 ref $class || $class);
7fb16f1a 309 my $schema;
64acc2bc 310 foreach my $pre (keys %{$prefetch||{}}) {
311 my $pre_val = $prefetch->{$pre};
f9cc31dd 312 my $pre_source = $source->related_source($pre);
a86b1efe 313 $class->throw_exception("Can't prefetch non-existent relationship ${pre}")
314 unless $pre_source;
0f66a01b 315 if (ref($pre_val->[0]) eq 'ARRAY') { # multi
a86b1efe 316 my @pre_objects;
317 foreach my $pre_rec (@$pre_val) {
318 unless ($pre_source->primary_columns == grep { exists $pre_rec->[0]{$_}
5a5bec6c 319 and defined $pre_rec->[0]{$_} } $pre_source->primary_columns) {
a86b1efe 320 next;
321 }
322 push(@pre_objects, $pre_source->result_class->inflate_result(
323 $pre_source, @{$pre_rec}));
324 }
325 $new->related_resultset($pre)->set_cache(\@pre_objects);
f9cc31dd 326 } else {
a86b1efe 327 my $fetched;
328 unless ($pre_source->primary_columns == grep { exists $pre_val->[0]{$_}
329 and !defined $pre_val->[0]{$_} } $pre_source->primary_columns)
330 {
331 $fetched = $pre_source->result_class->inflate_result(
332 $pre_source, @{$pre_val});
333 }
334 my $accessor = $source->relationship_info($pre)->{attrs}{accessor};
335 $class->throw_exception("No accessor for prefetched $pre")
336 unless defined $accessor;
337 if ($accessor eq 'single') {
338 $new->{_relationship_data}{$pre} = $fetched;
339 } elsif ($accessor eq 'filter') {
340 $new->{_inflated_column}{$pre} = $fetched;
341 } else {
342 $class->throw_exception("Prefetch not supported with accessor '$accessor'");
343 }
b52e9bf8 344 }
345 }
7624b19f 346 return $new;
347}
348
8091aa91 349=head2 insert_or_update
7624b19f 350
351 $obj->insert_or_update
352
8091aa91 353Updates the object if it's already in the db, else inserts it.
7624b19f 354
355=cut
356
357sub insert_or_update {
358 my $self = shift;
359 return ($self->in_storage ? $self->update : $self->insert);
360}
361
8091aa91 362=head2 is_changed
7624b19f 363
364 my @changed_col_names = $obj->is_changed
365
366=cut
367
368sub is_changed {
369 return keys %{shift->{_dirty_columns} || {}};
370}
371
097d3227 372=head2 result_source
373
374 Accessor to the ResultSource this object was created from
375
87c4e602 376=head2 register_column
377
378=head3 Arguments: ($column, $column_info)
1f23a877 379
91b0fbd7 380 Registers a column on the class. If the column_info has an 'accessor' key,
381 creates an accessor named after the value if defined; if there is no such
382 key, creates an accessor with the same name as the column
1f23a877 383
097d3227 384=cut
385
1f23a877 386sub register_column {
387 my ($class, $col, $info) = @_;
91b0fbd7 388 my $acc = $col;
389 if (exists $info->{accessor}) {
390 return unless defined $info->{accessor};
391 $acc = [ $info->{accessor}, $col ];
392 }
393 $class->mk_group_accessors('column' => $acc);
1f23a877 394}
395
701da8c4 396
5160b401 397=head2 throw_exception
701da8c4 398
399See Schema's throw_exception.
400
401=cut
402
403sub throw_exception {
404 my $self=shift;
405 if (ref $self && ref $self->result_source) {
406 $self->result_source->schema->throw_exception(@_);
407 } else {
408 croak(@_);
409 }
410}
411
7624b19f 4121;
413
7624b19f 414=head1 AUTHORS
415
daec44b8 416Matt S. Trout <mst@shadowcatsystems.co.uk>
7624b19f 417
418=head1 LICENSE
419
420You may distribute this code under the same terms as Perl itself.
421
422=cut
423