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 # prefetch causes additional columns to be fetched, but we can not just make a new
87 # rs via the _resolved_attrs trick - we need to retain the separation between
88 # +select/+as and select/as. At the same time we want to preserve any joins that the
89 # prefetch would otherwise generate.
90 $new_attrs->{join} = $rs->_merge_attr( $new_attrs->{join}, delete $new_attrs->{prefetch} );
92 # {collapse} would mean a has_many join was injected, which in turn means
93 # we need to group *IF WE CAN* (only if the column in question is unique)
94 if (!$new_attrs->{group_by} && keys %{$orig_attrs->{collapse}}) {
96 # scan for a constraint that would contain our column only - that'd be proof
98 my $constraints = { $rs->result_source->unique_constraints };
99 for my $constraint_columns ( values %$constraints ) {
101 next unless @$constraint_columns == 1;
103 my $col = $constraint_columns->[0];
104 my $fqcol = join ('.', $new_attrs->{alias}, $col);
106 if ($col eq $select or $fqcol eq $select) {
107 $new_attrs->{group_by} = [ $select ];
108 delete $new_attrs->{distinct}; # it is ignored when group_by is present
113 if (!$new_attrs->{group_by}) {
115 "Attempting to retrieve non-unique column '$column' on a resultset containing "
116 . 'one-to-many joins will return duplicate results.'
121 my $new = bless { _select => $select, _as => $column, _parent_resultset => $new_parent_rs }, $class;
129 =item Arguments: none
131 =item Return Value: \[ $sql, @bind ]
135 Returns the SQL query and bind vars associated with the invocant.
137 This is generally used as the RHS for a subquery.
141 sub as_query { return shift->_resultset->as_query(@_) }
147 =item Arguments: none
149 =item Return Value: $value
153 Returns the next value of the column in the resultset (or C<undef> if
156 Much like L<DBIx::Class::ResultSet/next> but just returning the
164 # using cursor so we don't inflate anything
165 my ($row) = $self->_resultset->cursor->next;
174 =item Arguments: none
176 =item Return Value: @values
180 Returns all values of the column in the resultset (or C<undef> if
183 Much like L<DBIx::Class::ResultSet/all> but returns values rather
191 # using cursor so we don't inflate anything
192 return map { $_->[0] } $self->_resultset->cursor->all;
199 =item Arguments: none
201 =item Return Value: $self
205 Resets the underlying resultset's cursor, so you can iterate through the
206 elements of the column again.
208 Much like L<DBIx::Class::ResultSet/reset>.
214 $self->_resultset->cursor->reset;
222 =item Arguments: none
224 =item Return Value: $value
228 Resets the underlying resultset and returns the next value of the column in the
229 resultset (or C<undef> if there is none).
231 Much like L<DBIx::Class::ResultSet/first> but just returning the one value.
238 # using cursor so we don't inflate anything
239 $self->_resultset->cursor->reset;
240 my ($row) = $self->_resultset->cursor->next;
249 =item Arguments: none
251 =item Return Value: $value
255 Much like L<DBIx::Class::ResultSet/single> fetches one and only one column
256 value using the cursor directly. If additional rows are present a warning
257 is issued before discarding the cursor.
264 my $attrs = $self->_resultset->_resolved_attrs;
265 my ($row) = $self->_resultset->result_source->storage->select_single(
266 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
276 =item Arguments: none
278 =item Return Value: $lowest_value
282 my $first_year = $year_col->min();
284 Wrapper for ->func. Returns the lowest value of the column in the
285 resultset (or C<undef> if there are none).
290 return shift->func('MIN');
297 =item Arguments: none
299 =item Return Value: $resultset
303 my $rs = $year_col->min_rs();
305 Wrapper for ->func_rs for function MIN().
309 sub min_rs { return shift->func_rs('MIN') }
315 =item Arguments: none
317 =item Return Value: $highest_value
321 my $last_year = $year_col->max();
323 Wrapper for ->func. Returns the highest value of the column in the
324 resultset (or C<undef> if there are none).
329 return shift->func('MAX');
336 =item Arguments: none
338 =item Return Value: $resultset
342 my $rs = $year_col->max_rs();
344 Wrapper for ->func_rs for function MAX().
348 sub max_rs { return shift->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 return shift->func('SUM');
375 =item Arguments: none
377 =item Return Value: $resultset
381 my $rs = $year_col->sum_rs();
383 Wrapper for ->func_rs for function SUM().
387 sub sum_rs { return shift->func_rs('SUM') }
393 =item Arguments: $function
395 =item Return Value: $function_return_value
399 $rs = $schema->resultset("CD")->search({});
400 $length = $rs->get_column('title')->func('LENGTH');
402 Runs a query using the function on the column and returns the
403 value. Produces the following SQL:
405 SELECT LENGTH( title ) FROM cd me
410 my ($self,$function) = @_;
411 my $cursor = $self->func_rs($function)->cursor;
414 return map { $_->[ 0 ] } $cursor->all;
417 return ( $cursor->next )[ 0 ];
424 =item Arguments: $function
426 =item Return Value: $resultset
430 Creates the resultset that C<func()> uses to run its query.
435 my ($self,$function) = @_;
436 return $self->{_parent_resultset}->search(
438 select => {$function => $self->{_select}},
439 as => [$self->{_as}],
444 =head2 throw_exception
446 See L<DBIx::Class::Schema/throw_exception> for details.
450 sub throw_exception {
453 if (ref $self && $self->{_parent_resultset}) {
454 $self->{_parent_resultset}->throw_exception(@_);
457 DBIx::Class::Exception->throw(@_);
465 # Return Value: $resultset
467 # $year_col->_resultset->next
469 # Returns the underlying resultset. Creates it from the parent resultset if
475 return $self->{_resultset} ||= $self->{_parent_resultset}->search(undef,
477 select => [$self->{_select}],
487 Luke Saunders <luke.saunders@gmail.com>
493 You may distribute this code under the same terms as Perl itself.