create now on resultset as well
[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->storage->insert($self->_table_name, { $self->get_columns });
57   $self->in_storage(1);
58   $self->{_dirty_columns} = {};
59   return $self;
60 }
61
62 =head2 in_storage
63
64   $obj->in_storage; # Get value
65   $obj->in_storage(1); # Set value
66
67 Indicated whether the object exists as a row in the database or not
68
69 =cut
70
71 sub in_storage {
72   my ($self, $val) = @_;
73   $self->{_in_storage} = $val if @_ > 1;
74   return $self->{_in_storage};
75 }
76
77 =head2 update
78
79   $obj->update;
80
81 Must be run on an object that is already in the database; issues an SQL
82 UPDATE query to commit any changes to the object to the db if required.
83
84 =cut
85
86 sub update {
87   my ($self, $upd) = @_;
88   $self->throw( "Not in database" ) unless $self->in_storage;
89   my %to_update = $self->get_dirty_columns;
90   return -1 unless keys %to_update;
91   my $rows = $self->storage->update($self->result_source->from, \%to_update,
92                                       $self->ident_condition);
93   if ($rows == 0) {
94     $self->throw( "Can't update ${self}: row not found" );
95   } elsif ($rows > 1) {
96     $self->throw("Can't update ${self}: updated more than one row");
97   }
98   $self->{_dirty_columns} = {};
99   return $self;
100 }
101
102 =head2 delete
103
104   $obj->delete
105
106 Deletes the object from the database. The object is still perfectly usable
107 accessor-wise etc. but ->in_storage will now return 0 and the object must
108 be re ->insert'ed before it can be ->update'ed
109
110 =cut
111
112 sub delete {
113   my $self = shift;
114   if (ref $self) {
115     $self->throw( "Not in database" ) unless $self->in_storage;
116     #warn $self->_ident_cond.' '.join(', ', $self->_ident_values);
117     $self->storage->delete($self->result_source->from, $self->ident_condition);
118     $self->in_storage(undef);
119     #$self->store_column($_ => undef) for $self->primary_columns;
120       # Should probably also arrange to trash PK if auto
121       # but if we do, post-delete cascade triggers fail :/
122   } else {
123     my $attrs = { };
124     if (@_ > 1 && ref $_[$#_] eq 'HASH') {
125       $attrs = { %{ pop(@_) } };
126     }
127     my $query = (ref $_[0] eq 'HASH' ? $_[0] : {@_});
128     $self->storage->delete($self->_table_name, $query);
129   }
130   return $self;
131 }
132
133 =head2 get_column
134
135   my $val = $obj->get_column($col);
136
137 Gets a column value from a row object. Currently, does not do
138 any queries; the column must have already been fetched from
139 the database and stored in the object.
140
141 =cut
142
143 sub get_column {
144   my ($self, $column) = @_;
145   $self->throw( "Can't fetch data as class method" ) unless ref $self;
146   return $self->{_column_data}{$column}
147     if exists $self->{_column_data}{$column};
148   $self->throw( "No such column '${column}'" ) unless $self->has_column($column);
149   return undef;
150 }
151
152 =head2 get_columns
153
154   my %data = $obj->get_columns;
155
156 Does C<get_column>, for all column values at once.
157
158 =cut
159
160 sub get_columns {
161   my $self = shift;
162   return return %{$self->{_column_data}};
163 }
164
165 =head2 get_dirty_columns
166
167   my %data = $obj->get_dirty_columns;
168
169 Identical to get_columns but only returns those that have been changed.
170
171 =cut
172
173 sub get_dirty_columns {
174   my $self = shift;
175   return map { $_ => $self->{_column_data}{$_} }
176            keys %{$self->{_dirty_columns}};
177 }
178
179 =head2 set_column
180
181   $obj->set_column($col => $val);
182
183 Sets a column value. If the new value is different from the old one,
184 the column is marked as dirty for when you next call $obj->update.
185
186 =cut
187
188 sub set_column {
189   my $self = shift;
190   my ($column) = @_;
191   my $old = $self->get_column($column);
192   my $ret = $self->store_column(@_);
193   $self->{_dirty_columns}{$column} = 1 unless defined $old && $old eq $ret;
194   return $ret;
195 }
196
197 =head2 set_columns
198
199   my $copy = $orig->set_columns({ $col => $val, ... });
200
201 Sets more than one column value at once.
202
203 =cut
204
205 sub set_columns {
206   my ($self,$data) = @_;
207   while (my ($col,$val) = each %$data) {
208     $self->set_column($col,$val);
209   }
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 =head2 store_column
221
222   $obj->store_column($col => $val);
223
224 Sets a column value without marking it as dirty.
225
226 =cut
227
228 sub store_column {
229   my ($self, $column, $value) = @_;
230   $self->throw( "No such column '${column}'" ) 
231     unless exists $self->{_column_data}{$column} || $self->has_column($column);
232   $self->throw( "set_column called for ${column} without value" ) 
233     if @_ < 3;
234   return $self->{_column_data}{$column} = $value;
235 }
236
237 =head2 inflate_result
238
239   Class->inflate_result(\%me, \%prefetch?)
240
241 Called by ResultSet to inflate a result from storage
242
243 =cut
244
245 sub inflate_result {
246   my ($class, $me, $prefetch) = @_;
247   #use Data::Dumper; print Dumper(@_);
248   my $new = bless({ _column_data => $me }, ref $class || $class);
249   $new->in_storage(1);
250   PRE: foreach my $pre (keys %{$prefetch||{}}) {
251     my $rel_obj = $class->_relationships->{$pre};
252     my $pre_class = $class->resolve_class($rel_obj->{class});
253     my $fetched = $pre_class->inflate_result(@{$prefetch->{$pre}});
254     $class->throw("No accessor for prefetched $pre")
255       unless defined $rel_obj->{attrs}{accessor};
256     if ($rel_obj->{attrs}{accessor} eq 'single') {
257       PRIMARY: foreach my $pri ($rel_obj->{class}->primary_columns) {
258         unless (defined $fetched->get_column($pri)) {
259           undef $fetched;
260           last PRIMARY;
261         }
262       }
263       $new->{_relationship_data}{$pre} = $fetched;
264     } elsif ($rel_obj->{attrs}{accessor} eq 'filter') {
265       $new->{_inflated_column}{$pre} = $fetched;
266     } else {
267       $class->throw("Don't know how to store prefetched $pre");
268     }
269   }
270   return $new;
271 }
272
273 sub copy {
274   my ($self, $changes) = @_;
275   my $new = bless({ _column_data => { %{$self->{_column_data}}} }, ref $self);
276   $new->set_column($_ => $changes->{$_}) for keys %$changes;
277   return $new->insert;
278 }
279
280 =head2 insert_or_update
281
282   $obj->insert_or_update
283
284 Updates the object if it's already in the db, else inserts it.
285
286 =cut
287
288 sub insert_or_update {
289   my $self = shift;
290   return ($self->in_storage ? $self->update : $self->insert);
291 }
292
293 =head2 is_changed
294
295   my @changed_col_names = $obj->is_changed
296
297 =cut
298
299 sub is_changed {
300   return keys %{shift->{_dirty_columns} || {}};
301 }
302
303 1;
304
305 =head1 AUTHORS
306
307 Matt S. Trout <mst@shadowcatsystems.co.uk>
308
309 =head1 LICENSE
310
311 You may distribute this code under the same terms as Perl itself.
312
313 =cut
314