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