Factored common cdbi rel features out into Relationship:: packages
[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   #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   }
17   my $new = {
18     class => $db_class,
19     sth => $sth,
20     cols => $cols,
21     args => $args,
22     pos => 0,
23     attrs => $attrs };
24   return bless ($new, $it_class);
25 }
26
27 sub 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
38 sub next {
39   my ($self) = @_;
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   }
49   my @row = $self->{sth}->fetchrow_array;
50   unless (@row) {
51     $self->{sth}->finish if $self->{sth}->{Active};
52     return;
53   }
54   $self->{pos}++;
55   return $self->{class}->_row_to_object($self->{cols}, \@row);
56 }
57
58 sub count {
59   my ($self) = @_;
60   return $self->{attrs}{rows} if $self->{attrs}{rows};
61   if (my $cond = $self->{attrs}->{where}) {
62     my $class = $self->{class};
63     my $sth = $class->_get_sth( 'select', [ 'COUNT(*)' ],
64                                   $class->_table_name, $cond);
65     my ($count) = $class->_get_dbh->selectrow_array(
66                                       $sth, undef, @{$self->{args} || []});
67     return $count;
68   } else {
69     return scalar $_[0]->all; # So inefficient
70   }
71 }
72
73 sub all {
74   my ($self) = @_;
75   $self->reset;
76   my @all;
77   while (my $obj = $self->next) {
78     push(@all, $obj);
79   }
80   $self->reset;
81   return @all;
82 }
83
84 sub reset {
85   my ($self) = @_;
86   $self->{sth}->finish if $self->{sth}->{Active};
87   $self->{pos} = 0;
88   $self->{live_sth} = 0;
89   return $self;
90 }
91
92 sub first {
93   return $_[0]->reset->next;
94 }
95
96 sub delete_all {
97   my ($self) = @_;
98   $_->delete for $self->all;
99   return 1;
100 }
101
102 1;