1 package DBIx::Class::ResultSetColumn;
6 use base 'DBIx::Class';
8 use Carp::Clan qw/^DBIx::Class/;
9 use DBIx::Class::Exception;
14 DBIx::Class::ResultSetColumn - helpful methods for messing
15 with a single column of the resultset
19 $rs = $schema->resultset('CD')->search({ artist => 'Tool' });
20 $rs_column = $rs->get_column('year');
21 $max_year = $rs_column->max; #returns latest year
25 A convenience class used to perform operations on a specific column of
34 my $obj = DBIx::Class::ResultSetColumn->new($rs, $column);
36 Creates a new resultset column object from the resultset and column
37 passed as params. Used internally by L<DBIx::Class::ResultSet/get_column>.
42 my ($class, $rs, $column) = @_;
43 $class = ref $class if ref $class;
45 $rs->throw_exception('column must be supplied') unless $column;
47 my $orig_attrs = $rs->_resolved_attrs;
49 # If $column can be found in the 'as' list of the parent resultset, use the
50 # corresponding element of its 'select' list (to keep any custom column
51 # definition set up with 'select' or '+select' attrs), otherwise use $column
52 # (to create a new column definition on-the-fly).
53 my $as_list = $orig_attrs->{as} || [];
54 my $select_list = $orig_attrs->{select} || [];
55 my $as_index = List::Util::first { ($as_list->[$_] || "") eq $column } 0..$#$as_list;
56 my $select = defined $as_index ? $select_list->[$as_index] : $column;
59 # analyze the order_by, and see if it is done over a function/nonexistentcolumn
60 # if this is the case we will need to wrap a subquery since the result of RSC
61 # *must* be a single column select
62 my %collist = map { $_ => 1 } ($rs->result_source->columns, $column);
66 ( $rs->result_source->schema->storage->_parse_order_by ($orig_attrs->{order_by} ) )
68 my $alias = $rs->current_source_alias;
69 # nuke the prefetch before collapsing to sql
70 my $subq_rs = $rs->search;
71 $subq_rs->{attrs}{join} = $subq_rs->_merge_attr( $subq_rs->{attrs}{join}, delete $subq_rs->{attrs}{prefetch} );
73 $new_parent_rs = $rs->result_source->resultset->search ( {}, {
76 $alias => $subq_rs->as_query,
78 -source_handle => $rs->result_source->handle,
83 $new_parent_rs ||= $rs->search_rs;
84 my $new_attrs = $new_parent_rs->{attrs} ||= {};
86 # FIXME - this should go away when the chaining branch is merged
87 # since what we do is actually chain to the original resultset, we need to throw
88 # away all selectors (otherwise they'll chain)
89 delete $new_attrs->{$_} for (qw/columns +columns select +select as +as cols include_columns/);
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_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 (!$new_attrs->{group_by} && keys %{$orig_attrs->{collapse}}) {
101 # scan for a constraint that would contain our column only - that'd be proof
102 # enough it is unique
103 my $constraints = { $rs->result_source->unique_constraints };
104 for my $constraint_columns ( values %$constraints ) {
106 next unless @$constraint_columns == 1;
108 my $col = $constraint_columns->[0];
109 my $fqcol = join ('.', $new_attrs->{alias}, $col);
111 if ($col eq $select or $fqcol eq $select) {
112 $new_attrs->{group_by} = [ $select ];
113 delete $new_attrs->{distinct}; # it is ignored when group_by is present
118 if (!$new_attrs->{group_by}) {
120 "Attempting to retrieve non-unique column '$column' on a resultset containing "
121 . 'one-to-many joins will return duplicate results.'
126 my $new = bless { _select => $select, _as => $column, _parent_resultset => $new_parent_rs }, $class;
134 =item Arguments: none
136 =item Return Value: \[ $sql, @bind ]
140 Returns the SQL query and bind vars associated with the invocant.
142 This is generally used as the RHS for a subquery.
146 sub as_query { return shift->_resultset->as_query(@_) }
152 =item Arguments: none
154 =item Return Value: $value
158 Returns the next value of the column in the resultset (or C<undef> if
161 Much like L<DBIx::Class::ResultSet/next> but just returning the
169 # using cursor so we don't inflate anything
170 my ($row) = $self->_resultset->cursor->next;
179 =item Arguments: none
181 =item Return Value: @values
185 Returns all values of the column in the resultset (or C<undef> if
188 Much like L<DBIx::Class::ResultSet/all> but returns values rather
196 # using cursor so we don't inflate anything
197 return map { $_->[0] } $self->_resultset->cursor->all;
204 =item Arguments: none
206 =item Return Value: $self
210 Resets the underlying resultset's cursor, so you can iterate through the
211 elements of the column again.
213 Much like L<DBIx::Class::ResultSet/reset>.
219 $self->_resultset->cursor->reset;
227 =item Arguments: none
229 =item Return Value: $value
233 Resets the underlying resultset and returns the next value of the column in the
234 resultset (or C<undef> if there is none).
236 Much like L<DBIx::Class::ResultSet/first> but just returning the one value.
243 # using cursor so we don't inflate anything
244 $self->_resultset->cursor->reset;
245 my ($row) = $self->_resultset->cursor->next;
254 =item Arguments: none
256 =item Return Value: $value
260 Much like L<DBIx::Class::ResultSet/single> fetches one and only one column
261 value using the cursor directly. If additional rows are present a warning
262 is issued before discarding the cursor.
269 my $attrs = $self->_resultset->_resolved_attrs;
270 my ($row) = $self->_resultset->result_source->storage->select_single(
271 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
281 =item Arguments: none
283 =item Return Value: $lowest_value
287 my $first_year = $year_col->min();
289 Wrapper for ->func. Returns the lowest value of the column in the
290 resultset (or C<undef> if there are none).
295 return shift->func('MIN');
302 =item Arguments: none
304 =item Return Value: $resultset
308 my $rs = $year_col->min_rs();
310 Wrapper for ->func_rs for function MIN().
314 sub min_rs { return shift->func_rs('MIN') }
320 =item Arguments: none
322 =item Return Value: $highest_value
326 my $last_year = $year_col->max();
328 Wrapper for ->func. Returns the highest value of the column in the
329 resultset (or C<undef> if there are none).
334 return shift->func('MAX');
341 =item Arguments: none
343 =item Return Value: $resultset
347 my $rs = $year_col->max_rs();
349 Wrapper for ->func_rs for function MAX().
353 sub max_rs { return shift->func_rs('MAX') }
359 =item Arguments: none
361 =item Return Value: $sum_of_values
365 my $total = $prices_col->sum();
367 Wrapper for ->func. Returns the sum of all the values in the column of
368 the resultset. Use on varchar-like columns at your own risk.
373 return shift->func('SUM');
380 =item Arguments: none
382 =item Return Value: $resultset
386 my $rs = $year_col->sum_rs();
388 Wrapper for ->func_rs for function SUM().
392 sub sum_rs { return shift->func_rs('SUM') }
398 =item Arguments: $function
400 =item Return Value: $function_return_value
404 $rs = $schema->resultset("CD")->search({});
405 $length = $rs->get_column('title')->func('LENGTH');
407 Runs a query using the function on the column and returns the
408 value. Produces the following SQL:
410 SELECT LENGTH( title ) FROM cd me
415 my ($self,$function) = @_;
416 my $cursor = $self->func_rs($function)->cursor;
419 return map { $_->[ 0 ] } $cursor->all;
422 return ( $cursor->next )[ 0 ];
429 =item Arguments: $function
431 =item Return Value: $resultset
435 Creates the resultset that C<func()> uses to run its query.
440 my ($self,$function) = @_;
441 return $self->{_parent_resultset}->search(
443 select => {$function => $self->{_select}},
444 as => [$self->{_as}],
449 =head2 throw_exception
451 See L<DBIx::Class::Schema/throw_exception> for details.
455 sub throw_exception {
458 if (ref $self && $self->{_parent_resultset}) {
459 $self->{_parent_resultset}->throw_exception(@_);
462 DBIx::Class::Exception->throw(@_);
470 # Return Value: $resultset
472 # $year_col->_resultset->next
474 # Returns the underlying resultset. Creates it from the parent resultset if
480 return $self->{_resultset} ||= $self->{_parent_resultset}->search(undef,
482 select => [$self->{_select}],
492 Luke Saunders <luke.saunders@gmail.com>
498 You may distribute this code under the same terms as Perl itself.