3b1f87532f13a046cf32551588e08f98d3d95724
[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 $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   my $new_parent_rs;
74   # analyze the order_by, and see if it is done over a function/nonexistentcolumn
75   # if this is the case we will need to wrap a subquery since the result of RSC
76   # *must* be a single column select
77   if (
78     scalar grep
79       { ! exists $colmap->{$_->[0]} }
80       ( $rsrc->schema->storage->_extract_order_criteria ($orig_attrs->{order_by} ) )
81   ) {
82     # nuke the prefetch before collapsing to sql
83     my $subq_rs = $rs->search_rs;
84     $subq_rs->{attrs}{join} = $subq_rs->_merge_joinpref_attr( $subq_rs->{attrs}{join}, delete $subq_rs->{attrs}{prefetch} );
85     $new_parent_rs = $subq_rs->as_subselect_rs;
86   }
87
88   $new_parent_rs ||= $rs->search_rs;
89   my $new_attrs = $new_parent_rs->{attrs} ||= {};
90
91   # prefetch causes additional columns to be fetched, but we can not just make a new
92   # rs via the _resolved_attrs trick - we need to retain the separation between
93   # +select/+as and select/as. At the same time we want to preserve any joins that the
94   # prefetch would otherwise generate.
95   $new_attrs->{join} = $rs->_merge_joinpref_attr( $new_attrs->{join}, delete $new_attrs->{prefetch} );
96
97   # {collapse} would mean a has_many join was injected, which in turn means
98   # we need to group *IF WE CAN* (only if the column in question is unique)
99   if (!$orig_attrs->{group_by} && $orig_attrs->{collapse}) {
100
101     if ($colmap->{$select} and $rsrc->_identifying_column_set([$colmap->{$select}])) {
102       $new_attrs->{group_by} = [ $select ];
103       delete @{$new_attrs}{qw(distinct _grouped_by_distinct)}; # it is ignored when group_by is present
104     }
105     else {
106       carp (
107           "Attempting to retrieve non-unique column '$column' on a resultset containing "
108         . 'one-to-many joins will return duplicate results.'
109       );
110     }
111   }
112
113   # collapse the selector to a literal so that it survives a possible distinct parse
114   # if it turns out to be an aggregate - at least the user will get a proper exception
115   # instead of silent drop of the group_by altogether
116   my $new = bless {
117     _select => \ $rsrc->storage->sql_maker->_recurse_fields($select),
118     _as => $column,
119     _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, L<@bind_values|DBIx::Class::ResultSet/DBIC BIND VALUES> ]
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 result 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: L<$resultset|DBIx::Class::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: L<$resultset|DBIx::Class::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: L<$resultset|DBIx::Class::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     DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_WANTARRAY and my $sog = fail_on_internal_wantarray($self);
413     return map { $_->[ 0 ] } $cursor->all;
414   }
415
416   return ( $cursor->next )[ 0 ];
417 }
418
419 =head2 func_rs
420
421 =over 4
422
423 =item Arguments: $function
424
425 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
426
427 =back
428
429 Creates the resultset that C<func()> uses to run its query.
430
431 =cut
432
433 sub func_rs {
434   my ($self,$function) = @_;
435
436   my $rs = $self->{_parent_resultset};
437   my $select = $self->{_select};
438
439   # wrap a grouped rs
440   if ($rs->_resolved_attrs->{group_by}) {
441     $select = $self->{_as};
442     $rs = $rs->as_subselect_rs;
443   }
444
445   $rs->search( undef, {
446     columns => { $self->{_as} => { $function => $select } }
447   } );
448 }
449
450 =head2 throw_exception
451
452 See L<DBIx::Class::Schema/throw_exception> for details.
453
454 =cut
455
456 sub throw_exception {
457   my $self = shift;
458
459   if (ref $self && $self->{_parent_resultset}) {
460     $self->{_parent_resultset}->throw_exception(@_);
461   }
462   else {
463     DBIx::Class::Exception->throw(@_);
464   }
465 }
466
467 # _resultset
468 #
469 # Arguments: none
470 #
471 # Return Value: $resultset
472 #
473 #  $year_col->_resultset->next
474 #
475 # Returns the underlying resultset. Creates it from the parent resultset if
476 # necessary.
477 #
478 sub _resultset {
479   my $self = shift;
480
481   return $self->{_resultset} ||= $self->{_parent_resultset}->search(undef,
482     {
483       select => [$self->{_select}],
484       as => [$self->{_as}]
485     }
486   );
487 }
488
489 1;
490
491 =head1 AUTHOR AND CONTRIBUTORS
492
493 See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class
494
495 =head1 LICENSE
496
497 You may distribute this code under the same terms as Perl itself.
498
499 =cut