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