Modified Cursor to use COUNT(*) for count if possible
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Cursor.pm
1 package DBIx::Class::Cursor;
2
3 use strict;
4 use warnings;
5 use overload
6         '0+'     => 'count',
7         fallback => 1;
8
9 sub new {
10   my ($it_class, $db_class, $sth, $args, $cols, $attrs) = @_;
11   $sth->execute(@{$args || []}) unless $sth->{Active};
12   my $new = {
13     class => $db_class,
14     sth => $sth,
15     cols => $cols,
16     args => $args,
17     attrs => $attrs };
18   return bless ($new, $it_class);
19 }
20
21 sub next {
22   my ($self) = @_;
23   my @row = $self->{sth}->fetchrow_array;
24   return unless @row;
25   #unless (@row) { $self->{sth}->finish; return; }
26   return $self->{class}->_row_to_object($self->{cols}, \@row);
27 }
28
29 sub count {
30   my ($self) = @_;
31   if (my $cond = $self->{attrs}->{where}) {
32     my $class = $self->{class};
33     my $sth = $class->_get_sth( 'select', [ 'COUNT(*)' ],
34                                   $class->_table_name, $cond);
35     $sth->execute(@{$self->{args} || []});
36     my ($count) = $sth->fetchrow_array;
37     $sth->finish;
38     return $count;
39   } else {
40     return scalar $_[0]->all; # So inefficient
41   }
42 }
43
44 sub all {
45   my ($self) = @_;
46   $self->reset;
47   my @all;
48   while (my $obj = $self->next) {
49     push(@all, $obj);
50   }
51   $self->reset;
52   return @all;
53 }
54
55 sub reset {
56   $_[0]->{sth}->finish if $_[0]->{sth}->{Active};
57   $_[0]->{sth}->execute(@{$_[0]->{args} || []});
58   return $_[0];
59 }
60
61 sub first {
62   return $_[0]->reset->next;
63 }
64
65 1;