Mostly refactored everything to select/update/delete off storage handle
[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->storage->select($db_class->_table_name,$cols,
15                                         $attrs->{where},$attrs);
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   return unless (@row);
51   $self->{pos}++;
52   return $self->{class}->_row_to_object($self->{cols}, \@row);
53 }
54
55 sub count {
56   my ($self) = @_;
57   return $self->{attrs}{rows} if $self->{attrs}{rows};
58   if (my $cond = $self->{attrs}->{where}) {
59 #warn "Counting ".$$cond;
60     return $self->{class}->count($cond, { bind => $self->{args} });
61   } else {
62     return scalar $_[0]->all; # So inefficient
63   }
64 }
65
66 sub all {
67   my ($self) = @_;
68   $self->reset;
69   my @all;
70   while (my $obj = $self->next) {
71     push(@all, $obj);
72   }
73   $self->reset;
74   return @all;
75 }
76
77 sub reset {
78   my ($self) = @_;
79   $self->{sth}->finish if $self->{sth}->{Active};
80   $self->{pos} = 0;
81   $self->{live_sth} = 0;
82   return $self;
83 }
84
85 sub first {
86   return $_[0]->reset->next;
87 }
88
89 sub delete_all {
90   my ($self) = @_;
91   $_->delete for $self->all;
92   return 1;
93 }
94
95 sub DESTROY {
96   my ($self) = @_;
97   $self->{sth}->finish if $self->{sth}->{Active};
98 }
99
100 1;