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