1 package DBIx::Class::ResultSetColumn;
6 use base 'DBIx::Class';
8 use DBIx::Class::_Util qw( fail_on_internal_wantarray fail_on_internal_call );
13 DBIx::Class::ResultSetColumn - helpful methods for messing
14 with a single column of the resultset
18 $rs = $schema->resultset('CD')->search({ artist => 'Tool' });
19 $rs_column = $rs->get_column('year');
20 $max_year = $rs_column->max; #returns latest year
24 A convenience class used to perform operations on a specific column of
33 my $obj = DBIx::Class::ResultSetColumn->new($rs, $column);
35 Creates a new resultset column object from the resultset and column
36 passed as params. Used internally by L<DBIx::Class::ResultSet/get_column>.
41 my ($class, $rs, $column) = @_;
42 $class = ref $class if ref $class;
44 $rs->throw_exception('column must be supplied') unless $column;
46 my $orig_attrs = $rs->_resolved_attrs;
47 my $alias = $rs->current_source_alias;
48 my $rsrc = $rs->result_source;
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} || [];
56 my ($as_index) = grep { ($as_list->[$_] || "") eq $column } 0..$#$as_list;
57 my $select = defined $as_index ? $select_list->[$as_index] : $column;
60 for ($rsrc->columns, $column) {
61 if ($_ =~ /^ \Q$alias\E \. ([^\.]+) $ /x) {
65 $colmap->{"$alias.$_"} = $_;
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
76 { ! exists $colmap->{$_->[0]} }
77 ( $rsrc->schema->storage->_extract_order_criteria ($orig_attrs->{order_by} ) )
79 # nuke the prefetch before collapsing to sql
80 my $subq_rs = $rs->search_rs;
81 $subq_rs->{attrs}{join} = $subq_rs->_merge_joinpref_attr( $subq_rs->{attrs}{join}, delete $subq_rs->{attrs}{prefetch} );
82 $new_parent_rs = $subq_rs->as_subselect_rs;
85 $new_parent_rs ||= $rs->search_rs;
86 my $new_attrs = $new_parent_rs->{attrs} ||= {};
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
90 # +select/+as and select/as. At the same time we want to preserve any joins that the
91 # prefetch would otherwise generate.
92 $new_attrs->{join} = $rs->_merge_joinpref_attr( $new_attrs->{join}, delete $new_attrs->{prefetch} );
94 # {collapse} would mean a has_many join was injected, which in turn means
95 # we need to group *IF WE CAN* (only if the column in question is unique)
96 if (!$orig_attrs->{group_by} && $orig_attrs->{collapse}) {
98 if ($colmap->{$select} and $rsrc->_identifying_column_set([$colmap->{$select}])) {
99 $new_attrs->{group_by} = [ $select ];
100 delete @{$new_attrs}{qw(distinct _grouped_by_distinct)}; # it is ignored when group_by is present
104 "Attempting to retrieve non-unique column '$column' on a resultset containing "
105 . 'one-to-many joins will return duplicate results.'
113 _parent_resultset => $new_parent_rs
121 =item Arguments: none
123 =item Return Value: \[ $sql, L<@bind_values|DBIx::Class::ResultSet/DBIC BIND VALUES> ]
127 Returns the SQL query and bind vars associated with the invocant.
129 This is generally used as the RHS for a subquery.
133 sub as_query { return shift->_resultset->as_query(@_) }
139 =item Arguments: none
141 =item Return Value: $value
145 Returns the next value of the column in the resultset (or C<undef> if
148 Much like L<DBIx::Class::ResultSet/next> but just returning the
156 # using cursor so we don't inflate anything
157 my ($row) = $self->_resultset->cursor->next;
166 =item Arguments: none
168 =item Return Value: @values
172 Returns all values of the column in the resultset (or C<undef> if
175 Much like L<DBIx::Class::ResultSet/all> but returns values rather
183 # using cursor so we don't inflate anything
184 return map { $_->[0] } $self->_resultset->cursor->all;
191 =item Arguments: none
193 =item Return Value: $self
197 Resets the underlying resultset's cursor, so you can iterate through the
198 elements of the column again.
200 Much like L<DBIx::Class::ResultSet/reset>.
206 $self->_resultset->cursor->reset;
214 =item Arguments: none
216 =item Return Value: $value
220 Resets the underlying resultset and returns the next value of the column in the
221 resultset (or C<undef> if there is none).
223 Much like L<DBIx::Class::ResultSet/first> but just returning the one value.
230 # using cursor so we don't inflate anything
231 $self->_resultset->cursor->reset;
232 my ($row) = $self->_resultset->cursor->next;
241 =item Arguments: none
243 =item Return Value: $value
247 Much like L<DBIx::Class::ResultSet/single> fetches one and only one column
248 value using the cursor directly. If additional rows are present a warning
249 is issued before discarding the cursor.
256 my $attrs = $self->_resultset->_resolved_attrs;
257 my ($row) = $self->_resultset->result_source->schema->storage->select_single(
258 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
268 =item Arguments: none
270 =item Return Value: $lowest_value
274 my $first_year = $year_col->min();
276 Wrapper for ->func. Returns the lowest value of the column in the
277 resultset (or C<undef> if there are none).
282 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
290 =item Arguments: none
292 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
296 my $rs = $year_col->min_rs();
298 Wrapper for ->func_rs for function MIN().
303 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
304 $_[0]->func_rs('MIN')
311 =item Arguments: none
313 =item Return Value: $highest_value
317 my $last_year = $year_col->max();
319 Wrapper for ->func. Returns the highest value of the column in the
320 resultset (or C<undef> if there are none).
325 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
333 =item Arguments: none
335 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
339 my $rs = $year_col->max_rs();
341 Wrapper for ->func_rs for function MAX().
346 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
347 $_[0]->func_rs('MAX')
354 =item Arguments: none
356 =item Return Value: $sum_of_values
360 my $total = $prices_col->sum();
362 Wrapper for ->func. Returns the sum of all the values in the column of
363 the resultset. Use on varchar-like columns at your own risk.
368 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
376 =item Arguments: none
378 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
382 my $rs = $year_col->sum_rs();
384 Wrapper for ->func_rs for function SUM().
389 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
390 $_[0]->func_rs('SUM')
397 =item Arguments: $function
399 =item Return Value: $function_return_value
403 $rs = $schema->resultset("CD")->search({});
404 $length = $rs->get_column('title')->func('LENGTH');
406 Runs a query using the function on the column and returns the
407 value. Produces the following SQL:
409 SELECT LENGTH( title ) FROM cd me
414 my ($self,$function) = @_;
415 my $cursor = $self->func_rs($function)->cursor;
418 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_WANTARRAY and my $sog = fail_on_internal_wantarray;
419 return map { $_->[ 0 ] } $cursor->all;
422 return ( $cursor->next )[ 0 ];
429 =item Arguments: $function
431 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
435 Creates the resultset that C<func()> uses to run its query.
440 my ($self,$function) = @_;
442 my $rs = $self->{_parent_resultset};
443 my $select = $self->{_select};
446 if ($rs->_resolved_attrs->{group_by}) {
447 $select = $self->{_as};
448 $rs = $rs->as_subselect_rs;
451 $rs->search( undef, {
452 columns => { $self->{_as} => { $function => $select } }
456 =head2 throw_exception
458 See L<DBIx::Class::Schema/throw_exception> for details.
462 sub throw_exception {
465 if (ref $self && $self->{_parent_resultset}) {
466 $self->{_parent_resultset}->throw_exception(@_);
469 DBIx::Class::Exception->throw(@_);
477 # Return Value: $resultset
479 # $year_col->_resultset->next
481 # Returns the underlying resultset. Creates it from the parent resultset if
487 return $self->{_resultset} ||= do {
489 my $select = $self->{_select};
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;
496 unless( $cols{$select} ) {
498 'Use of distinct => 1 while selecting anything other than a column '
499 . 'declared on the primary ResultSource is deprecated (you selected '
500 . "'$self->{_as}') - please supply an explicit group_by instead"
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
506 $select = \[ $rsrc->schema->storage->sql_maker->_recurse_fields($select) ];
510 $self->{_parent_resultset}->search(undef, {
511 columns => { $self->{_as} => $select }
516 =head1 FURTHER QUESTIONS?
518 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
520 =head1 COPYRIGHT AND LICENSE
522 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
523 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
524 redistribute it and/or modify it under the same terms as the
525 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.