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