Streamline ::ResultSource::* inheritance, similar to d009cb7d
[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;
e5053694 8use DBIx::Class::_Util qw( fail_on_internal_wantarray fail_on_internal_call );
64c50e81 9use namespace::clean;
94244987 10
2bb7b40b 11=head1 NAME
12
13 DBIx::Class::ResultSetColumn - helpful methods for messing
14 with a single column of the resultset
15
16=head1 SYNOPSIS
17
18 $rs = $schema->resultset('CD')->search({ artist => 'Tool' });
19 $rs_column = $rs->get_column('year');
20 $max_year = $rs_column->max; #returns latest year
21
22=head1 DESCRIPTION
23
eb98561c 24A convenience class used to perform operations on a specific column of
25a resultset.
2bb7b40b 26
27=cut
28
29=head1 METHODS
30
31=head2 new
32
33 my $obj = DBIx::Class::ResultSetColumn->new($rs, $column);
34
eb98561c 35Creates a new resultset column object from the resultset and column
36passed as params. Used internally by L<DBIx::Class::ResultSet/get_column>.
2bb7b40b 37
38=cut
39
40sub new {
41 my ($class, $rs, $column) = @_;
42 $class = ref $class if ref $class;
7ae9706c 43
66e33361 44 $rs->throw_exception('column must be supplied') unless $column;
7ae9706c 45
d8dbe471 46 my $orig_attrs = $rs->_resolved_attrs;
9b8930f4 47 my $alias = $rs->current_source_alias;
2b3fc408 48 my $rsrc = $rs->result_source;
472d7df3 49
50 # If $column can be found in the 'as' list of the parent resultset, use the
51 # corresponding element of its 'select' list (to keep any custom column
52 # definition set up with 'select' or '+select' attrs), otherwise use $column
53 # (to create a new column definition on-the-fly).
54 my $as_list = $orig_attrs->{as} || [];
55 my $select_list = $orig_attrs->{select} || [];
87b12551 56 my ($as_index) = grep { ($as_list->[$_] || "") eq $column } 0..$#$as_list;
472d7df3 57 my $select = defined $as_index ? $select_list->[$as_index] : $column;
58
aca094b4 59 my $colmap;
2b3fc408 60 for ($rsrc->columns, $column) {
61 if ($_ =~ /^ \Q$alias\E \. ([^\.]+) $ /x) {
62 $colmap->{$_} = $1;
63 }
64 elsif ($_ !~ /\./) {
65 $colmap->{"$alias.$_"} = $_;
66 $colmap->{$_} = $_;
67 }
68 }
69
aca094b4 70 my $new_parent_rs;
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
aca094b4 80 my $subq_rs = $rs->search_rs;
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
722274d0 110 return bless {
111 _select => $select,
aca094b4 112 _as => $column,
722274d0 113 _parent_resultset => $new_parent_rs
114 }, $class;
2bb7b40b 115}
116
6dfbe2f8 117=head2 as_query
658fa250 118
119=over 4
120
428a645e 121=item Arguments: none
658fa250 122
00c12490 123=item Return Value: \[ $sql, L<@bind_values|DBIx::Class::ResultSet/DBIC BIND VALUES> ]
658fa250 124
125=back
126
127Returns the SQL query and bind vars associated with the invocant.
128
03834f77 129This is generally used as the RHS for a subquery.
c7a9d102 130
131=cut
132
0f6fc705 133sub as_query { return shift->_resultset->as_query(@_) }
c7a9d102 134
2bb7b40b 135=head2 next
136
137=over 4
138
139=item Arguments: none
140
141=item Return Value: $value
142
143=back
144
eb98561c 145Returns the next value of the column in the resultset (or C<undef> if
146there is none).
2bb7b40b 147
8273e845 148Much like L<DBIx::Class::ResultSet/next> but just returning the
eb98561c 149one value.
2bb7b40b 150
151=cut
152
153sub next {
154 my $self = shift;
b7c79955 155
156 # using cursor so we don't inflate anything
66521001 157 my ($row) = $self->_resultset->cursor->next;
b7c79955 158
2bb7b40b 159 return $row;
160}
161
162=head2 all
163
164=over 4
165
166=item Arguments: none
167
168=item Return Value: @values
169
170=back
171
eb98561c 172Returns all values of the column in the resultset (or C<undef> if
173there are none).
2bb7b40b 174
eb98561c 175Much like L<DBIx::Class::ResultSet/all> but returns values rather
fb13a49f 176than result objects.
2bb7b40b 177
178=cut
179
180sub all {
181 my $self = shift;
b7c79955 182
183 # using cursor so we don't inflate anything
66521001 184 return map { $_->[0] } $self->_resultset->cursor->all;
185}
186
187=head2 reset
188
189=over 4
190
191=item Arguments: none
192
193=item Return Value: $self
194
195=back
196
197Resets the underlying resultset's cursor, so you can iterate through the
198elements of the column again.
199
200Much like L<DBIx::Class::ResultSet/reset>.
201
202=cut
203
204sub reset {
205 my $self = shift;
206 $self->_resultset->cursor->reset;
b7c79955 207 return $self;
66521001 208}
209
210=head2 first
211
212=over 4
213
214=item Arguments: none
215
216=item Return Value: $value
217
218=back
219
220Resets the underlying resultset and returns the next value of the column in the
221resultset (or C<undef> if there is none).
222
223Much like L<DBIx::Class::ResultSet/first> but just returning the one value.
224
225=cut
226
227sub first {
228 my $self = shift;
b7c79955 229
230 # using cursor so we don't inflate anything
231 $self->_resultset->cursor->reset;
01dc6781 232 my ($row) = $self->_resultset->cursor->next;
b7c79955 233
66521001 234 return $row;
2bb7b40b 235}
236
4e55c3ae 237=head2 single
238
239=over 4
240
241=item Arguments: none
242
243=item Return Value: $value
244
245=back
246
247Much like L<DBIx::Class::ResultSet/single> fetches one and only one column
248value using the cursor directly. If additional rows are present a warning
249is issued before discarding the cursor.
250
251=cut
252
253sub single {
254 my $self = shift;
255
256 my $attrs = $self->_resultset->_resolved_attrs;
e5053694 257 my ($row) = $self->_resultset->result_source->schema->storage->select_single(
4e55c3ae 258 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
259 );
260
261 return $row;
262}
263
2bb7b40b 264=head2 min
265
266=over 4
267
268=item Arguments: none
269
270=item Return Value: $lowest_value
271
272=back
273
eb98561c 274 my $first_year = $year_col->min();
275
276Wrapper for ->func. Returns the lowest value of the column in the
277resultset (or C<undef> if there are none).
2bb7b40b 278
279=cut
280
281sub min {
e5053694 282 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
283 $_[0]->func('MIN');
2bb7b40b 284}
285
4fa7bc22 286=head2 min_rs
287
288=over 4
289
290=item Arguments: none
291
fb13a49f 292=item Return Value: L<$resultset|DBIx::Class::ResultSet>
4fa7bc22 293
294=back
295
296 my $rs = $year_col->min_rs();
297
298Wrapper for ->func_rs for function MIN().
299
300=cut
301
e5053694 302sub min_rs {
303 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
304 $_[0]->func_rs('MIN')
305}
4fa7bc22 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 {
e5053694 325 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
326 $_[0]->func('MAX');
2bb7b40b 327}
328
4fa7bc22 329=head2 max_rs
330
331=over 4
332
333=item Arguments: none
334
fb13a49f 335=item Return Value: L<$resultset|DBIx::Class::ResultSet>
4fa7bc22 336
337=back
338
339 my $rs = $year_col->max_rs();
340
341Wrapper for ->func_rs for function MAX().
342
343=cut
344
e5053694 345sub max_rs {
346 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
347 $_[0]->func_rs('MAX')
348}
4fa7bc22 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 {
e5053694 368 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
369 $_[0]->func('SUM');
2bb7b40b 370}
371
4fa7bc22 372=head2 sum_rs
373
374=over 4
375
376=item Arguments: none
377
fb13a49f 378=item Return Value: L<$resultset|DBIx::Class::ResultSet>
4fa7bc22 379
380=back
381
382 my $rs = $year_col->sum_rs();
383
384Wrapper for ->func_rs for function SUM().
385
386=cut
387
e5053694 388sub sum_rs {
389 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
390 $_[0]->func_rs('SUM')
391}
4fa7bc22 392
2bb7b40b 393=head2 func
394
395=over 4
396
397=item Arguments: $function
398
399=item Return Value: $function_return_value
400
401=back
402
e8419341 403 $rs = $schema->resultset("CD")->search({});
404 $length = $rs->get_column('title')->func('LENGTH');
2bb7b40b 405
eb98561c 406Runs a query using the function on the column and returns the
407value. Produces the following SQL:
408
409 SELECT LENGTH( title ) FROM cd me
2bb7b40b 410
411=cut
412
413sub func {
6b051e14 414 my ($self,$function) = @_;
4fa7bc22 415 my $cursor = $self->func_rs($function)->cursor;
d4daee7b 416
5d62876f 417 if( wantarray ) {
e89c7968 418 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_WANTARRAY and my $sog = fail_on_internal_wantarray;
5d62876f 419 return map { $_->[ 0 ] } $cursor->all;
420 }
421
422 return ( $cursor->next )[ 0 ];
2bb7b40b 423}
424
4fa7bc22 425=head2 func_rs
426
427=over 4
428
429=item Arguments: $function
430
fb13a49f 431=item Return Value: L<$resultset|DBIx::Class::ResultSet>
4fa7bc22 432
433=back
434
435Creates the resultset that C<func()> uses to run its query.
436
437=cut
438
439sub func_rs {
440 my ($self,$function) = @_;
3214abc7 441
442 my $rs = $self->{_parent_resultset};
443 my $select = $self->{_select};
444
445 # wrap a grouped rs
446 if ($rs->_resolved_attrs->{group_by}) {
447 $select = $self->{_as};
448 $rs = $rs->as_subselect_rs;
449 }
450
451 $rs->search( undef, {
452 columns => { $self->{_as} => { $function => $select } }
453 } );
4fa7bc22 454}
455
5d1fc7dc 456=head2 throw_exception
457
458See L<DBIx::Class::Schema/throw_exception> for details.
d4daee7b 459
8273e845 460=cut
d4daee7b 461
5d1fc7dc 462sub throw_exception {
f9080e45 463 my $self = shift;
1a58752c 464
5d1fc7dc 465 if (ref $self && $self->{_parent_resultset}) {
1a58752c 466 $self->{_parent_resultset}->throw_exception(@_);
467 }
468 else {
469 DBIx::Class::Exception->throw(@_);
5d1fc7dc 470 }
471}
472
b6e85b48 473# _resultset
474#
475# Arguments: none
476#
477# Return Value: $resultset
478#
479# $year_col->_resultset->next
480#
481# Returns the underlying resultset. Creates it from the parent resultset if
482# necessary.
b7c79955 483#
66521001 484sub _resultset {
485 my $self = shift;
486
722274d0 487 return $self->{_resultset} ||= do {
488
489 my $select = $self->{_select};
490
491 if ($self->{_parent_resultset}{attrs}{distinct}) {
492 my $alias = $self->{_parent_resultset}->current_source_alias;
493 my $rsrc = $self->{_parent_resultset}->result_source;
494 my %cols = map { $_ => 1, "$alias.$_" => 1 } $rsrc->columns;
495
496 unless( $cols{$select} ) {
497 carp_unique(
498 'Use of distinct => 1 while selecting anything other than a column '
885c3dbd 499 . 'declared on the primary ResultSource is deprecated (you selected '
500 . "'$self->{_as}') - please supply an explicit group_by instead"
722274d0 501 );
502
503 # collapse the selector to a literal so that it survives the distinct parse
504 # if it turns out to be an aggregate - at least the user will get a proper exception
505 # instead of silent drop of the group_by altogether
e5053694 506 $select = \[ $rsrc->schema->storage->sql_maker->_recurse_fields($select) ];
722274d0 507 }
66521001 508 }
722274d0 509
510 $self->{_parent_resultset}->search(undef, {
511 columns => { $self->{_as} => $select }
512 });
513 };
66521001 514}
515
a2bd3796 516=head1 FURTHER QUESTIONS?
2bb7b40b 517
a2bd3796 518Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
eb98561c 519
a2bd3796 520=head1 COPYRIGHT AND LICENSE
2bb7b40b 521
a2bd3796 522This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
523by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
524redistribute it and/or modify it under the same terms as the
525L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
2bb7b40b 526
527=cut
a2bd3796 528
5291;
530