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