|
Revision 21337, 1.2 kB
(checked in by nekokak, 5 years ago)
|
|
import
|
| Line | |
|---|
| 1 | package DBIx::Skinny::Iterator; |
|---|
| 2 | use strict; |
|---|
| 3 | use warnings; |
|---|
| 4 | use DBIx::Skinny::Row; |
|---|
| 5 | |
|---|
| 6 | sub new { |
|---|
| 7 | my ($class, %args) = @_; |
|---|
| 8 | |
|---|
| 9 | my $self = bless \%args, $class; |
|---|
| 10 | |
|---|
| 11 | $self->reset; |
|---|
| 12 | |
|---|
| 13 | return wantarray ? $self->all : $self; |
|---|
| 14 | } |
|---|
| 15 | |
|---|
| 16 | sub iterator { |
|---|
| 17 | my $self = shift; |
|---|
| 18 | |
|---|
| 19 | my $potition = $self->{_potition} + 1; |
|---|
| 20 | if ( my $row_cache = $self->{_rows_cache}->[$potition] ) { |
|---|
| 21 | $self->{_potition} = $potition; |
|---|
| 22 | return $row_cache; |
|---|
| 23 | } |
|---|
| 24 | |
|---|
| 25 | my $row = $self->{sth}->fetchrow_hashref(); |
|---|
| 26 | unless ( $row ) { |
|---|
| 27 | $self->{skinny}->_close_sth($self->{sth}); |
|---|
| 28 | return; |
|---|
| 29 | } |
|---|
| 30 | |
|---|
| 31 | my $obj = DBIx::Skinny::Row->new( |
|---|
| 32 | { |
|---|
| 33 | row_data => $row, |
|---|
| 34 | skinny => $self->{skinny}, |
|---|
| 35 | sql_structure => $self->{sql_structure}, |
|---|
| 36 | } |
|---|
| 37 | ); |
|---|
| 38 | $obj->setup; |
|---|
| 39 | |
|---|
| 40 | $self->{_rows_cache}->[$potition] = $obj; |
|---|
| 41 | $self->{_potition} = $potition; |
|---|
| 42 | |
|---|
| 43 | return $obj; |
|---|
| 44 | } |
|---|
| 45 | |
|---|
| 46 | sub first { |
|---|
| 47 | my $self = shift; |
|---|
| 48 | $self->reset; |
|---|
| 49 | $self->next; |
|---|
| 50 | } |
|---|
| 51 | |
|---|
| 52 | sub next { |
|---|
| 53 | my $self = shift; |
|---|
| 54 | $self->iterator; |
|---|
| 55 | } |
|---|
| 56 | |
|---|
| 57 | sub all { |
|---|
| 58 | my $self = shift; |
|---|
| 59 | my @result; |
|---|
| 60 | while ( my $row = $self->next ) { |
|---|
| 61 | push @result, $row; |
|---|
| 62 | } |
|---|
| 63 | return @result; |
|---|
| 64 | } |
|---|
| 65 | |
|---|
| 66 | sub reset { |
|---|
| 67 | my $self = shift; |
|---|
| 68 | $self->{_potition} = 0; |
|---|
| 69 | return $self; |
|---|
| 70 | } |
|---|
| 71 | |
|---|
| 72 | 1; |
|---|
| 73 | |
|---|