Removed finish in Cursor::next, not necessary because the sth is already at the end...
[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) = @_;
525035fb 11 #use Data::Dumper; warn Dumper(@_);
12 $it_class = ref $it_class if ref $it_class;
13 unless ($sth) {
14 $sth = $db_class->_get_sth('select', $cols,
15 $db_class->_table_name, $attrs->{where});
16 }
1923c0b4 17 my $new = {
18 class => $db_class,
19 sth => $sth,
20 cols => $cols,
54644855 21 args => $args,
525035fb 22 pos => 0,
54644855 23 attrs => $attrs };
1923c0b4 24 return bless ($new, $it_class);
25}
26
525035fb 27sub slice {
28 my ($self, $min, $max) = @_;
29 my $attrs = { %{ $self->{attrs} || {} } };
30 $self->{class}->throw("Can't slice without where") unless $attrs->{where};
31 $attrs->{offset} = $min;
32 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
33 my $slice = $self->new($self->{class}, undef, $self->{args},
34 $self->{cols}, $attrs);
35 return (wantarray ? $slice->all : $slice);
36}
37
1923c0b4 38sub next {
39 my ($self) = @_;
525035fb 40 return if $self->{attrs}{rows}
41 && $self->{pos} >= $self->{attrs}{rows}; # + $self->{attrs}{offset});
42 unless ($self->{live_sth}) {
43 $self->{sth}->execute(@{$self->{args} || []});
44 if (my $offset = $self->{attrs}{offset}) {
45 $self->{sth}->fetchrow_array for 1 .. $offset;
46 }
47 $self->{live_sth} = 1;
48 }
1923c0b4 49 my @row = $self->{sth}->fetchrow_array;
c23835c4 50 return unless (@row);
525035fb 51 $self->{pos}++;
1923c0b4 52 return $self->{class}->_row_to_object($self->{cols}, \@row);
53}
54
55sub count {
54644855 56 my ($self) = @_;
525035fb 57 return $self->{attrs}{rows} if $self->{attrs}{rows};
54644855 58 if (my $cond = $self->{attrs}->{where}) {
59 my $class = $self->{class};
60 my $sth = $class->_get_sth( 'select', [ 'COUNT(*)' ],
61 $class->_table_name, $cond);
2840de8f 62 my ($count) = $class->_get_dbh->selectrow_array(
63 $sth, undef, @{$self->{args} || []});
54644855 64 return $count;
65 } else {
66 return scalar $_[0]->all; # So inefficient
67 }
1923c0b4 68}
69
70sub all {
71 my ($self) = @_;
72 $self->reset;
73 my @all;
74 while (my $obj = $self->next) {
75 push(@all, $obj);
76 }
77 $self->reset;
78 return @all;
79}
80
81sub reset {
525035fb 82 my ($self) = @_;
83 $self->{sth}->finish if $self->{sth}->{Active};
84 $self->{pos} = 0;
85 $self->{live_sth} = 0;
86 return $self;
1923c0b4 87}
88
89sub first {
90 return $_[0]->reset->next;
91}
92
525035fb 93sub delete_all {
94 my ($self) = @_;
95 $_->delete for $self->all;
96 return 1;
97}
98
1923c0b4 991;