--- trunk/lib/Frey/Collection.pm 2008/07/13 16:15:45 110 +++ trunk/lib/Frey/Collection.pm 2008/07/13 16:17:34 111 @@ -3,40 +3,62 @@ use Data::Dump qw/dump/; use Carp; +use Data::Page; + +sub total_rows { + my $self = shift; + my $table = $self->_table; + my $count = Fey::Literal::Function->new( 'COUNT', $table->column('id') ); # FIXME id? + my $select = $self->_sql->select( $count )->from( $self->_table ); + my $dbh = $self->_dbh($select); + my $sth = $dbh->prepare( $select->sql($dbh) ); + $sth->execute; + return $sth->fetchrow_arrayref->[0]; +} + +sub _table { + my $self = shift; + return $self->SchemaClass()->Schema()->table( $self->collection_table ); +} + +sub _sql { + my $self = shift; + return $self->SchemaClass()->SQLFactoryClass()->new_select(); +} sub collection { - my ( $class, $args ) = @_; + my ( $self, $args ) = @_; croak "expect HASH not ",dump( $args ) unless ref($args) eq 'HASH'; warn "## collection args = ",dump( $args ); - my $schema = $class->SchemaClass()->Schema(); - my $select = $class->SchemaClass()->SQLFactoryClass()->new_select(); - - my $table = $class->collection_table; - - warn "## table $table"; + my $pager = Data::Page->new; + $pager->total_entries( $self->total_rows ); + $pager->entries_per_page( $args->{per_page} || 20 ); + $pager->current_page( $args->{page} || 1 ); - my $users_t = $schema->table( $table ); + my $users_t = $self->_table; - $select->select( $users_t ) + my $select = $self->_sql->select( $users_t ) ->from( $users_t ) # ->where( $message_t->column('message_date'), '>=', # DateTime->today()->subtract( days => 7 )->strftime( '%Y-%m-%d' ) ) - ->limit( $args->{limit} || 20, $args->{offset} || 0 ) + ->limit( $pager->entries_per_page, $pager->skipped ) ; - my $dbh = $class->_dbh($select); - + my $dbh = $self->_dbh($select); my $sth = $dbh->prepare( $select->sql($dbh) ); - return + my $i = Fey::Object::Iterator->new( - classes => [ $class->meta()->ClassForTable( $users_t ) ], + classes => [ $self->meta()->ClassForTable( $users_t ) ], handle => $sth, bind_params => [ $select->bind_params() ], ); + + return ( $i, $pager ) if wantarray; + return $i; } 1;