- fix ResultSet bug when requesting a subset of columns
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSet.pm
1 package DBIx::Class::ResultSet;
2
3 use strict;
4 use warnings;
5 use overload
6         '0+'     => 'count',
7         fallback => 1;
8 use Data::Page;
9
10 =head1 NAME
11
12 DBIX::Class::Recordset - Responsible for fetching and creating recordsets.
13
14 =head1 SYNOPSIS;
15
16 $rs=MyApp::DB::Class->search(registered=>1);
17
18 =head1 DESCRIPTION
19
20 The recordset is also know as an iterator.
21
22 =head1 METHODS
23
24 =over 4
25
26 =item new  <db_class> <attrs>
27
28 The recordset constructor. Takes a db class and an
29 attribute hash (see below for more info on attributes)
30
31 =cut
32
33 sub new {
34   my ($it_class, $db_class, $attrs) = @_;
35   #use Data::Dumper; warn Dumper(@_);
36   $it_class = ref $it_class if ref $it_class;
37   $attrs = { %{ $attrs || {} } };
38   my %seen;
39   $attrs->{cols} ||= [ map { "me.$_" } $db_class->_select_columns ];
40   $attrs->{from} ||= [ { 'me' => $db_class->_table_name } ];
41   if ($attrs->{join}) {
42     foreach my $j (ref $attrs->{join} eq 'ARRAY'
43               ? (@{$attrs->{join}}) : ($attrs->{join})) {
44       if (ref $j eq 'HASH') {
45         $seen{$_} = 1 foreach keys %$j;
46       } else {
47         $seen{$j} = 1;
48       }
49     }
50     push(@{$attrs->{from}}, $db_class->_resolve_join($attrs->{join}, 'me'));
51   }
52   foreach my $pre (@{$attrs->{prefetch} || []}) {
53     push(@{$attrs->{from}}, $db_class->_resolve_join($pre, 'me'))
54       unless $seen{$pre};
55     push(@{$attrs->{cols}},
56       map { "$pre.$_" }
57       $db_class->_relationships->{$pre}->{class}->_select_columns);
58   }
59   my $new = {
60     class => $db_class,
61     cols => $attrs->{cols} || [ $db_class->_select_columns ],
62     cond => $attrs->{where},
63     from => $attrs->{from} || $db_class->_table_name,
64     count => undef,
65     pager => undef,
66     attrs => $attrs };
67   bless ($new, $it_class);
68   $new->pager if ($attrs->{page});
69   return $new;
70 }
71
72 =item cursor
73
74 Return a storage driven cursor to the given record set.
75
76 =cut
77
78 sub cursor {
79   my ($self) = @_;
80   my ($db_class, $attrs) = @{$self}{qw/class attrs/};
81   if ($attrs->{page}) {
82     $attrs->{rows} = $self->pager->entries_per_page;
83     $attrs->{offset} = $self->pager->skipped;
84   }
85   return $self->{cursor}
86     ||= $db_class->storage->select($self->{from}, $self->{cols},
87           $attrs->{where},$attrs);
88 }
89
90 =item slice <first> <last>
91
92 return a number of elements from the given record set.
93
94 =cut
95
96 sub slice {
97   my ($self, $min, $max) = @_;
98   my $attrs = { %{ $self->{attrs} || {} } };
99   $self->{class}->throw("Can't slice without where") unless $attrs->{where};
100   $attrs->{offset} = $min;
101   $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
102   my $slice = $self->new($self->{class}, $attrs);
103   return (wantarray ? $slice->all : $slice);
104 }
105
106 =item next 
107
108 Returns the next element in this record set.
109
110 =cut
111
112 sub next {
113   my ($self) = @_;
114   my @row = $self->cursor->next;
115   return unless (@row);
116   return $self->_construct_object(@row);
117 }
118
119 sub _construct_object {
120   my ($self, @row) = @_;
121   my @cols = @{ $self->{attrs}{cols} };
122   s/^me\.// for @cols;
123   @cols = grep { ! /\./ } @cols;
124   my $new;
125   unless ($self->{attrs}{prefetch}) {
126     $new = $self->{class}->_row_to_object(\@cols, \@row);
127   } else {
128     my @main = splice(@row, 0, scalar @cols);
129     $new = $self->{class}->_row_to_object(\@cols, \@main);
130     PRE: foreach my $pre (@{$self->{attrs}{prefetch}}) {
131       my $rel_obj = $self->{class}->_relationships->{$pre};
132       my $pre_class = $self->{class}->resolve_class($rel_obj->{class});
133       my @pre_cols = $pre_class->_select_columns;
134       my @vals = splice(@row, 0, scalar @pre_cols);
135       my $fetched = $pre_class->_row_to_object(\@pre_cols, \@vals);
136       $self->{class}->throw("No accessor for prefetched $pre")
137         unless defined $rel_obj->{attrs}{accessor};
138       if ($rel_obj->{attrs}{accessor} eq 'single') {
139         foreach my $pri ($rel_obj->{class}->primary_columns) {
140           unless (defined $fetched->get_column($pri)) {
141             undef $fetched;
142             last;
143           }
144         }
145         $new->{_relationship_data}{$pre} = $fetched;
146       } elsif ($rel_obj->{attrs}{accessor} eq 'filter') {
147         $new->{_inflated_column}{$pre} = $fetched;
148       } else {
149         $self->{class}->throw("Don't know how to store prefetched $pre");
150       }
151     }
152   }
153   $new = $self->{attrs}{record_filter}->($new)
154     if exists $self->{attrs}{record_filter};
155   return $new;
156 }
157
158 =item count
159
160 Performs an SQL count with the same query as the resultset was built
161 with to find the number of elements.
162
163 =cut
164
165
166 sub count {
167   my ($self) = @_;
168   my $db_class = $self->{class};
169   my $attrs = { %{ $self->{attrs} } };
170   unless ($self->{count}) {
171     # offset and order by are not needed to count
172     delete $attrs->{$_} for qw/offset order_by/;
173         
174     my @cols = 'COUNT(*)';
175     $self->{count} = $db_class->storage->select_single($self->{from}, \@cols,
176                                               $self->{cond}, $attrs);
177   }
178   return 0 unless $self->{count};
179   return $self->{pager}->entries_on_this_page if ($self->{pager});
180   return ( $attrs->{rows} && $attrs->{rows} < $self->{count} ) 
181     ? $attrs->{rows} 
182     : $self->{count};
183 }
184
185 =item all
186
187 Returns all elements in the recordset. Is called implictly if the search
188 method is used in list context.
189
190 =cut
191
192 sub all {
193   my ($self) = @_;
194   return map { $self->_construct_object(@$_); }
195            $self->cursor->all;
196 }
197
198 =item reset
199
200 Reset this recordset's cursor, so you can iterate through the elements again.
201
202 =cut
203
204 sub reset {
205   my ($self) = @_;
206   $self->cursor->reset;
207   return $self;
208 }
209
210 =item first
211
212 resets the recordset and returns the first element.
213
214 =cut
215
216 sub first {
217   return $_[0]->reset->next;
218 }
219
220 =item delete
221
222 Deletes all elements in the recordset.
223
224 =cut
225
226 sub delete {
227   my ($self) = @_;
228   $_->delete for $self->all;
229   return 1;
230 }
231
232 *delete_all = \&delete; # Yeah, yeah, yeah ...
233
234 =item pager
235
236 Returns a L<Data::Page> object for the current resultset. Only makes
237 sense for queries with page turned on.
238
239 =cut
240
241 sub pager {
242   my ($self) = @_;
243   my $attrs = $self->{attrs};
244   delete $attrs->{offset};
245   my $rows_per_page = delete $attrs->{rows} || 10;
246   $self->{pager} ||= Data::Page->new(
247     $self->count, $rows_per_page, $attrs->{page} || 1);
248   $attrs->{rows} = $rows_per_page;
249   return $self->{pager};
250 }
251
252 =item page <page>
253
254 Returns a new recordset representing a given page.
255
256 =cut
257
258 sub page {
259   my ($self, $page) = @_;
260   my $attrs = $self->{attrs};
261   $attrs->{page} = $page;
262   return $self->new($self->{class}, $attrs);
263 }
264
265 =back 
266
267 =head1 Attributes
268
269 The recordset is responsible for handling the various attributes that
270 can be passed in with the search functions. Here's an overview of them:
271
272 =over 4
273
274 =item order_by
275
276 Which column to order the results by. 
277
278 =item cols
279
280 Which cols should be retrieved on the first search.
281
282 =item join
283
284 Contains a list of relations that should be joined for this query. Can also 
285 contain a hash referece to refer to that relation's relations.
286
287 =item from 
288
289 This attribute can contain a arrayref of  elements. each element can be another
290 arrayref, to nest joins, or it can be a hash which represents the two sides
291 of the join. 
292
293 *NOTE* Use this on your own risk. This allows you to shoot your foot off!
294
295 =item page
296
297 Should the resultset be paged? This can also be enabled by using the 
298 'page' option.
299
300 =item rows
301
302 For paged resultsset, how  many rows per page
303
304 =item  offset
305
306 For paged resultsset, which page to start on.
307
308 =back
309
310 1;