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