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