1 package DBIx::Class::ResultSetColumn;
6 use base 'DBIx::Class';
8 use DBIx::Class::_Util 'fail_on_internal_wantarray';
11 # not importing first() as it will clash with our own method
16 DBIx::Class::ResultSetColumn - helpful methods for messing
17 with a single column of the resultset
21 $rs = $schema->resultset('CD')->search({ artist => 'Tool' });
22 $rs_column = $rs->get_column('year');
23 $max_year = $rs_column->max; #returns latest year
27 A convenience class used to perform operations on a specific column of
36 my $obj = DBIx::Class::ResultSetColumn->new($rs, $column);
38 Creates a new resultset column object from the resultset and column
39 passed as params. Used internally by L<DBIx::Class::ResultSet/get_column>.
44 my ($class, $rs, $column) = @_;
45 $class = ref $class if ref $class;
47 $rs->throw_exception('column must be supplied') unless $column;
49 my $orig_attrs = $rs->_resolved_attrs;
50 my $alias = $rs->current_source_alias;
51 my $rsrc = $rs->result_source;
53 # If $column can be found in the 'as' list of the parent resultset, use the
54 # corresponding element of its 'select' list (to keep any custom column
55 # definition set up with 'select' or '+select' attrs), otherwise use $column
56 # (to create a new column definition on-the-fly).
57 my $as_list = $orig_attrs->{as} || [];
58 my $select_list = $orig_attrs->{select} || [];
59 my $as_index = List::Util::first { ($as_list->[$_] || "") eq $column } 0..$#$as_list;
60 my $select = defined $as_index ? $select_list->[$as_index] : $column;
63 for ($rsrc->columns, $column) {
64 if ($_ =~ /^ \Q$alias\E \. ([^\.]+) $ /x) {
68 $colmap->{"$alias.$_"} = $_;
74 # analyze the order_by, and see if it is done over a function/nonexistentcolumn
75 # if this is the case we will need to wrap a subquery since the result of RSC
76 # *must* be a single column select
79 { ! exists $colmap->{$_->[0]} }
80 ( $rsrc->schema->storage->_extract_order_criteria ($orig_attrs->{order_by} ) )
82 # nuke the prefetch before collapsing to sql
83 my $subq_rs = $rs->search_rs;
84 $subq_rs->{attrs}{join} = $subq_rs->_merge_joinpref_attr( $subq_rs->{attrs}{join}, delete $subq_rs->{attrs}{prefetch} );
85 $new_parent_rs = $subq_rs->as_subselect_rs;
88 $new_parent_rs ||= $rs->search_rs;
89 my $new_attrs = $new_parent_rs->{attrs} ||= {};
91 # prefetch causes additional columns to be fetched, but we can not just make a new
92 # rs via the _resolved_attrs trick - we need to retain the separation between
93 # +select/+as and select/as. At the same time we want to preserve any joins that the
94 # prefetch would otherwise generate.
95 $new_attrs->{join} = $rs->_merge_joinpref_attr( $new_attrs->{join}, delete $new_attrs->{prefetch} );
97 # {collapse} would mean a has_many join was injected, which in turn means
98 # we need to group *IF WE CAN* (only if the column in question is unique)
99 if (!$orig_attrs->{group_by} && $orig_attrs->{collapse}) {
101 if ($colmap->{$select} and $rsrc->_identifying_column_set([$colmap->{$select}])) {
102 $new_attrs->{group_by} = [ $select ];
103 delete @{$new_attrs}{qw(distinct _grouped_by_distinct)}; # it is ignored when group_by is present
107 "Attempting to retrieve non-unique column '$column' on a resultset containing "
108 . 'one-to-many joins will return duplicate results.'
116 _parent_resultset => $new_parent_rs
124 =item Arguments: none
126 =item Return Value: \[ $sql, L<@bind_values|DBIx::Class::ResultSet/DBIC BIND VALUES> ]
130 Returns the SQL query and bind vars associated with the invocant.
132 This is generally used as the RHS for a subquery.
136 sub as_query { return shift->_resultset->as_query(@_) }
142 =item Arguments: none
144 =item Return Value: $value
148 Returns the next value of the column in the resultset (or C<undef> if
151 Much like L<DBIx::Class::ResultSet/next> but just returning the
159 # using cursor so we don't inflate anything
160 my ($row) = $self->_resultset->cursor->next;
169 =item Arguments: none
171 =item Return Value: @values
175 Returns all values of the column in the resultset (or C<undef> if
178 Much like L<DBIx::Class::ResultSet/all> but returns values rather
186 # using cursor so we don't inflate anything
187 return map { $_->[0] } $self->_resultset->cursor->all;
194 =item Arguments: none
196 =item Return Value: $self
200 Resets the underlying resultset's cursor, so you can iterate through the
201 elements of the column again.
203 Much like L<DBIx::Class::ResultSet/reset>.
209 $self->_resultset->cursor->reset;
217 =item Arguments: none
219 =item Return Value: $value
223 Resets the underlying resultset and returns the next value of the column in the
224 resultset (or C<undef> if there is none).
226 Much like L<DBIx::Class::ResultSet/first> but just returning the one value.
233 # using cursor so we don't inflate anything
234 $self->_resultset->cursor->reset;
235 my ($row) = $self->_resultset->cursor->next;
244 =item Arguments: none
246 =item Return Value: $value
250 Much like L<DBIx::Class::ResultSet/single> fetches one and only one column
251 value using the cursor directly. If additional rows are present a warning
252 is issued before discarding the cursor.
259 my $attrs = $self->_resultset->_resolved_attrs;
260 my ($row) = $self->_resultset->result_source->storage->select_single(
261 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
271 =item Arguments: none
273 =item Return Value: $lowest_value
277 my $first_year = $year_col->min();
279 Wrapper for ->func. Returns the lowest value of the column in the
280 resultset (or C<undef> if there are none).
285 return shift->func('MIN');
292 =item Arguments: none
294 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
298 my $rs = $year_col->min_rs();
300 Wrapper for ->func_rs for function MIN().
304 sub min_rs { return shift->func_rs('MIN') }
310 =item Arguments: none
312 =item Return Value: $highest_value
316 my $last_year = $year_col->max();
318 Wrapper for ->func. Returns the highest value of the column in the
319 resultset (or C<undef> if there are none).
324 return shift->func('MAX');
331 =item Arguments: none
333 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
337 my $rs = $year_col->max_rs();
339 Wrapper for ->func_rs for function MAX().
343 sub max_rs { return shift->func_rs('MAX') }
349 =item Arguments: none
351 =item Return Value: $sum_of_values
355 my $total = $prices_col->sum();
357 Wrapper for ->func. Returns the sum of all the values in the column of
358 the resultset. Use on varchar-like columns at your own risk.
363 return shift->func('SUM');
370 =item Arguments: none
372 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
376 my $rs = $year_col->sum_rs();
378 Wrapper for ->func_rs for function SUM().
382 sub sum_rs { return shift->func_rs('SUM') }
388 =item Arguments: $function
390 =item Return Value: $function_return_value
394 $rs = $schema->resultset("CD")->search({});
395 $length = $rs->get_column('title')->func('LENGTH');
397 Runs a query using the function on the column and returns the
398 value. Produces the following SQL:
400 SELECT LENGTH( title ) FROM cd me
405 my ($self,$function) = @_;
406 my $cursor = $self->func_rs($function)->cursor;
409 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_WANTARRAY and my $sog = fail_on_internal_wantarray;
410 return map { $_->[ 0 ] } $cursor->all;
413 return ( $cursor->next )[ 0 ];
420 =item Arguments: $function
422 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
426 Creates the resultset that C<func()> uses to run its query.
431 my ($self,$function) = @_;
433 my $rs = $self->{_parent_resultset};
434 my $select = $self->{_select};
437 if ($rs->_resolved_attrs->{group_by}) {
438 $select = $self->{_as};
439 $rs = $rs->as_subselect_rs;
442 $rs->search( undef, {
443 columns => { $self->{_as} => { $function => $select } }
447 =head2 throw_exception
449 See L<DBIx::Class::Schema/throw_exception> for details.
453 sub throw_exception {
456 if (ref $self && $self->{_parent_resultset}) {
457 $self->{_parent_resultset}->throw_exception(@_);
460 DBIx::Class::Exception->throw(@_);
468 # Return Value: $resultset
470 # $year_col->_resultset->next
472 # Returns the underlying resultset. Creates it from the parent resultset if
478 return $self->{_resultset} ||= do {
480 my $select = $self->{_select};
482 if ($self->{_parent_resultset}{attrs}{distinct}) {
483 my $alias = $self->{_parent_resultset}->current_source_alias;
484 my $rsrc = $self->{_parent_resultset}->result_source;
485 my %cols = map { $_ => 1, "$alias.$_" => 1 } $rsrc->columns;
487 unless( $cols{$select} ) {
489 'Use of distinct => 1 while selecting anything other than a column '
490 . 'declared on the primary ResultSource is deprecated (you selected '
491 . "'$self->{_as}') - please supply an explicit group_by instead"
494 # collapse the selector to a literal so that it survives the distinct parse
495 # if it turns out to be an aggregate - at least the user will get a proper exception
496 # instead of silent drop of the group_by altogether
497 $select = \[ $rsrc->storage->sql_maker->_recurse_fields($select) ];
501 $self->{_parent_resultset}->search(undef, {
502 columns => { $self->{_as} => $select }
507 =head1 FURTHER QUESTIONS?
509 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
511 =head1 COPYRIGHT AND LICENSE
513 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
514 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
515 redistribute it and/or modify it under the same terms as the
516 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.