Modified Cursor to use COUNT(*) for count if possible
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Cursor.pm
CommitLineData
1923c0b4 1package DBIx::Class::Cursor;
2
3use strict;
4use warnings;
5use overload
6 '0+' => 'count',
7 fallback => 1;
8
9sub new {
54644855 10 my ($it_class, $db_class, $sth, $args, $cols, $attrs) = @_;
1923c0b4 11 $sth->execute(@{$args || []}) unless $sth->{Active};
12 my $new = {
13 class => $db_class,
14 sth => $sth,
15 cols => $cols,
54644855 16 args => $args,
17 attrs => $attrs };
1923c0b4 18 return bless ($new, $it_class);
19}
20
21sub 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
29sub count {
54644855 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 }
1923c0b4 42}
43
44sub 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
55sub reset {
56 $_[0]->{sth}->finish if $_[0]->{sth}->{Active};
57 $_[0]->{sth}->execute(@{$_[0]->{args} || []});
58 return $_[0];
59}
60
61sub first {
62 return $_[0]->reset->next;
63}
64
651;