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