1 package DBIx::Class::ResultSetColumn;
6 use base 'DBIx::Class';
8 use DBIx::Class::Exception;
9 use Carp::Clan qw/^DBIx::Class/;
12 # not importing first() as it will clash with our own method
17 DBIx::Class::ResultSetColumn - helpful methods for messing
18 with a single column of the resultset
22 $rs = $schema->resultset('CD')->search({ artist => 'Tool' });
23 $rs_column = $rs->get_column('year');
24 $max_year = $rs_column->max; #returns latest year
28 A convenience class used to perform operations on a specific column of
37 my $obj = DBIx::Class::ResultSetColumn->new($rs, $column);
39 Creates a new resultset column object from the resultset and column
40 passed as params. Used internally by L<DBIx::Class::ResultSet/get_column>.
45 my ($class, $rs, $column) = @_;
46 $class = ref $class if ref $class;
48 $rs->throw_exception('column must be supplied') unless $column;
50 my $orig_attrs = $rs->_resolved_attrs;
51 my $alias = $rs->current_source_alias;
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 # analyze the order_by, and see if it is done over a function/nonexistentcolumn
64 # if this is the case we will need to wrap a subquery since the result of RSC
65 # *must* be a single column select
67 { $_ => 1, ($_ =~ /\./) ? () : ( "$alias.$_" => 1 ) }
68 ($rs->result_source->columns, $column)
72 { ! $collist{$_->[0]} }
73 ( $rs->result_source->schema->storage->_extract_order_criteria ($orig_attrs->{order_by} ) )
75 # nuke the prefetch before collapsing to sql
76 my $subq_rs = $rs->search;
77 $subq_rs->{attrs}{join} = $subq_rs->_merge_joinpref_attr( $subq_rs->{attrs}{join}, delete $subq_rs->{attrs}{prefetch} );
78 $new_parent_rs = $subq_rs->as_subselect_rs;
81 $new_parent_rs ||= $rs->search_rs;
82 my $new_attrs = $new_parent_rs->{attrs} ||= {};
84 # prefetch causes additional columns to be fetched, but we can not just make a new
85 # rs via the _resolved_attrs trick - we need to retain the separation between
86 # +select/+as and select/as. At the same time we want to preserve any joins that the
87 # prefetch would otherwise generate.
88 $new_attrs->{join} = $rs->_merge_joinpref_attr( $new_attrs->{join}, delete $new_attrs->{prefetch} );
90 # {collapse} would mean a has_many join was injected, which in turn means
91 # we need to group *IF WE CAN* (only if the column in question is unique)
92 if (!$orig_attrs->{group_by} && keys %{$orig_attrs->{collapse}}) {
94 # scan for a constraint that would contain our column only - that'd be proof
96 my $constraints = { $rs->result_source->unique_constraints };
97 for my $constraint_columns ( values %$constraints ) {
99 next unless @$constraint_columns == 1;
101 my $col = $constraint_columns->[0];
102 my $fqcol = join ('.', $new_attrs->{alias}, $col);
104 if ($col eq $select or $fqcol eq $select) {
105 $new_attrs->{group_by} = [ $select ];
106 delete $new_attrs->{distinct}; # it is ignored when group_by is present
111 if (!$new_attrs->{group_by}) {
113 "Attempting to retrieve non-unique column '$column' on a resultset containing "
114 . 'one-to-many joins will return duplicate results.'
119 my $new = bless { _select => $select, _as => $column, _parent_resultset => $new_parent_rs }, $class;
127 =item Arguments: none
129 =item Return Value: \[ $sql, @bind ]
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: $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: $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: $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 return map { $_->[ 0 ] } $cursor->all;
415 return ( $cursor->next )[ 0 ];
422 =item Arguments: $function
424 =item Return Value: $resultset
428 Creates the resultset that C<func()> uses to run its query.
433 my ($self,$function) = @_;
434 return $self->{_parent_resultset}->search(
436 select => {$function => $self->{_select}},
437 as => [$self->{_as}],
442 =head2 throw_exception
444 See L<DBIx::Class::Schema/throw_exception> for details.
448 sub throw_exception {
451 if (ref $self && $self->{_parent_resultset}) {
452 $self->{_parent_resultset}->throw_exception(@_);
455 DBIx::Class::Exception->throw(@_);
463 # Return Value: $resultset
465 # $year_col->_resultset->next
467 # Returns the underlying resultset. Creates it from the parent resultset if
473 return $self->{_resultset} ||= $self->{_parent_resultset}->search(undef,
475 select => [$self->{_select}],
485 Luke Saunders <luke.saunders@gmail.com>
491 You may distribute this code under the same terms as Perl itself.