1 package DBIx::Class::ResultSetColumn;
6 use base 'DBIx::Class';
8 use Carp::Clan qw/^DBIx::Class/;
9 use DBIx::Class::Exception;
11 # not importing first() as it will clash with our own method
16 DBIx::Class::ResultSetColumn - helpful methods for messing
17 with a single column of the resultset
21 $rs = $schema->resultset('CD')->search({ artist => 'Tool' });
22 $rs_column = $rs->get_column('year');
23 $max_year = $rs_column->max; #returns latest year
27 A convenience class used to perform operations on a specific column of
36 my $obj = DBIx::Class::ResultSetColumn->new($rs, $column);
38 Creates a new resultset column object from the resultset and column
39 passed as params. Used internally by L<DBIx::Class::ResultSet/get_column>.
44 my ($class, $rs, $column) = @_;
45 $class = ref $class if ref $class;
47 $rs->throw_exception('column must be supplied') unless $column;
49 my $orig_attrs = $rs->_resolved_attrs;
50 my $alias = $rs->current_source_alias;
52 # If $column can be found in the 'as' list of the parent resultset, use the
53 # corresponding element of its 'select' list (to keep any custom column
54 # definition set up with 'select' or '+select' attrs), otherwise use $column
55 # (to create a new column definition on-the-fly).
56 my $as_list = $orig_attrs->{as} || [];
57 my $select_list = $orig_attrs->{select} || [];
58 my $as_index = List::Util::first { ($as_list->[$_] || "") eq $column } 0..$#$as_list;
59 my $select = defined $as_index ? $select_list->[$as_index] : $column;
62 # analyze the order_by, and see if it is done over a function/nonexistentcolumn
63 # if this is the case we will need to wrap a subquery since the result of RSC
64 # *must* be a single column select
66 { $_ => 1, ($_ =~ /\./) ? () : ( "$alias.$_" => 1 ) }
67 ($rs->result_source->columns, $column)
71 { ! $collist{$_->[0]} }
72 ( $rs->result_source->schema->storage->_extract_order_criteria ($orig_attrs->{order_by} ) )
74 # nuke the prefetch before collapsing to sql
75 my $subq_rs = $rs->search;
76 $subq_rs->{attrs}{join} = $subq_rs->_merge_joinpref_attr( $subq_rs->{attrs}{join}, delete $subq_rs->{attrs}{prefetch} );
77 $new_parent_rs = $subq_rs->as_subselect_rs;
80 $new_parent_rs ||= $rs->search_rs;
81 my $new_attrs = $new_parent_rs->{attrs} ||= {};
83 # prefetch causes additional columns to be fetched, but we can not just make a new
84 # rs via the _resolved_attrs trick - we need to retain the separation between
85 # +select/+as and select/as. At the same time we want to preserve any joins that the
86 # prefetch would otherwise generate.
87 $new_attrs->{join} = $rs->_merge_joinpref_attr( $new_attrs->{join}, delete $new_attrs->{prefetch} );
89 # {collapse} would mean a has_many join was injected, which in turn means
90 # we need to group *IF WE CAN* (only if the column in question is unique)
91 if (!$orig_attrs->{group_by} && keys %{$orig_attrs->{collapse}}) {
93 # scan for a constraint that would contain our column only - that'd be proof
95 my $constraints = { $rs->result_source->unique_constraints };
96 for my $constraint_columns ( values %$constraints ) {
98 next unless @$constraint_columns == 1;
100 my $col = $constraint_columns->[0];
101 my $fqcol = join ('.', $new_attrs->{alias}, $col);
103 if ($col eq $select or $fqcol eq $select) {
104 $new_attrs->{group_by} = [ $select ];
105 delete $new_attrs->{distinct}; # it is ignored when group_by is present
110 if (!$new_attrs->{group_by}) {
112 "Attempting to retrieve non-unique column '$column' on a resultset containing "
113 . 'one-to-many joins will return duplicate results.'
118 my $new = bless { _select => $select, _as => $column, _parent_resultset => $new_parent_rs }, $class;
126 =item Arguments: none
128 =item Return Value: \[ $sql, @bind ]
132 Returns the SQL query and bind vars associated with the invocant.
134 This is generally used as the RHS for a subquery.
138 sub as_query { return shift->_resultset->as_query(@_) }
144 =item Arguments: none
146 =item Return Value: $value
150 Returns the next value of the column in the resultset (or C<undef> if
153 Much like L<DBIx::Class::ResultSet/next> but just returning the
161 # using cursor so we don't inflate anything
162 my ($row) = $self->_resultset->cursor->next;
171 =item Arguments: none
173 =item Return Value: @values
177 Returns all values of the column in the resultset (or C<undef> if
180 Much like L<DBIx::Class::ResultSet/all> but returns values rather
188 # using cursor so we don't inflate anything
189 return map { $_->[0] } $self->_resultset->cursor->all;
196 =item Arguments: none
198 =item Return Value: $self
202 Resets the underlying resultset's cursor, so you can iterate through the
203 elements of the column again.
205 Much like L<DBIx::Class::ResultSet/reset>.
211 $self->_resultset->cursor->reset;
219 =item Arguments: none
221 =item Return Value: $value
225 Resets the underlying resultset and returns the next value of the column in the
226 resultset (or C<undef> if there is none).
228 Much like L<DBIx::Class::ResultSet/first> but just returning the one value.
235 # using cursor so we don't inflate anything
236 $self->_resultset->cursor->reset;
237 my ($row) = $self->_resultset->cursor->next;
246 =item Arguments: none
248 =item Return Value: $value
252 Much like L<DBIx::Class::ResultSet/single> fetches one and only one column
253 value using the cursor directly. If additional rows are present a warning
254 is issued before discarding the cursor.
261 my $attrs = $self->_resultset->_resolved_attrs;
262 my ($row) = $self->_resultset->result_source->storage->select_single(
263 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
273 =item Arguments: none
275 =item Return Value: $lowest_value
279 my $first_year = $year_col->min();
281 Wrapper for ->func. Returns the lowest value of the column in the
282 resultset (or C<undef> if there are none).
287 return shift->func('MIN');
294 =item Arguments: none
296 =item Return Value: $resultset
300 my $rs = $year_col->min_rs();
302 Wrapper for ->func_rs for function MIN().
306 sub min_rs { return shift->func_rs('MIN') }
312 =item Arguments: none
314 =item Return Value: $highest_value
318 my $last_year = $year_col->max();
320 Wrapper for ->func. Returns the highest value of the column in the
321 resultset (or C<undef> if there are none).
326 return shift->func('MAX');
333 =item Arguments: none
335 =item Return Value: $resultset
339 my $rs = $year_col->max_rs();
341 Wrapper for ->func_rs for function MAX().
345 sub max_rs { return shift->func_rs('MAX') }
351 =item Arguments: none
353 =item Return Value: $sum_of_values
357 my $total = $prices_col->sum();
359 Wrapper for ->func. Returns the sum of all the values in the column of
360 the resultset. Use on varchar-like columns at your own risk.
365 return shift->func('SUM');
372 =item Arguments: none
374 =item Return Value: $resultset
378 my $rs = $year_col->sum_rs();
380 Wrapper for ->func_rs for function SUM().
384 sub sum_rs { return shift->func_rs('SUM') }
390 =item Arguments: $function
392 =item Return Value: $function_return_value
396 $rs = $schema->resultset("CD")->search({});
397 $length = $rs->get_column('title')->func('LENGTH');
399 Runs a query using the function on the column and returns the
400 value. Produces the following SQL:
402 SELECT LENGTH( title ) FROM cd me
407 my ($self,$function) = @_;
408 my $cursor = $self->func_rs($function)->cursor;
411 return map { $_->[ 0 ] } $cursor->all;
414 return ( $cursor->next )[ 0 ];
421 =item Arguments: $function
423 =item Return Value: $resultset
427 Creates the resultset that C<func()> uses to run its query.
432 my ($self,$function) = @_;
433 return $self->{_parent_resultset}->search(
435 select => {$function => $self->{_select}},
436 as => [$self->{_as}],
441 =head2 throw_exception
443 See L<DBIx::Class::Schema/throw_exception> for details.
447 sub throw_exception {
450 if (ref $self && $self->{_parent_resultset}) {
451 $self->{_parent_resultset}->throw_exception(@_);
454 DBIx::Class::Exception->throw(@_);
462 # Return Value: $resultset
464 # $year_col->_resultset->next
466 # Returns the underlying resultset. Creates it from the parent resultset if
472 return $self->{_resultset} ||= $self->{_parent_resultset}->search(undef,
474 select => [$self->{_select}],
484 Luke Saunders <luke.saunders@gmail.com>
490 You may distribute this code under the same terms as Perl itself.