More internals cleanup, separated out ResultSourceInstance from TableInstance
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Row.pm
1 package DBIx::Class::Row;
2
3 use strict;
4 use warnings;
5
6 use base qw/DBIx::Class/;
7
8 =head1 NAME 
9
10 DBIx::Class::Row - Basic row methods
11
12 =head1 SYNOPSIS
13
14 =head1 DESCRIPTION
15
16 This class is responsible for defining and doing basic operations on rows
17 derived from L<DBIx::Class::Table> objects.
18
19 =head1 METHODS
20
21 =head2 new
22
23   my $obj = My::Class->new($attrs);
24
25 Creates a new row object from column => value mappings passed as a hash ref
26
27 =cut
28
29 sub new {
30   my ($class, $attrs) = @_;
31   $class = ref $class if ref $class;
32   my $new = bless({ _column_data => { } }, $class);
33   if ($attrs) {
34     $new->throw("attrs must be a hashref" ) unless ref($attrs) eq 'HASH';
35     while (my ($k, $v) = each %{$attrs}) {
36       die "No such column $k on $class" unless $class->has_column($k);
37       $new->store_column($k => $v);
38     }
39   }
40   return $new;
41 }
42
43 =head2 insert
44
45   $obj->insert;
46
47 Inserts an object into the database if it isn't already in there. Returns
48 the object itself.
49
50 =cut
51
52 sub insert {
53   my ($self) = @_;
54   return $self if $self->in_storage;
55   #use Data::Dumper; warn Dumper($self);
56   $self->result_source->storage->insert(
57     $self->result_source->from, { $self->get_columns });
58   $self->in_storage(1);
59   $self->{_dirty_columns} = {};
60   return $self;
61 }
62
63 =head2 in_storage
64
65   $obj->in_storage; # Get value
66   $obj->in_storage(1); # Set value
67
68 Indicated whether the object exists as a row in the database or not
69
70 =cut
71
72 sub in_storage {
73   my ($self, $val) = @_;
74   $self->{_in_storage} = $val if @_ > 1;
75   return $self->{_in_storage};
76 }
77
78 =head2 update
79
80   $obj->update;
81
82 Must be run on an object that is already in the database; issues an SQL
83 UPDATE query to commit any changes to the object to the db if required.
84
85 =cut
86
87 sub update {
88   my ($self, $upd) = @_;
89   $self->throw( "Not in database" ) unless $self->in_storage;
90   my %to_update = $self->get_dirty_columns;
91   return $self unless keys %to_update;
92   my $rows = $self->result_source->storage->update(
93                $self->result_source->from, \%to_update, $self->ident_condition);
94   if ($rows == 0) {
95     $self->throw( "Can't update ${self}: row not found" );
96   } elsif ($rows > 1) {
97     $self->throw("Can't update ${self}: updated more than one row");
98   }
99   $self->{_dirty_columns} = {};
100   return $self;
101 }
102
103 =head2 delete
104
105   $obj->delete
106
107 Deletes the object from the database. The object is still perfectly usable
108 accessor-wise etc. but ->in_storage will now return 0 and the object must
109 be re ->insert'ed before it can be ->update'ed
110
111 =cut
112
113 sub delete {
114   my $self = shift;
115   if (ref $self) {
116     $self->throw( "Not in database" ) unless $self->in_storage;
117     $self->result_source->storage->delete(
118       $self->result_source->from, $self->ident_condition);
119     $self->in_storage(undef);
120   } else {
121     my $attrs = { };
122     if (@_ > 1 && ref $_[$#_] eq 'HASH') {
123       $attrs = { %{ pop(@_) } };
124     }
125     my $query = (ref $_[0] eq 'HASH' ? $_[0] : {@_});
126     $self->result_source->resultset->search(@_)->delete;
127   }
128   return $self;
129 }
130
131 =head2 get_column
132
133   my $val = $obj->get_column($col);
134
135 Gets a column value from a row object. Currently, does not do
136 any queries; the column must have already been fetched from
137 the database and stored in the object.
138
139 =cut
140
141 sub get_column {
142   my ($self, $column) = @_;
143   $self->throw( "Can't fetch data as class method" ) unless ref $self;
144   return $self->{_column_data}{$column}
145     if exists $self->{_column_data}{$column};
146   $self->throw( "No such column '${column}'" ) unless $self->has_column($column);
147   return undef;
148 }
149
150 =head2 get_columns
151
152   my %data = $obj->get_columns;
153
154 Does C<get_column>, for all column values at once.
155
156 =cut
157
158 sub get_columns {
159   my $self = shift;
160   return return %{$self->{_column_data}};
161 }
162
163 =head2 get_dirty_columns
164
165   my %data = $obj->get_dirty_columns;
166
167 Identical to get_columns but only returns those that have been changed.
168
169 =cut
170
171 sub get_dirty_columns {
172   my $self = shift;
173   return map { $_ => $self->{_column_data}{$_} }
174            keys %{$self->{_dirty_columns}};
175 }
176
177 =head2 set_column
178
179   $obj->set_column($col => $val);
180
181 Sets a column value. If the new value is different from the old one,
182 the column is marked as dirty for when you next call $obj->update.
183
184 =cut
185
186 sub set_column {
187   my $self = shift;
188   my ($column) = @_;
189   my $old = $self->get_column($column);
190   my $ret = $self->store_column(@_);
191   $self->{_dirty_columns}{$column} = 1
192     if (defined $old ^ defined $ret) || (defined $old && $old ne $ret);
193   return $ret;
194 }
195
196 =head2 set_columns
197
198   my $copy = $orig->set_columns({ $col => $val, ... });
199
200 Sets more than one column value at once.
201
202 =cut
203
204 sub set_columns {
205   my ($self,$data) = @_;
206   while (my ($col,$val) = each %$data) {
207     $self->set_column($col,$val);
208   }
209   return $self;
210 }
211
212 =head2 copy
213
214   my $copy = $orig->copy({ change => $to, ... });
215
216 Inserts a new row with the specified changes.
217
218 =cut
219
220 sub copy {
221   my ($self, $changes) = @_;
222   my $new = bless({ _column_data => { %{$self->{_column_data}}} }, ref $self);
223   $new->set_column($_ => $changes->{$_}) for keys %$changes;
224   return $new->insert;
225 }
226
227 =head2 store_column
228
229   $obj->store_column($col => $val);
230
231 Sets a column value without marking it as dirty.
232
233 =cut
234
235 sub store_column {
236   my ($self, $column, $value) = @_;
237   $self->throw( "No such column '${column}'" ) 
238     unless exists $self->{_column_data}{$column} || $self->has_column($column);
239   $self->throw( "set_column called for ${column} without value" ) 
240     if @_ < 3;
241   return $self->{_column_data}{$column} = $value;
242 }
243
244 =head2 inflate_result
245
246   Class->inflate_result($result_source, \%me, \%prefetch?)
247
248 Called by ResultSet to inflate a result from storage
249
250 =cut
251
252 sub inflate_result {
253   my ($class, $source, $me, $prefetch) = @_;
254   #use Data::Dumper; print Dumper(@_);
255   my $new = bless({ result_source => $source,
256                     _column_data => $me,
257                     _in_storage => 1
258                   },
259                   ref $class || $class);
260   my $schema;
261   PRE: foreach my $pre (keys %{$prefetch||{}}) {
262     my $rel_obj = $class->relationship_info($pre);
263     die "Can't prefetch non-eistant relationship ${pre}" unless $rel_obj;
264     $schema ||= $source->schema;
265     my $pre_class = $schema->class($rel_obj->{class});
266     my $fetched = $pre_class->inflate_result(
267                     $schema->source($pre_class), @{$prefetch->{$pre}});
268     $class->throw("No accessor for prefetched $pre")
269       unless defined $rel_obj->{attrs}{accessor};
270     PRIMARY: foreach my $pri ($rel_obj->{class}->primary_columns) {
271       unless (defined $fetched->get_column($pri)) {
272         undef $fetched;
273         last PRIMARY;
274       }
275     }
276     if ($rel_obj->{attrs}{accessor} eq 'single') {
277       $new->{_relationship_data}{$pre} = $fetched;
278     } elsif ($rel_obj->{attrs}{accessor} eq 'filter') {
279       $new->{_inflated_column}{$pre} = $fetched;
280     } else {
281       $class->throw("Don't know how to store prefetched $pre");
282     }
283   }
284   return $new;
285 }
286
287 =head2 insert_or_update
288
289   $obj->insert_or_update
290
291 Updates the object if it's already in the db, else inserts it.
292
293 =cut
294
295 sub insert_or_update {
296   my $self = shift;
297   return ($self->in_storage ? $self->update : $self->insert);
298 }
299
300 =head2 is_changed
301
302   my @changed_col_names = $obj->is_changed
303
304 =cut
305
306 sub is_changed {
307   return keys %{shift->{_dirty_columns} || {}};
308 }
309
310 1;
311
312 =head1 AUTHORS
313
314 Matt S. Trout <mst@shadowcatsystems.co.uk>
315
316 =head1 LICENSE
317
318 You may distribute this code under the same terms as Perl itself.
319
320 =cut
321