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