Looks like RSC is finally (halfway) fixed
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSetColumn.pm
1 package DBIx::Class::ResultSetColumn;
2
3 use strict;
4 use warnings;
5
6 use base 'DBIx::Class';
7
8 use Carp::Clan qw/^DBIx::Class/;
9 use DBIx::Class::Exception;
10 use List::Util;
11
12 =head1 NAME
13
14   DBIx::Class::ResultSetColumn - helpful methods for messing
15   with a single column of the resultset
16
17 =head1 SYNOPSIS
18
19   $rs = $schema->resultset('CD')->search({ artist => 'Tool' });
20   $rs_column = $rs->get_column('year');
21   $max_year = $rs_column->max; #returns latest year
22
23 =head1 DESCRIPTION
24
25 A convenience class used to perform operations on a specific column of
26 a resultset.
27
28 =cut
29
30 =head1 METHODS
31
32 =head2 new
33
34   my $obj = DBIx::Class::ResultSetColumn->new($rs, $column);
35
36 Creates a new resultset column object from the resultset and column
37 passed as params. Used internally by L<DBIx::Class::ResultSet/get_column>.
38
39 =cut
40
41 sub new {
42   my ($class, $rs, $column) = @_;
43   $class = ref $class if ref $class;
44
45   $rs->throw_exception('column must be supplied') unless $column;
46
47   my $orig_attrs = $rs->_resolved_attrs;
48
49   # If $column can be found in the 'as' list of the parent resultset, use the
50   # corresponding element of its 'select' list (to keep any custom column
51   # definition set up with 'select' or '+select' attrs), otherwise use $column
52   # (to create a new column definition on-the-fly).
53   my $as_list = $orig_attrs->{as} || [];
54   my $select_list = $orig_attrs->{select} || [];
55   my $as_index = List::Util::first { ($as_list->[$_] || "") eq $column } 0..$#$as_list;
56   my $select = defined $as_index ? $select_list->[$as_index] : $column;
57
58   my $new_parent_rs;
59   # analyze the order_by, and see if it is done over a function/nonexistentcolumn
60   # if this is the case we will need to wrap a subquery since the result of RSC
61   # *must* be a single column select
62   my %collist = map { $_ => 1 } ($rs->result_source->columns, $column);
63   if (
64     scalar grep
65       { ! $collist{$_} }
66       ( $rs->result_source->schema->storage->_parse_order_by ($orig_attrs->{order_by} ) ) 
67   ) {
68     my $alias = $rs->current_source_alias;
69     $new_parent_rs = $rs->result_source->resultset->search ( {}, {
70       alias => $alias,
71       from => [{
72         $alias => $rs->as_query,
73         -alias => $alias,
74         -source_handle => $rs->result_source->handle,
75       }]
76     });
77   }
78
79   $new_parent_rs ||= $rs->search_rs;
80   my $new_attrs = $new_parent_rs->{attrs} ||= {};
81
82   # FIXME - this should go away when the chaining branch is merged
83   # since what we do is actually chain to the original resultset, we need to throw
84   # away all selectors (otherwise they'll chain)
85   delete $new_attrs->{$_} for (qw/columns +columns select +select as +as cols include_columns/);
86
87   # prefetch causes additional columns to be fetched, but we can not just make a new
88   # rs via the _resolved_attrs trick - we need to retain the separation between
89   # +select/+as and select/as. At the same time we want to preserve any joins that the
90   # prefetch would otherwise generate.
91   $new_attrs->{join} = $rs->_merge_attr( delete $new_attrs->{join}, delete $new_attrs->{prefetch} );
92
93   # {collapse} would mean a has_many join was injected, which in turn means
94   # we need to group *IF WE CAN* (only if the column in question is unique)
95   if (!$new_attrs->{group_by} && keys %{$orig_attrs->{collapse}}) {
96
97     # scan for a constraint that would contain our column only - that'd be proof
98     # enough it is unique
99     my $constraints = { $rs->result_source->unique_constraints };
100     for my $constraint_columns ( values %$constraints ) {
101
102       next unless @$constraint_columns == 1;
103
104       my $col = $constraint_columns->[0];
105       my $fqcol = join ('.', $new_attrs->{alias}, $col);
106
107       if ($col eq $select or $fqcol eq $select) {
108         $new_attrs->{group_by} = [ $select ];
109         delete $new_attrs->{distinct}; # it is ignored when group_by is present
110         last;
111       }
112     }
113
114     if (!$new_attrs->{group_by}) {
115       carp (
116           "Attempting to retrieve non-unique column '$column' on a resultset containing "
117         . 'one-to-many joins will return duplicate results.'
118       );
119     }
120   }
121
122   my $new = bless { _select => $select, _as => $column, _parent_resultset => $new_parent_rs }, $class;
123   return $new;
124 }
125
126 =head2 as_query
127
128 =over 4
129
130 =item Arguments: none
131
132 =item Return Value: \[ $sql, @bind ]
133
134 =back
135
136 Returns the SQL query and bind vars associated with the invocant.
137
138 This is generally used as the RHS for a subquery.
139
140 =cut
141
142 sub as_query { return shift->_resultset->as_query(@_) }
143
144 =head2 next
145
146 =over 4
147
148 =item Arguments: none
149
150 =item Return Value: $value
151
152 =back
153
154 Returns the next value of the column in the resultset (or C<undef> if
155 there is none).
156
157 Much like L<DBIx::Class::ResultSet/next> but just returning the 
158 one value.
159
160 =cut
161
162 sub next {
163   my $self = shift;
164
165   # using cursor so we don't inflate anything
166   my ($row) = $self->_resultset->cursor->next;
167
168   return $row;
169 }
170
171 =head2 all
172
173 =over 4
174
175 =item Arguments: none
176
177 =item Return Value: @values
178
179 =back
180
181 Returns all values of the column in the resultset (or C<undef> if
182 there are none).
183
184 Much like L<DBIx::Class::ResultSet/all> but returns values rather
185 than row objects.
186
187 =cut
188
189 sub all {
190   my $self = shift;
191
192   # using cursor so we don't inflate anything
193   return map { $_->[0] } $self->_resultset->cursor->all;
194 }
195
196 =head2 reset
197
198 =over 4
199
200 =item Arguments: none
201
202 =item Return Value: $self
203
204 =back
205
206 Resets the underlying resultset's cursor, so you can iterate through the
207 elements of the column again.
208
209 Much like L<DBIx::Class::ResultSet/reset>.
210
211 =cut
212
213 sub reset {
214   my $self = shift;
215   $self->_resultset->cursor->reset;
216   return $self;
217 }
218
219 =head2 first
220
221 =over 4
222
223 =item Arguments: none
224
225 =item Return Value: $value
226
227 =back
228
229 Resets the underlying resultset and returns the next value of the column in the
230 resultset (or C<undef> if there is none).
231
232 Much like L<DBIx::Class::ResultSet/first> but just returning the one value.
233
234 =cut
235
236 sub first {
237   my $self = shift;
238
239   # using cursor so we don't inflate anything
240   $self->_resultset->cursor->reset;
241   my ($row) = $self->_resultset->cursor->next;
242
243   return $row;
244 }
245
246 =head2 single
247
248 =over 4
249
250 =item Arguments: none
251
252 =item Return Value: $value
253
254 =back
255
256 Much like L<DBIx::Class::ResultSet/single> fetches one and only one column
257 value using the cursor directly. If additional rows are present a warning
258 is issued before discarding the cursor.
259
260 =cut
261
262 sub single {
263   my $self = shift;
264
265   my $attrs = $self->_resultset->_resolved_attrs;
266   my ($row) = $self->_resultset->result_source->storage->select_single(
267     $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
268   );
269
270   return $row;
271 }
272
273 =head2 min
274
275 =over 4
276
277 =item Arguments: none
278
279 =item Return Value: $lowest_value
280
281 =back
282
283   my $first_year = $year_col->min();
284
285 Wrapper for ->func. Returns the lowest value of the column in the
286 resultset (or C<undef> if there are none).
287
288 =cut
289
290 sub min {
291   return shift->func('MIN');
292 }
293
294 =head2 min_rs
295
296 =over 4
297
298 =item Arguments: none
299
300 =item Return Value: $resultset
301
302 =back
303
304   my $rs = $year_col->min_rs();
305
306 Wrapper for ->func_rs for function MIN().
307
308 =cut
309
310 sub min_rs { return shift->func_rs('MIN') }
311
312 =head2 max
313
314 =over 4
315
316 =item Arguments: none
317
318 =item Return Value: $highest_value
319
320 =back
321
322   my $last_year = $year_col->max();
323
324 Wrapper for ->func. Returns the highest value of the column in the
325 resultset (or C<undef> if there are none).
326
327 =cut
328
329 sub max {
330   return shift->func('MAX');
331 }
332
333 =head2 max_rs
334
335 =over 4
336
337 =item Arguments: none
338
339 =item Return Value: $resultset
340
341 =back
342
343   my $rs = $year_col->max_rs();
344
345 Wrapper for ->func_rs for function MAX().
346
347 =cut
348
349 sub max_rs { return shift->func_rs('MAX') }
350
351 =head2 sum
352
353 =over 4
354
355 =item Arguments: none
356
357 =item Return Value: $sum_of_values
358
359 =back
360
361   my $total = $prices_col->sum();
362
363 Wrapper for ->func. Returns the sum of all the values in the column of
364 the resultset. Use on varchar-like columns at your own risk.
365
366 =cut
367
368 sub sum {
369   return shift->func('SUM');
370 }
371
372 =head2 sum_rs
373
374 =over 4
375
376 =item Arguments: none
377
378 =item Return Value: $resultset
379
380 =back
381
382   my $rs = $year_col->sum_rs();
383
384 Wrapper for ->func_rs for function SUM().
385
386 =cut
387
388 sub sum_rs { return shift->func_rs('SUM') }
389
390 =head2 func
391
392 =over 4
393
394 =item Arguments: $function
395
396 =item Return Value: $function_return_value
397
398 =back
399
400   $rs = $schema->resultset("CD")->search({});
401   $length = $rs->get_column('title')->func('LENGTH');
402
403 Runs a query using the function on the column and returns the
404 value. Produces the following SQL:
405
406   SELECT LENGTH( title ) FROM cd me
407
408 =cut
409
410 sub func {
411   my ($self,$function) = @_;
412   my $cursor = $self->func_rs($function)->cursor;
413
414   if( wantarray ) {
415     return map { $_->[ 0 ] } $cursor->all;
416   }
417
418   return ( $cursor->next )[ 0 ];
419 }
420
421 =head2 func_rs
422
423 =over 4
424
425 =item Arguments: $function
426
427 =item Return Value: $resultset
428
429 =back
430
431 Creates the resultset that C<func()> uses to run its query.
432
433 =cut
434
435 sub func_rs {
436   my ($self,$function) = @_;
437   return $self->{_parent_resultset}->search(
438     undef, {
439       select => {$function => $self->{_select}},
440       as => [$self->{_as}],
441     },
442   );
443 }
444
445 =head2 throw_exception
446
447 See L<DBIx::Class::Schema/throw_exception> for details.
448
449 =cut 
450
451 sub throw_exception {
452   my $self=shift;
453
454   if (ref $self && $self->{_parent_resultset}) {
455     $self->{_parent_resultset}->throw_exception(@_);
456   }
457   else {
458     DBIx::Class::Exception->throw(@_);
459   }
460 }
461
462 # _resultset
463 #
464 # Arguments: none
465 #
466 # Return Value: $resultset
467 #
468 #  $year_col->_resultset->next
469 #
470 # Returns the underlying resultset. Creates it from the parent resultset if
471 # necessary.
472 #
473 sub _resultset {
474   my $self = shift;
475
476   return $self->{_resultset} ||= $self->{_parent_resultset}->search(undef,
477     {
478       select => [$self->{_select}],
479       as => [$self->{_as}]
480     }
481   );
482 }
483
484 1;
485
486 =head1 AUTHORS
487
488 Luke Saunders <luke.saunders@gmail.com>
489
490 Jess Robinson
491
492 =head1 LICENSE
493
494 You may distribute this code under the same terms as Perl itself.
495
496 =cut