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