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