1package AI::Categorizer::Collection::DBI; 2use strict; 3 4use DBI; 5use AI::Categorizer::Collection; 6use base qw(AI::Categorizer::Collection); 7 8use Params::Validate qw(:types); 9 10__PACKAGE__->valid_params 11 ( 12 connection_string => {type => SCALAR, default => undef}, 13 dbh => {isa => 'DBI::db', default => undef}, 14 select_statement => {type => SCALAR, default => "SELECT text FROM documents"}, 15 ); 16 17__PACKAGE__->contained_objects 18 ( 19 document => { class => 'AI::Categorizer::Document', 20 delayed => 1 }, 21 ); 22 23sub new { 24 my $class = shift; 25 my $self = $class->SUPER::new(@_); 26 27 die "Must provide 'dbh' or 'connection_string' arguments" 28 unless $self->{dbh} or $self->{connection_string}; 29 30 unless ($self->{dbh}) { 31 $self->{dbh} = DBI->connect($self->{connection_string}, '', '', {RaiseError => 1}) 32 or die DBI->errstr; 33 delete $self->{connection_string}; 34 } 35 36 $self->rewind; 37 return $self; 38} 39 40sub dbh { shift()->{dbh} } 41 42sub rewind { 43 my $self = shift; 44 45 if (!$self->{sth}) { 46 $self->{sth} = $self->dbh->prepare($self->{select_statement}); 47 } 48 49 if ($self->{sth}{Active}) { 50 $self->{sth}->finish; 51 } 52 53 $self->{sth}->execute; 54} 55 56sub next { 57 my $self = shift; 58 59 my @result = $self->{sth}->fetchrow_array; 60 return undef unless @result; 61 62 return $self->create_delayed_object('document', 63 name => $result[0], 64 categories => [$result[1]], 65 content => $result[2], 66 ); 67} 68 691; 70