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;
48 my $new_parent_rs = $rs->search_rs;
50 # prefetch causes additional columns to be fetched, but we can not just make a new
51 # rs via the _resolved_attrs trick - we need to retain the separation between
52 # +select/+as and select/as. At the same time we want to preserve any joins that the
53 # prefetch would otherwise generate.
55 my $new_attrs = $new_parent_rs->{attrs} ||= {};
56 $new_attrs->{join} = $rs->_merge_attr( delete $new_attrs->{join}, delete $new_attrs->{prefetch} );
58 # If $column can be found in the 'as' list of the parent resultset, use the
59 # corresponding element of its 'select' list (to keep any custom column
60 # definition set up with 'select' or '+select' attrs), otherwise use $column
61 # (to create a new column definition on-the-fly).
63 my $as_list = $orig_attrs->{as} || [];
64 my $select_list = $orig_attrs->{select} || [];
65 my $as_index = List::Util::first { ($as_list->[$_] || "") eq $column } 0..$#$as_list;
66 my $select = defined $as_index ? $select_list->[$as_index] : $column;
68 # {collapse} would mean a has_many join was injected, which in turn means
69 # we need to group *IF WE CAN* (only if the column in question is unique)
70 if (!$new_attrs->{group_by} && keys %{$orig_attrs->{collapse}}) {
72 # scan for a constraint that would contain our column only - that'd be proof
74 my $constraints = { $rs->result_source->unique_constraints };
75 for my $constraint_columns ( values %$constraints ) {
77 next unless @$constraint_columns == 1;
79 my $col = $constraint_columns->[0];
80 my $fqcol = join ('.', $new_attrs->{alias}, $col);
82 if ($col eq $select or $fqcol eq $select) {
83 $new_attrs->{group_by} = [ $select ];
84 delete $new_attrs->{distinct}; # it is ignored when group_by is present
89 if (!$new_attrs->{group_by}) {
91 "Attempting to retrieve non-unique column '$column' on a resultset containing "
92 . 'one-to-many joins will return duplicate results.'
97 my $new = bless { _select => $select, _as => $column, _parent_resultset => $new_parent_rs }, $class;
101 =head2 as_query (EXPERIMENTAL)
105 =item Arguments: none
107 =item Return Value: \[ $sql, @bind ]
111 Returns the SQL query and bind vars associated with the invocant.
113 This is generally used as the RHS for a subquery.
115 B<NOTE>: This feature is still experimental.
119 sub as_query { return shift->_resultset->as_query(@_) }
125 =item Arguments: none
127 =item Return Value: $value
131 Returns the next value of the column in the resultset (or C<undef> if
134 Much like L<DBIx::Class::ResultSet/next> but just returning the
142 # using cursor so we don't inflate anything
143 my ($row) = $self->_resultset->cursor->next;
152 =item Arguments: none
154 =item Return Value: @values
158 Returns all values of the column in the resultset (or C<undef> if
161 Much like L<DBIx::Class::ResultSet/all> but returns values rather
169 # using cursor so we don't inflate anything
170 return map { $_->[0] } $self->_resultset->cursor->all;
177 =item Arguments: none
179 =item Return Value: $self
183 Resets the underlying resultset's cursor, so you can iterate through the
184 elements of the column again.
186 Much like L<DBIx::Class::ResultSet/reset>.
192 $self->_resultset->cursor->reset;
200 =item Arguments: none
202 =item Return Value: $value
206 Resets the underlying resultset and returns the next value of the column in the
207 resultset (or C<undef> if there is none).
209 Much like L<DBIx::Class::ResultSet/first> but just returning the one value.
216 # using cursor so we don't inflate anything
217 $self->_resultset->cursor->reset;
218 my ($row) = $self->_resultset->cursor->next;
227 =item Arguments: none
229 =item Return Value: $value
233 Much like L<DBIx::Class::ResultSet/single> fetches one and only one column
234 value using the cursor directly. If additional rows are present a warning
235 is issued before discarding the cursor.
242 my $attrs = $self->_resultset->_resolved_attrs;
243 my ($row) = $self->_resultset->result_source->storage->select_single(
244 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
254 =item Arguments: none
256 =item Return Value: $lowest_value
260 my $first_year = $year_col->min();
262 Wrapper for ->func. Returns the lowest value of the column in the
263 resultset (or C<undef> if there are none).
268 return shift->func('MIN');
275 =item Arguments: none
277 =item Return Value: $resultset
281 my $rs = $year_col->min_rs();
283 Wrapper for ->func_rs for function MIN().
287 sub min_rs { return shift->func_rs('MIN') }
293 =item Arguments: none
295 =item Return Value: $highest_value
299 my $last_year = $year_col->max();
301 Wrapper for ->func. Returns the highest value of the column in the
302 resultset (or C<undef> if there are none).
307 return shift->func('MAX');
314 =item Arguments: none
316 =item Return Value: $resultset
320 my $rs = $year_col->max_rs();
322 Wrapper for ->func_rs for function MAX().
326 sub max_rs { return shift->func_rs('MAX') }
332 =item Arguments: none
334 =item Return Value: $sum_of_values
338 my $total = $prices_col->sum();
340 Wrapper for ->func. Returns the sum of all the values in the column of
341 the resultset. Use on varchar-like columns at your own risk.
346 return shift->func('SUM');
353 =item Arguments: none
355 =item Return Value: $resultset
359 my $rs = $year_col->sum_rs();
361 Wrapper for ->func_rs for function SUM().
365 sub sum_rs { return shift->func_rs('SUM') }
371 =item Arguments: $function
373 =item Return Value: $function_return_value
377 $rs = $schema->resultset("CD")->search({});
378 $length = $rs->get_column('title')->func('LENGTH');
380 Runs a query using the function on the column and returns the
381 value. Produces the following SQL:
383 SELECT LENGTH( title ) FROM cd me
388 my ($self,$function) = @_;
389 my $cursor = $self->func_rs($function)->cursor;
392 return map { $_->[ 0 ] } $cursor->all;
395 return ( $cursor->next )[ 0 ];
402 =item Arguments: $function
404 =item Return Value: $resultset
408 Creates the resultset that C<func()> uses to run its query.
413 my ($self,$function) = @_;
414 return $self->{_parent_resultset}->search(
416 select => {$function => $self->{_select}},
417 as => [$self->{_as}],
422 =head2 throw_exception
424 See L<DBIx::Class::Schema/throw_exception> for details.
428 sub throw_exception {
431 if (ref $self && $self->{_parent_resultset}) {
432 $self->{_parent_resultset}->throw_exception(@_);
435 DBIx::Class::Exception->throw(@_);
443 # Return Value: $resultset
445 # $year_col->_resultset->next
447 # Returns the underlying resultset. Creates it from the parent resultset if
453 return $self->{_resultset} ||= $self->{_parent_resultset}->search(undef,
455 select => [$self->{_select}],
465 Luke Saunders <luke.saunders@gmail.com>
471 You may distribute this code under the same terms as Perl itself.