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.'
113 # collapse the selector to a literal so that it survives a possible distinct parse
114 # if it turns out to be an aggregate - at least the user will get a proper exception
115 # instead of silent drop of the group_by altogether
117 _select => \ $rsrc->storage->sql_maker->_recurse_fields($select),
119 _parent_resultset => $new_parent_rs }, $class;
127 =item Arguments: none
129 =item Return Value: \[ $sql, L<@bind_values|DBIx::Class::ResultSet/DBIC BIND VALUES> ]
133 Returns the SQL query and bind vars associated with the invocant.
135 This is generally used as the RHS for a subquery.
139 sub as_query { return shift->_resultset->as_query(@_) }
145 =item Arguments: none
147 =item Return Value: $value
151 Returns the next value of the column in the resultset (or C<undef> if
154 Much like L<DBIx::Class::ResultSet/next> but just returning the
162 # using cursor so we don't inflate anything
163 my ($row) = $self->_resultset->cursor->next;
172 =item Arguments: none
174 =item Return Value: @values
178 Returns all values of the column in the resultset (or C<undef> if
181 Much like L<DBIx::Class::ResultSet/all> but returns values rather
189 # using cursor so we don't inflate anything
190 return map { $_->[0] } $self->_resultset->cursor->all;
197 =item Arguments: none
199 =item Return Value: $self
203 Resets the underlying resultset's cursor, so you can iterate through the
204 elements of the column again.
206 Much like L<DBIx::Class::ResultSet/reset>.
212 $self->_resultset->cursor->reset;
220 =item Arguments: none
222 =item Return Value: $value
226 Resets the underlying resultset and returns the next value of the column in the
227 resultset (or C<undef> if there is none).
229 Much like L<DBIx::Class::ResultSet/first> but just returning the one value.
236 # using cursor so we don't inflate anything
237 $self->_resultset->cursor->reset;
238 my ($row) = $self->_resultset->cursor->next;
247 =item Arguments: none
249 =item Return Value: $value
253 Much like L<DBIx::Class::ResultSet/single> fetches one and only one column
254 value using the cursor directly. If additional rows are present a warning
255 is issued before discarding the cursor.
262 my $attrs = $self->_resultset->_resolved_attrs;
263 my ($row) = $self->_resultset->result_source->storage->select_single(
264 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
274 =item Arguments: none
276 =item Return Value: $lowest_value
280 my $first_year = $year_col->min();
282 Wrapper for ->func. Returns the lowest value of the column in the
283 resultset (or C<undef> if there are none).
288 return shift->func('MIN');
295 =item Arguments: none
297 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
301 my $rs = $year_col->min_rs();
303 Wrapper for ->func_rs for function MIN().
307 sub min_rs { return shift->func_rs('MIN') }
313 =item Arguments: none
315 =item Return Value: $highest_value
319 my $last_year = $year_col->max();
321 Wrapper for ->func. Returns the highest value of the column in the
322 resultset (or C<undef> if there are none).
327 return shift->func('MAX');
334 =item Arguments: none
336 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
340 my $rs = $year_col->max_rs();
342 Wrapper for ->func_rs for function MAX().
346 sub max_rs { return shift->func_rs('MAX') }
352 =item Arguments: none
354 =item Return Value: $sum_of_values
358 my $total = $prices_col->sum();
360 Wrapper for ->func. Returns the sum of all the values in the column of
361 the resultset. Use on varchar-like columns at your own risk.
366 return shift->func('SUM');
373 =item Arguments: none
375 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
379 my $rs = $year_col->sum_rs();
381 Wrapper for ->func_rs for function SUM().
385 sub sum_rs { return shift->func_rs('SUM') }
391 =item Arguments: $function
393 =item Return Value: $function_return_value
397 $rs = $schema->resultset("CD")->search({});
398 $length = $rs->get_column('title')->func('LENGTH');
400 Runs a query using the function on the column and returns the
401 value. Produces the following SQL:
403 SELECT LENGTH( title ) FROM cd me
408 my ($self,$function) = @_;
409 my $cursor = $self->func_rs($function)->cursor;
412 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_WANTARRAY and my $sog = fail_on_internal_wantarray($self);
413 return map { $_->[ 0 ] } $cursor->all;
416 return ( $cursor->next )[ 0 ];
423 =item Arguments: $function
425 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
429 Creates the resultset that C<func()> uses to run its query.
434 my ($self,$function) = @_;
436 my $rs = $self->{_parent_resultset};
437 my $select = $self->{_select};
440 if ($rs->_resolved_attrs->{group_by}) {
441 $select = $self->{_as};
442 $rs = $rs->as_subselect_rs;
445 $rs->search( undef, {
446 columns => { $self->{_as} => { $function => $select } }
450 =head2 throw_exception
452 See L<DBIx::Class::Schema/throw_exception> for details.
456 sub throw_exception {
459 if (ref $self && $self->{_parent_resultset}) {
460 $self->{_parent_resultset}->throw_exception(@_);
463 DBIx::Class::Exception->throw(@_);
471 # Return Value: $resultset
473 # $year_col->_resultset->next
475 # Returns the underlying resultset. Creates it from the parent resultset if
481 return $self->{_resultset} ||= $self->{_parent_resultset}->search(undef,
483 select => [$self->{_select}],
491 =head1 AUTHOR AND CONTRIBUTORS
493 See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class
497 You may distribute this code under the same terms as Perl itself.