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