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