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 $new_parent_rs = $rs->result_source->resultset->search ( {}, {
72 $alias => $rs->as_query,
74 -source_handle => $rs->result_source->handle,
79 $new_parent_rs ||= $rs->search_rs;
80 my $new_attrs = $new_parent_rs->{attrs} ||= {};
82 # FIXME - this should go away when the chaining branch is merged
83 # since what we do is actually chain to the original resultset, we need to throw
84 # away all selectors (otherwise they'll chain)
85 delete $new_attrs->{$_} for (qw/columns +columns select +select as +as cols include_columns/);
87 # prefetch causes additional columns to be fetched, but we can not just make a new
88 # rs via the _resolved_attrs trick - we need to retain the separation between
89 # +select/+as and select/as. At the same time we want to preserve any joins that the
90 # prefetch would otherwise generate.
91 $new_attrs->{join} = $rs->_merge_attr( delete $new_attrs->{join}, delete $new_attrs->{prefetch} );
93 # {collapse} would mean a has_many join was injected, which in turn means
94 # we need to group *IF WE CAN* (only if the column in question is unique)
95 if (!$new_attrs->{group_by} && keys %{$orig_attrs->{collapse}}) {
97 # scan for a constraint that would contain our column only - that'd be proof
99 my $constraints = { $rs->result_source->unique_constraints };
100 for my $constraint_columns ( values %$constraints ) {
102 next unless @$constraint_columns == 1;
104 my $col = $constraint_columns->[0];
105 my $fqcol = join ('.', $new_attrs->{alias}, $col);
107 if ($col eq $select or $fqcol eq $select) {
108 $new_attrs->{group_by} = [ $select ];
109 delete $new_attrs->{distinct}; # it is ignored when group_by is present
114 if (!$new_attrs->{group_by}) {
116 "Attempting to retrieve non-unique column '$column' on a resultset containing "
117 . 'one-to-many joins will return duplicate results.'
122 my $new = bless { _select => $select, _as => $column, _parent_resultset => $new_parent_rs }, $class;
130 =item Arguments: none
132 =item Return Value: \[ $sql, @bind ]
136 Returns the SQL query and bind vars associated with the invocant.
138 This is generally used as the RHS for a subquery.
142 sub as_query { return shift->_resultset->as_query(@_) }
148 =item Arguments: none
150 =item Return Value: $value
154 Returns the next value of the column in the resultset (or C<undef> if
157 Much like L<DBIx::Class::ResultSet/next> but just returning the
165 # using cursor so we don't inflate anything
166 my ($row) = $self->_resultset->cursor->next;
175 =item Arguments: none
177 =item Return Value: @values
181 Returns all values of the column in the resultset (or C<undef> if
184 Much like L<DBIx::Class::ResultSet/all> but returns values rather
192 # using cursor so we don't inflate anything
193 return map { $_->[0] } $self->_resultset->cursor->all;
200 =item Arguments: none
202 =item Return Value: $self
206 Resets the underlying resultset's cursor, so you can iterate through the
207 elements of the column again.
209 Much like L<DBIx::Class::ResultSet/reset>.
215 $self->_resultset->cursor->reset;
223 =item Arguments: none
225 =item Return Value: $value
229 Resets the underlying resultset and returns the next value of the column in the
230 resultset (or C<undef> if there is none).
232 Much like L<DBIx::Class::ResultSet/first> but just returning the one value.
239 # using cursor so we don't inflate anything
240 $self->_resultset->cursor->reset;
241 my ($row) = $self->_resultset->cursor->next;
250 =item Arguments: none
252 =item Return Value: $value
256 Much like L<DBIx::Class::ResultSet/single> fetches one and only one column
257 value using the cursor directly. If additional rows are present a warning
258 is issued before discarding the cursor.
265 my $attrs = $self->_resultset->_resolved_attrs;
266 my ($row) = $self->_resultset->result_source->storage->select_single(
267 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
277 =item Arguments: none
279 =item Return Value: $lowest_value
283 my $first_year = $year_col->min();
285 Wrapper for ->func. Returns the lowest value of the column in the
286 resultset (or C<undef> if there are none).
291 return shift->func('MIN');
298 =item Arguments: none
300 =item Return Value: $resultset
304 my $rs = $year_col->min_rs();
306 Wrapper for ->func_rs for function MIN().
310 sub min_rs { return shift->func_rs('MIN') }
316 =item Arguments: none
318 =item Return Value: $highest_value
322 my $last_year = $year_col->max();
324 Wrapper for ->func. Returns the highest value of the column in the
325 resultset (or C<undef> if there are none).
330 return shift->func('MAX');
337 =item Arguments: none
339 =item Return Value: $resultset
343 my $rs = $year_col->max_rs();
345 Wrapper for ->func_rs for function MAX().
349 sub max_rs { return shift->func_rs('MAX') }
355 =item Arguments: none
357 =item Return Value: $sum_of_values
361 my $total = $prices_col->sum();
363 Wrapper for ->func. Returns the sum of all the values in the column of
364 the resultset. Use on varchar-like columns at your own risk.
369 return shift->func('SUM');
376 =item Arguments: none
378 =item Return Value: $resultset
382 my $rs = $year_col->sum_rs();
384 Wrapper for ->func_rs for function SUM().
388 sub sum_rs { return shift->func_rs('SUM') }
394 =item Arguments: $function
396 =item Return Value: $function_return_value
400 $rs = $schema->resultset("CD")->search({});
401 $length = $rs->get_column('title')->func('LENGTH');
403 Runs a query using the function on the column and returns the
404 value. Produces the following SQL:
406 SELECT LENGTH( title ) FROM cd me
411 my ($self,$function) = @_;
412 my $cursor = $self->func_rs($function)->cursor;
415 return map { $_->[ 0 ] } $cursor->all;
418 return ( $cursor->next )[ 0 ];
425 =item Arguments: $function
427 =item Return Value: $resultset
431 Creates the resultset that C<func()> uses to run its query.
436 my ($self,$function) = @_;
437 return $self->{_parent_resultset}->search(
439 select => {$function => $self->{_select}},
440 as => [$self->{_as}],
445 =head2 throw_exception
447 See L<DBIx::Class::Schema/throw_exception> for details.
451 sub throw_exception {
454 if (ref $self && $self->{_parent_resultset}) {
455 $self->{_parent_resultset}->throw_exception(@_);
458 DBIx::Class::Exception->throw(@_);
466 # Return Value: $resultset
468 # $year_col->_resultset->next
470 # Returns the underlying resultset. Creates it from the parent resultset if
476 return $self->{_resultset} ||= $self->{_parent_resultset}->search(undef,
478 select => [$self->{_select}],
488 Luke Saunders <luke.saunders@gmail.com>
494 You may distribute this code under the same terms as Perl itself.