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