1 package DBIx::Class::ResultSetColumn;
6 use base 'DBIx::Class';
8 use DBIx::Class::Exception;
10 # not importing first() as it will clash with our own method
15 DBIx::Class::ResultSetColumn - helpful methods for messing
16 with a single column of the resultset
20 $rs = $schema->resultset('CD')->search({ artist => 'Tool' });
21 $rs_column = $rs->get_column('year');
22 $max_year = $rs_column->max; #returns latest year
26 A convenience class used to perform operations on a specific column of
35 my $obj = DBIx::Class::ResultSetColumn->new($rs, $column);
37 Creates a new resultset column object from the resultset and column
38 passed as params. Used internally by L<DBIx::Class::ResultSet/get_column>.
43 my ($class, $rs, $column) = @_;
44 $class = ref $class if ref $class;
46 $rs->throw_exception('column must be supplied') unless $column;
48 my $orig_attrs = $rs->_resolved_attrs;
49 my $alias = $rs->current_source_alias;
51 # If $column can be found in the 'as' list of the parent resultset, use the
52 # corresponding element of its 'select' list (to keep any custom column
53 # definition set up with 'select' or '+select' attrs), otherwise use $column
54 # (to create a new column definition on-the-fly).
55 my $as_list = $orig_attrs->{as} || [];
56 my $select_list = $orig_attrs->{select} || [];
57 my $as_index = List::Util::first { ($as_list->[$_] || "") eq $column } 0..$#$as_list;
58 my $select = defined $as_index ? $select_list->[$as_index] : $column;
61 # analyze the order_by, and see if it is done over a function/nonexistentcolumn
62 # if this is the case we will need to wrap a subquery since the result of RSC
63 # *must* be a single column select
65 { $_ => 1, ($_ =~ /\./) ? () : ( "$alias.$_" => 1 ) }
66 ($rs->result_source->columns, $column)
70 { ! $collist{$_->[0]} }
71 ( $rs->result_source->schema->storage->_extract_order_criteria ($orig_attrs->{order_by} ) )
73 # nuke the prefetch before collapsing to sql
74 my $subq_rs = $rs->search;
75 $subq_rs->{attrs}{join} = $subq_rs->_merge_joinpref_attr( $subq_rs->{attrs}{join}, delete $subq_rs->{attrs}{prefetch} );
76 $new_parent_rs = $subq_rs->as_subselect_rs;
79 $new_parent_rs ||= $rs->search_rs;
80 my $new_attrs = $new_parent_rs->{attrs} ||= {};
82 # prefetch causes additional columns to be fetched, but we can not just make a new
83 # rs via the _resolved_attrs trick - we need to retain the separation between
84 # +select/+as and select/as. At the same time we want to preserve any joins that the
85 # prefetch would otherwise generate.
86 $new_attrs->{join} = $rs->_merge_joinpref_attr( $new_attrs->{join}, delete $new_attrs->{prefetch} );
88 # {collapse} would mean a has_many join was injected, which in turn means
89 # we need to group *IF WE CAN* (only if the column in question is unique)
90 if (!$orig_attrs->{group_by} && keys %{$orig_attrs->{collapse}}) {
92 # scan for a constraint that would contain our column only - that'd be proof
94 my $constraints = { $rs->result_source->unique_constraints };
95 for my $constraint_columns ( values %$constraints ) {
97 next unless @$constraint_columns == 1;
99 my $col = $constraint_columns->[0];
100 my $fqcol = join ('.', $new_attrs->{alias}, $col);
102 if ($col eq $select or $fqcol eq $select) {
103 $new_attrs->{group_by} = [ $select ];
104 delete $new_attrs->{distinct}; # it is ignored when group_by is present
109 if (!$new_attrs->{group_by}) {
111 "Attempting to retrieve non-unique column '$column' on a resultset containing "
112 . 'one-to-many joins will return duplicate results.'
117 my $new = bless { _select => $select, _as => $column, _parent_resultset => $new_parent_rs }, $class;
125 =item Arguments: none
127 =item Return Value: \[ $sql, @bind ]
131 Returns the SQL query and bind vars associated with the invocant.
133 This is generally used as the RHS for a subquery.
137 sub as_query { return shift->_resultset->as_query(@_) }
143 =item Arguments: none
145 =item Return Value: $value
149 Returns the next value of the column in the resultset (or C<undef> if
152 Much like L<DBIx::Class::ResultSet/next> but just returning the
160 # using cursor so we don't inflate anything
161 my ($row) = $self->_resultset->cursor->next;
170 =item Arguments: none
172 =item Return Value: @values
176 Returns all values of the column in the resultset (or C<undef> if
179 Much like L<DBIx::Class::ResultSet/all> but returns values rather
187 # using cursor so we don't inflate anything
188 return map { $_->[0] } $self->_resultset->cursor->all;
195 =item Arguments: none
197 =item Return Value: $self
201 Resets the underlying resultset's cursor, so you can iterate through the
202 elements of the column again.
204 Much like L<DBIx::Class::ResultSet/reset>.
210 $self->_resultset->cursor->reset;
218 =item Arguments: none
220 =item Return Value: $value
224 Resets the underlying resultset and returns the next value of the column in the
225 resultset (or C<undef> if there is none).
227 Much like L<DBIx::Class::ResultSet/first> but just returning the one value.
234 # using cursor so we don't inflate anything
235 $self->_resultset->cursor->reset;
236 my ($row) = $self->_resultset->cursor->next;
245 =item Arguments: none
247 =item Return Value: $value
251 Much like L<DBIx::Class::ResultSet/single> fetches one and only one column
252 value using the cursor directly. If additional rows are present a warning
253 is issued before discarding the cursor.
260 my $attrs = $self->_resultset->_resolved_attrs;
261 my ($row) = $self->_resultset->result_source->storage->select_single(
262 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
272 =item Arguments: none
274 =item Return Value: $lowest_value
278 my $first_year = $year_col->min();
280 Wrapper for ->func. Returns the lowest value of the column in the
281 resultset (or C<undef> if there are none).
286 return shift->func('MIN');
293 =item Arguments: none
295 =item Return Value: $resultset
299 my $rs = $year_col->min_rs();
301 Wrapper for ->func_rs for function MIN().
305 sub min_rs { return shift->func_rs('MIN') }
311 =item Arguments: none
313 =item Return Value: $highest_value
317 my $last_year = $year_col->max();
319 Wrapper for ->func. Returns the highest value of the column in the
320 resultset (or C<undef> if there are none).
325 return shift->func('MAX');
332 =item Arguments: none
334 =item Return Value: $resultset
338 my $rs = $year_col->max_rs();
340 Wrapper for ->func_rs for function MAX().
344 sub max_rs { return shift->func_rs('MAX') }
350 =item Arguments: none
352 =item Return Value: $sum_of_values
356 my $total = $prices_col->sum();
358 Wrapper for ->func. Returns the sum of all the values in the column of
359 the resultset. Use on varchar-like columns at your own risk.
364 return shift->func('SUM');
371 =item Arguments: none
373 =item Return Value: $resultset
377 my $rs = $year_col->sum_rs();
379 Wrapper for ->func_rs for function SUM().
383 sub sum_rs { return shift->func_rs('SUM') }
389 =item Arguments: $function
391 =item Return Value: $function_return_value
395 $rs = $schema->resultset("CD")->search({});
396 $length = $rs->get_column('title')->func('LENGTH');
398 Runs a query using the function on the column and returns the
399 value. Produces the following SQL:
401 SELECT LENGTH( title ) FROM cd me
406 my ($self,$function) = @_;
407 my $cursor = $self->func_rs($function)->cursor;
410 return map { $_->[ 0 ] } $cursor->all;
413 return ( $cursor->next )[ 0 ];
420 =item Arguments: $function
422 =item Return Value: $resultset
426 Creates the resultset that C<func()> uses to run its query.
431 my ($self,$function) = @_;
432 return $self->{_parent_resultset}->search(
434 select => {$function => $self->{_select}},
435 as => [$self->{_as}],
440 =head2 throw_exception
442 See L<DBIx::Class::Schema/throw_exception> for details.
446 sub throw_exception {
449 if (ref $self && $self->{_parent_resultset}) {
450 $self->{_parent_resultset}->throw_exception(@_);
453 DBIx::Class::Exception->throw(@_);
461 # Return Value: $resultset
463 # $year_col->_resultset->next
465 # Returns the underlying resultset. Creates it from the parent resultset if
471 return $self->{_resultset} ||= $self->{_parent_resultset}->search(undef,
473 select => [$self->{_select}],
483 Luke Saunders <luke.saunders@gmail.com>
489 You may distribute this code under the same terms as Perl itself.