Added as_sql and as_subselect as wrappers around as_query
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSetColumn.pm
1 package DBIx::Class::ResultSetColumn;
2 use strict;
3 use warnings;
4 use base 'DBIx::Class';
5 use List::Util;
6
7 =head1 NAME
8
9   DBIx::Class::ResultSetColumn - helpful methods for messing
10   with a single column of the resultset
11
12 =head1 SYNOPSIS
13
14   $rs = $schema->resultset('CD')->search({ artist => 'Tool' });
15   $rs_column = $rs->get_column('year');
16   $max_year = $rs_column->max; #returns latest year
17
18 =head1 DESCRIPTION
19
20 A convenience class used to perform operations on a specific column of
21 a resultset.
22
23 =cut
24
25 =head1 METHODS
26
27 =head2 new
28
29   my $obj = DBIx::Class::ResultSetColumn->new($rs, $column);
30
31 Creates a new resultset column object from the resultset and column
32 passed as params. Used internally by L<DBIx::Class::ResultSet/get_column>.
33
34 =cut
35
36 sub new {
37   my ($class, $rs, $column) = @_;
38   $class = ref $class if ref $class;
39   my $new_parent_rs = $rs->search_rs; # we don't want to mess up the original, so clone it
40   my $attrs = $new_parent_rs->_resolved_attrs;
41   $new_parent_rs->{attrs}->{$_} = undef for qw(prefetch include_columns +select +as); # prefetch, include_columns, +select, +as cause additional columns to be fetched
42
43   # If $column can be found in the 'as' list of the parent resultset, use the
44   # corresponding element of its 'select' list (to keep any custom column
45   # definition set up with 'select' or '+select' attrs), otherwise use $column
46   # (to create a new column definition on-the-fly).
47   my $as_list = $attrs->{as} || [];
48   my $select_list = $attrs->{select} || [];
49   my $as_index = List::Util::first { ($as_list->[$_] || "") eq $column } 0..$#$as_list;
50   my $select = defined $as_index ? $select_list->[$as_index] : $column;
51
52   my $new = bless { _select => $select, _as => $column, _parent_resultset => $new_parent_rs }, $class;
53   $new->throw_exception("column must be supplied") unless $column;
54   return $new;
55 }
56
57 =head2 as_query
58
59 =over 4
60
61 =item Arguments: none
62
63 =item Return Value: \[ $sql, @bind ]
64
65 =back
66
67 Returns the SQL query and bind vars associated with the invocant.
68
69 =cut
70
71 sub as_query { return shift->_resultset->as_query }
72
73 =head2 as_subselect
74
75 =over 4
76
77 =item Arguments: none
78
79 =item Return Value: \[ $sql, @bind ]
80
81 =back
82
83 Returns the SQL query and bind vars associated with the invocant.
84
85 The SQL will be wrapped in parentheses, ready for use as a subselect.
86
87 =cut
88
89 sub as_subselect {
90   my $self = shift;
91   my $arr = ${$self->as_query(@_)};
92   $arr->[0] = '( ' . $arr->[0] . ' )';
93   return \$arr;
94 }
95
96 =head2 as_query
97
98 =over 4
99
100 =item Arguments: none
101
102 =item Return Value: $sql
103
104 =back
105
106 Returns the SQL query associated with the invocant. All bind vars
107 will have been bound using C<< DBI->quote() >>.
108
109 =cut
110
111 sub as_sql {
112   my $self = shift;
113   my $arr = ${$self->as_query(@_)};
114   my $sql = shift @$arr;
115   my $dbh = $self->_resultset->result_source->schema->storage->dbh;
116   $sql =~ s/\?/$dbh->quote((shift @$arr)->[1])/eg;
117   return $sql
118 }
119
120 =head2 next
121
122 =over 4
123
124 =item Arguments: none
125
126 =item Return Value: $value
127
128 =back
129
130 Returns the next value of the column in the resultset (or C<undef> if
131 there is none).
132
133 Much like L<DBIx::Class::ResultSet/next> but just returning the 
134 one value.
135
136 =cut
137
138 sub next {
139   my $self = shift;
140   my ($row) = $self->_resultset->cursor->next;
141   return $row;
142 }
143
144 =head2 all
145
146 =over 4
147
148 =item Arguments: none
149
150 =item Return Value: @values
151
152 =back
153
154 Returns all values of the column in the resultset (or C<undef> if
155 there are none).
156
157 Much like L<DBIx::Class::ResultSet/all> but returns values rather
158 than row objects.
159
160 =cut
161
162 sub all {
163   my $self = shift;
164   return map { $_->[0] } $self->_resultset->cursor->all;
165 }
166
167 =head2 reset
168
169 =over 4
170
171 =item Arguments: none
172
173 =item Return Value: $self
174
175 =back
176
177 Resets the underlying resultset's cursor, so you can iterate through the
178 elements of the column again.
179
180 Much like L<DBIx::Class::ResultSet/reset>.
181
182 =cut
183
184 sub reset {
185   my $self = shift;
186   $self->_resultset->cursor->reset;
187   return $self;
188 }
189
190 =head2 first
191
192 =over 4
193
194 =item Arguments: none
195
196 =item Return Value: $value
197
198 =back
199
200 Resets the underlying resultset and returns the next value of the column in the
201 resultset (or C<undef> if there is none).
202
203 Much like L<DBIx::Class::ResultSet/first> but just returning the one value.
204
205 =cut
206
207 sub first {
208   my $self = shift;
209   my ($row) = $self->_resultset->cursor->reset->next;
210   return $row;
211 }
212
213 =head2 min
214
215 =over 4
216
217 =item Arguments: none
218
219 =item Return Value: $lowest_value
220
221 =back
222
223   my $first_year = $year_col->min();
224
225 Wrapper for ->func. Returns the lowest value of the column in the
226 resultset (or C<undef> if there are none).
227
228 =cut
229
230 sub min {
231   return shift->func('MIN');
232 }
233
234 =head2 max
235
236 =over 4
237
238 =item Arguments: none
239
240 =item Return Value: $highest_value
241
242 =back
243
244   my $last_year = $year_col->max();
245
246 Wrapper for ->func. Returns the highest value of the column in the
247 resultset (or C<undef> if there are none).
248
249 =cut
250
251 sub max {
252   return shift->func('MAX');
253 }
254
255 =head2 sum
256
257 =over 4
258
259 =item Arguments: none
260
261 =item Return Value: $sum_of_values
262
263 =back
264
265   my $total = $prices_col->sum();
266
267 Wrapper for ->func. Returns the sum of all the values in the column of
268 the resultset. Use on varchar-like columns at your own risk.
269
270 =cut
271
272 sub sum {
273   return shift->func('SUM');
274 }
275
276 =head2 func
277
278 =over 4
279
280 =item Arguments: $function
281
282 =item Return Value: $function_return_value
283
284 =back
285
286   $rs = $schema->resultset("CD")->search({});
287   $length = $rs->get_column('title')->func('LENGTH');
288
289 Runs a query using the function on the column and returns the
290 value. Produces the following SQL:
291
292   SELECT LENGTH( title ) FROM cd me
293
294 =cut
295
296 sub func {
297   my ($self,$function) = @_;
298   my $cursor = $self->{_parent_resultset}->search(undef, {select => {$function => $self->{_select}}, as => [$self->{_as}]})->cursor;
299   
300   if( wantarray ) {
301     return map { $_->[ 0 ] } $cursor->all;
302   }
303
304   return ( $cursor->next )[ 0 ];
305 }
306
307 =head2 throw_exception
308
309 See L<DBIx::Class::Schema/throw_exception> for details.
310   
311 =cut 
312     
313 sub throw_exception {
314   my $self=shift;
315   if (ref $self && $self->{_parent_resultset}) {
316     $self->{_parent_resultset}->throw_exception(@_)
317   } else {
318     croak(@_);
319   }
320 }
321
322 # _resultset
323 #
324 # Arguments: none
325 #
326 # Return Value: $resultset
327 #
328 #  $year_col->_resultset->next
329 #
330 # Returns the underlying resultset. Creates it from the parent resultset if
331 # necessary.
332
333 sub _resultset {
334   my $self = shift;
335
336   return $self->{_resultset} ||= $self->{_parent_resultset}->search(undef,
337     {
338       select => [$self->{_select}],
339       as => [$self->{_as}]
340     }
341   );
342 }
343
344 1;
345
346 =head1 AUTHORS
347
348 Luke Saunders <luke.saunders@gmail.com>
349
350 Jess Robinson
351
352 =head1 LICENSE
353
354 You may distribute this code under the same terms as Perl itself.
355
356 =cut