1 package DBIx::Class::ResultSetColumn;
6 use base 'DBIx::Class';
8 use DBIx::Class::_Util 'fail_on_internal_wantarray';
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;
51 my $rsrc = $rs->result_source;
53 # If $column can be found in the 'as' list of the parent resultset, use the
54 # corresponding element of its 'select' list (to keep any custom column
55 # definition set up with 'select' or '+select' attrs), otherwise use $column
56 # (to create a new column definition on-the-fly).
57 my $as_list = $orig_attrs->{as} || [];
58 my $select_list = $orig_attrs->{select} || [];
59 my $as_index = List::Util::first { ($as_list->[$_] || "") eq $column } 0..$#$as_list;
60 my $select = defined $as_index ? $select_list->[$as_index] : $column;
62 my ($new_parent_rs, $colmap);
63 for ($rsrc->columns, $column) {
64 if ($_ =~ /^ \Q$alias\E \. ([^\.]+) $ /x) {
68 $colmap->{"$alias.$_"} = $_;
73 # analyze the order_by, and see if it is done over a function/nonexistentcolumn
74 # if this is the case we will need to wrap a subquery since the result of RSC
75 # *must* be a single column select
78 { ! exists $colmap->{$_->[0]} }
79 ( $rsrc->schema->storage->_extract_order_criteria ($orig_attrs->{order_by} ) )
81 # nuke the prefetch before collapsing to sql
82 my $subq_rs = $rs->search;
83 $subq_rs->{attrs}{join} = $subq_rs->_merge_joinpref_attr( $subq_rs->{attrs}{join}, delete $subq_rs->{attrs}{prefetch} );
84 $new_parent_rs = $subq_rs->as_subselect_rs;
87 $new_parent_rs ||= $rs->search_rs;
88 my $new_attrs = $new_parent_rs->{attrs} ||= {};
90 # prefetch causes additional columns to be fetched, but we can not just make a new
91 # rs via the _resolved_attrs trick - we need to retain the separation between
92 # +select/+as and select/as. At the same time we want to preserve any joins that the
93 # prefetch would otherwise generate.
94 $new_attrs->{join} = $rs->_merge_joinpref_attr( $new_attrs->{join}, delete $new_attrs->{prefetch} );
96 # {collapse} would mean a has_many join was injected, which in turn means
97 # we need to group *IF WE CAN* (only if the column in question is unique)
98 if (!$orig_attrs->{group_by} && $orig_attrs->{collapse}) {
100 if ($colmap->{$select} and $rsrc->_identifying_column_set([$colmap->{$select}])) {
101 $new_attrs->{group_by} = [ $select ];
102 delete @{$new_attrs}{qw(distinct _grouped_by_distinct)}; # it is ignored when group_by is present
106 "Attempting to retrieve non-unique column '$column' on a resultset containing "
107 . 'one-to-many joins will return duplicate results.'
112 my $new = bless { _select => $select, _as => $column, _parent_resultset => $new_parent_rs }, $class;
120 =item Arguments: none
122 =item Return Value: \[ $sql, L<@bind_values|DBIx::Class::ResultSet/DBIC BIND VALUES> ]
126 Returns the SQL query and bind vars associated with the invocant.
128 This is generally used as the RHS for a subquery.
132 sub as_query { return shift->_resultset->as_query(@_) }
138 =item Arguments: none
140 =item Return Value: $value
144 Returns the next value of the column in the resultset (or C<undef> if
147 Much like L<DBIx::Class::ResultSet/next> but just returning the
155 # using cursor so we don't inflate anything
156 my ($row) = $self->_resultset->cursor->next;
165 =item Arguments: none
167 =item Return Value: @values
171 Returns all values of the column in the resultset (or C<undef> if
174 Much like L<DBIx::Class::ResultSet/all> but returns values rather
182 # using cursor so we don't inflate anything
183 return map { $_->[0] } $self->_resultset->cursor->all;
190 =item Arguments: none
192 =item Return Value: $self
196 Resets the underlying resultset's cursor, so you can iterate through the
197 elements of the column again.
199 Much like L<DBIx::Class::ResultSet/reset>.
205 $self->_resultset->cursor->reset;
213 =item Arguments: none
215 =item Return Value: $value
219 Resets the underlying resultset and returns the next value of the column in the
220 resultset (or C<undef> if there is none).
222 Much like L<DBIx::Class::ResultSet/first> but just returning the one value.
229 # using cursor so we don't inflate anything
230 $self->_resultset->cursor->reset;
231 my ($row) = $self->_resultset->cursor->next;
240 =item Arguments: none
242 =item Return Value: $value
246 Much like L<DBIx::Class::ResultSet/single> fetches one and only one column
247 value using the cursor directly. If additional rows are present a warning
248 is issued before discarding the cursor.
255 my $attrs = $self->_resultset->_resolved_attrs;
256 my ($row) = $self->_resultset->result_source->storage->select_single(
257 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
267 =item Arguments: none
269 =item Return Value: $lowest_value
273 my $first_year = $year_col->min();
275 Wrapper for ->func. Returns the lowest value of the column in the
276 resultset (or C<undef> if there are none).
281 return shift->func('MIN');
288 =item Arguments: none
290 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
294 my $rs = $year_col->min_rs();
296 Wrapper for ->func_rs for function MIN().
300 sub min_rs { return shift->func_rs('MIN') }
306 =item Arguments: none
308 =item Return Value: $highest_value
312 my $last_year = $year_col->max();
314 Wrapper for ->func. Returns the highest value of the column in the
315 resultset (or C<undef> if there are none).
320 return shift->func('MAX');
327 =item Arguments: none
329 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
333 my $rs = $year_col->max_rs();
335 Wrapper for ->func_rs for function MAX().
339 sub max_rs { return shift->func_rs('MAX') }
345 =item Arguments: none
347 =item Return Value: $sum_of_values
351 my $total = $prices_col->sum();
353 Wrapper for ->func. Returns the sum of all the values in the column of
354 the resultset. Use on varchar-like columns at your own risk.
359 return shift->func('SUM');
366 =item Arguments: none
368 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
372 my $rs = $year_col->sum_rs();
374 Wrapper for ->func_rs for function SUM().
378 sub sum_rs { return shift->func_rs('SUM') }
384 =item Arguments: $function
386 =item Return Value: $function_return_value
390 $rs = $schema->resultset("CD")->search({});
391 $length = $rs->get_column('title')->func('LENGTH');
393 Runs a query using the function on the column and returns the
394 value. Produces the following SQL:
396 SELECT LENGTH( title ) FROM cd me
401 my ($self,$function) = @_;
402 my $cursor = $self->func_rs($function)->cursor;
405 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_WANTARRAY and my $sog = fail_on_internal_wantarray($self);
406 return map { $_->[ 0 ] } $cursor->all;
409 return ( $cursor->next )[ 0 ];
416 =item Arguments: $function
418 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
422 Creates the resultset that C<func()> uses to run its query.
427 my ($self,$function) = @_;
429 my $rs = $self->{_parent_resultset};
430 my $select = $self->{_select};
433 if ($rs->_resolved_attrs->{group_by}) {
434 $select = $self->{_as};
435 $rs = $rs->as_subselect_rs;
438 $rs->search( undef, {
439 columns => { $self->{_as} => { $function => $select } }
443 =head2 throw_exception
445 See L<DBIx::Class::Schema/throw_exception> for details.
449 sub throw_exception {
452 if (ref $self && $self->{_parent_resultset}) {
453 $self->{_parent_resultset}->throw_exception(@_);
456 DBIx::Class::Exception->throw(@_);
464 # Return Value: $resultset
466 # $year_col->_resultset->next
468 # Returns the underlying resultset. Creates it from the parent resultset if
474 return $self->{_resultset} ||= $self->{_parent_resultset}->search(undef,
476 select => [$self->{_select}],
484 =head1 AUTHOR AND CONTRIBUTORS
486 See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class
490 You may distribute this code under the same terms as Perl itself.