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