SQLite changed their exception text again
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSetColumn.pm
CommitLineData
2bb7b40b 1package DBIx::Class::ResultSetColumn;
1a58752c 2
2bb7b40b 3use strict;
4use warnings;
1a58752c 5
2bb7b40b 6use base 'DBIx::Class';
70c28808 7use DBIx::Class::Carp;
a9da9b6a 8use DBIx::Class::_Util 'fail_on_internal_wantarray';
64c50e81 9use namespace::clean;
94244987 10
11# not importing first() as it will clash with our own method
6298a324 12use List::Util ();
2bb7b40b 13
14=head1 NAME
15
16 DBIx::Class::ResultSetColumn - helpful methods for messing
17 with a single column of the resultset
18
19=head1 SYNOPSIS
20
21 $rs = $schema->resultset('CD')->search({ artist => 'Tool' });
22 $rs_column = $rs->get_column('year');
23 $max_year = $rs_column->max; #returns latest year
24
25=head1 DESCRIPTION
26
eb98561c 27A convenience class used to perform operations on a specific column of
28a resultset.
2bb7b40b 29
30=cut
31
32=head1 METHODS
33
34=head2 new
35
36 my $obj = DBIx::Class::ResultSetColumn->new($rs, $column);
37
eb98561c 38Creates a new resultset column object from the resultset and column
39passed as params. Used internally by L<DBIx::Class::ResultSet/get_column>.
2bb7b40b 40
41=cut
42
43sub new {
44 my ($class, $rs, $column) = @_;
45 $class = ref $class if ref $class;
7ae9706c 46
66e33361 47 $rs->throw_exception('column must be supplied') unless $column;
7ae9706c 48
d8dbe471 49 my $orig_attrs = $rs->_resolved_attrs;
9b8930f4 50 my $alias = $rs->current_source_alias;
2b3fc408 51 my $rsrc = $rs->result_source;
472d7df3 52
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;
61
aca094b4 62 my $colmap;
2b3fc408 63 for ($rsrc->columns, $column) {
64 if ($_ =~ /^ \Q$alias\E \. ([^\.]+) $ /x) {
65 $colmap->{$_} = $1;
66 }
67 elsif ($_ !~ /\./) {
68 $colmap->{"$alias.$_"} = $_;
69 $colmap->{$_} = $_;
70 }
71 }
72
aca094b4 73 my $new_parent_rs;
472d7df3 74 # analyze the order_by, and see if it is done over a function/nonexistentcolumn
75 # if this is the case we will need to wrap a subquery since the result of RSC
76 # *must* be a single column select
472d7df3 77 if (
78 scalar grep
2b3fc408 79 { ! exists $colmap->{$_->[0]} }
80 ( $rsrc->schema->storage->_extract_order_criteria ($orig_attrs->{order_by} ) )
472d7df3 81 ) {
5716e003 82 # nuke the prefetch before collapsing to sql
aca094b4 83 my $subq_rs = $rs->search_rs;
37aafa2e 84 $subq_rs->{attrs}{join} = $subq_rs->_merge_joinpref_attr( $subq_rs->{attrs}{join}, delete $subq_rs->{attrs}{prefetch} );
9b8930f4 85 $new_parent_rs = $subq_rs->as_subselect_rs;
472d7df3 86 }
87
88 $new_parent_rs ||= $rs->search_rs;
66e33361 89 my $new_attrs = $new_parent_rs->{attrs} ||= {};
90
7ae9706c 91 # prefetch causes additional columns to be fetched, but we can not just make a new
92 # rs via the _resolved_attrs trick - we need to retain the separation between
bed3a173 93 # +select/+as and select/as. At the same time we want to preserve any joins that the
94 # prefetch would otherwise generate.
37aafa2e 95 $new_attrs->{join} = $rs->_merge_joinpref_attr( $new_attrs->{join}, delete $new_attrs->{prefetch} );
b6e85b48 96
d8dbe471 97 # {collapse} would mean a has_many join was injected, which in turn means
722c0140 98 # we need to group *IF WE CAN* (only if the column in question is unique)
f1693c0d 99 if (!$orig_attrs->{group_by} && $orig_attrs->{collapse}) {
d8dbe471 100
2b3fc408 101 if ($colmap->{$select} and $rsrc->_identifying_column_set([$colmap->{$select}])) {
102 $new_attrs->{group_by} = [ $select ];
1e4f9fb3 103 delete @{$new_attrs}{qw(distinct _grouped_by_distinct)}; # it is ignored when group_by is present
d8dbe471 104 }
2b3fc408 105 else {
722c0140 106 carp (
107 "Attempting to retrieve non-unique column '$column' on a resultset containing "
108 . 'one-to-many joins will return duplicate results.'
109 );
110 }
d8dbe471 111 }
112
aca094b4 113 # collapse the selector to a literal so that it survives a possible distinct parse
114 # if it turns out to be an aggregate - at least the user will get a proper exception
115 # instead of silent drop of the group_by altogether
116 my $new = bless {
117 _select => \ $rsrc->storage->sql_maker->_recurse_fields($select),
118 _as => $column,
119 _parent_resultset => $new_parent_rs }, $class;
2bb7b40b 120 return $new;
121}
122
6dfbe2f8 123=head2 as_query
658fa250 124
125=over 4
126
428a645e 127=item Arguments: none
658fa250 128
00c12490 129=item Return Value: \[ $sql, L<@bind_values|DBIx::Class::ResultSet/DBIC BIND VALUES> ]
658fa250 130
131=back
132
133Returns the SQL query and bind vars associated with the invocant.
134
03834f77 135This is generally used as the RHS for a subquery.
c7a9d102 136
137=cut
138
0f6fc705 139sub as_query { return shift->_resultset->as_query(@_) }
c7a9d102 140
2bb7b40b 141=head2 next
142
143=over 4
144
145=item Arguments: none
146
147=item Return Value: $value
148
149=back
150
eb98561c 151Returns the next value of the column in the resultset (or C<undef> if
152there is none).
2bb7b40b 153
8273e845 154Much like L<DBIx::Class::ResultSet/next> but just returning the
eb98561c 155one value.
2bb7b40b 156
157=cut
158
159sub next {
160 my $self = shift;
b7c79955 161
162 # using cursor so we don't inflate anything
66521001 163 my ($row) = $self->_resultset->cursor->next;
b7c79955 164
2bb7b40b 165 return $row;
166}
167
168=head2 all
169
170=over 4
171
172=item Arguments: none
173
174=item Return Value: @values
175
176=back
177
eb98561c 178Returns all values of the column in the resultset (or C<undef> if
179there are none).
2bb7b40b 180
eb98561c 181Much like L<DBIx::Class::ResultSet/all> but returns values rather
fb13a49f 182than result objects.
2bb7b40b 183
184=cut
185
186sub all {
187 my $self = shift;
b7c79955 188
189 # using cursor so we don't inflate anything
66521001 190 return map { $_->[0] } $self->_resultset->cursor->all;
191}
192
193=head2 reset
194
195=over 4
196
197=item Arguments: none
198
199=item Return Value: $self
200
201=back
202
203Resets the underlying resultset's cursor, so you can iterate through the
204elements of the column again.
205
206Much like L<DBIx::Class::ResultSet/reset>.
207
208=cut
209
210sub reset {
211 my $self = shift;
212 $self->_resultset->cursor->reset;
b7c79955 213 return $self;
66521001 214}
215
216=head2 first
217
218=over 4
219
220=item Arguments: none
221
222=item Return Value: $value
223
224=back
225
226Resets the underlying resultset and returns the next value of the column in the
227resultset (or C<undef> if there is none).
228
229Much like L<DBIx::Class::ResultSet/first> but just returning the one value.
230
231=cut
232
233sub first {
234 my $self = shift;
b7c79955 235
236 # using cursor so we don't inflate anything
237 $self->_resultset->cursor->reset;
01dc6781 238 my ($row) = $self->_resultset->cursor->next;
b7c79955 239
66521001 240 return $row;
2bb7b40b 241}
242
4e55c3ae 243=head2 single
244
245=over 4
246
247=item Arguments: none
248
249=item Return Value: $value
250
251=back
252
253Much like L<DBIx::Class::ResultSet/single> fetches one and only one column
254value using the cursor directly. If additional rows are present a warning
255is issued before discarding the cursor.
256
257=cut
258
259sub single {
260 my $self = shift;
261
262 my $attrs = $self->_resultset->_resolved_attrs;
263 my ($row) = $self->_resultset->result_source->storage->select_single(
264 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
265 );
266
267 return $row;
268}
269
2bb7b40b 270=head2 min
271
272=over 4
273
274=item Arguments: none
275
276=item Return Value: $lowest_value
277
278=back
279
eb98561c 280 my $first_year = $year_col->min();
281
282Wrapper for ->func. Returns the lowest value of the column in the
283resultset (or C<undef> if there are none).
2bb7b40b 284
285=cut
286
287sub min {
6b051e14 288 return shift->func('MIN');
2bb7b40b 289}
290
4fa7bc22 291=head2 min_rs
292
293=over 4
294
295=item Arguments: none
296
fb13a49f 297=item Return Value: L<$resultset|DBIx::Class::ResultSet>
4fa7bc22 298
299=back
300
301 my $rs = $year_col->min_rs();
302
303Wrapper for ->func_rs for function MIN().
304
305=cut
306
307sub min_rs { return shift->func_rs('MIN') }
308
2bb7b40b 309=head2 max
310
311=over 4
312
313=item Arguments: none
314
315=item Return Value: $highest_value
316
317=back
318
eb98561c 319 my $last_year = $year_col->max();
320
321Wrapper for ->func. Returns the highest value of the column in the
322resultset (or C<undef> if there are none).
2bb7b40b 323
324=cut
325
326sub max {
6b051e14 327 return shift->func('MAX');
2bb7b40b 328}
329
4fa7bc22 330=head2 max_rs
331
332=over 4
333
334=item Arguments: none
335
fb13a49f 336=item Return Value: L<$resultset|DBIx::Class::ResultSet>
4fa7bc22 337
338=back
339
340 my $rs = $year_col->max_rs();
341
342Wrapper for ->func_rs for function MAX().
343
344=cut
345
346sub max_rs { return shift->func_rs('MAX') }
347
2bb7b40b 348=head2 sum
349
350=over 4
351
352=item Arguments: none
353
354=item Return Value: $sum_of_values
355
356=back
357
eb98561c 358 my $total = $prices_col->sum();
359
360Wrapper for ->func. Returns the sum of all the values in the column of
361the resultset. Use on varchar-like columns at your own risk.
2bb7b40b 362
363=cut
364
365sub sum {
6b051e14 366 return shift->func('SUM');
2bb7b40b 367}
368
4fa7bc22 369=head2 sum_rs
370
371=over 4
372
373=item Arguments: none
374
fb13a49f 375=item Return Value: L<$resultset|DBIx::Class::ResultSet>
4fa7bc22 376
377=back
378
379 my $rs = $year_col->sum_rs();
380
381Wrapper for ->func_rs for function SUM().
382
383=cut
384
385sub sum_rs { return shift->func_rs('SUM') }
386
2bb7b40b 387=head2 func
388
389=over 4
390
391=item Arguments: $function
392
393=item Return Value: $function_return_value
394
395=back
396
e8419341 397 $rs = $schema->resultset("CD")->search({});
398 $length = $rs->get_column('title')->func('LENGTH');
2bb7b40b 399
eb98561c 400Runs a query using the function on the column and returns the
401value. Produces the following SQL:
402
403 SELECT LENGTH( title ) FROM cd me
2bb7b40b 404
405=cut
406
407sub func {
6b051e14 408 my ($self,$function) = @_;
4fa7bc22 409 my $cursor = $self->func_rs($function)->cursor;
d4daee7b 410
5d62876f 411 if( wantarray ) {
a9da9b6a 412 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_WANTARRAY and my $sog = fail_on_internal_wantarray($self);
5d62876f 413 return map { $_->[ 0 ] } $cursor->all;
414 }
415
416 return ( $cursor->next )[ 0 ];
2bb7b40b 417}
418
4fa7bc22 419=head2 func_rs
420
421=over 4
422
423=item Arguments: $function
424
fb13a49f 425=item Return Value: L<$resultset|DBIx::Class::ResultSet>
4fa7bc22 426
427=back
428
429Creates the resultset that C<func()> uses to run its query.
430
431=cut
432
433sub func_rs {
434 my ($self,$function) = @_;
3214abc7 435
436 my $rs = $self->{_parent_resultset};
437 my $select = $self->{_select};
438
439 # wrap a grouped rs
440 if ($rs->_resolved_attrs->{group_by}) {
441 $select = $self->{_as};
442 $rs = $rs->as_subselect_rs;
443 }
444
445 $rs->search( undef, {
446 columns => { $self->{_as} => { $function => $select } }
447 } );
4fa7bc22 448}
449
5d1fc7dc 450=head2 throw_exception
451
452See L<DBIx::Class::Schema/throw_exception> for details.
d4daee7b 453
8273e845 454=cut
d4daee7b 455
5d1fc7dc 456sub throw_exception {
f9080e45 457 my $self = shift;
1a58752c 458
5d1fc7dc 459 if (ref $self && $self->{_parent_resultset}) {
1a58752c 460 $self->{_parent_resultset}->throw_exception(@_);
461 }
462 else {
463 DBIx::Class::Exception->throw(@_);
5d1fc7dc 464 }
465}
466
b6e85b48 467# _resultset
468#
469# Arguments: none
470#
471# Return Value: $resultset
472#
473# $year_col->_resultset->next
474#
475# Returns the underlying resultset. Creates it from the parent resultset if
476# necessary.
b7c79955 477#
66521001 478sub _resultset {
479 my $self = shift;
480
481 return $self->{_resultset} ||= $self->{_parent_resultset}->search(undef,
482 {
483 select => [$self->{_select}],
484 as => [$self->{_as}]
485 }
486 );
487}
488
2bb7b40b 4891;
490
0c11ad0e 491=head1 AUTHOR AND CONTRIBUTORS
2bb7b40b 492
0c11ad0e 493See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class
eb98561c 494
2bb7b40b 495=head1 LICENSE
496
497You may distribute this code under the same terms as Perl itself.
498
499=cut