From: Dobrica Pavlinusic Date: Tue, 15 Mar 2011 22:47:25 +0000 (+0000) Subject: read data from RDBMS using DBI X-Git-Url: http://git.rot13.org/?p=webpac2;a=commitdiff_plain;h=508a36bde71146738048b441cc7d11be2105828f read data from RDBMS using DBI git-svn-id: svn+ssh://mjesec/home/dpavlin/svn/webpac2/trunk@1359 07558da8-63fa-0310-ba24-9fe276d99e06 --- diff --git a/lib/WebPAC/Input/DBI.pm b/lib/WebPAC/Input/DBI.pm new file mode 100644 index 0000000..52484b1 --- /dev/null +++ b/lib/WebPAC/Input/DBI.pm @@ -0,0 +1,124 @@ +package WebPAC::Input::DBI; + +use warnings; +use strict; + +use WebPAC::Input; +use base qw/WebPAC::Common Class::Accessor/; +__PACKAGE__->mk_accessors(qw( + dsn + user + passwd + path +)); + +use Encode; +use Data::Dump qw/dump/; +use DBI; +use File::Slurp; + +=head1 NAME + +WebPAC::Input::DBI - read data from RDBMS using DBI + +=cut + +=head1 FUNCTIONS + +=head2 new + + my $input = new WebPAC::Input::DBI( + dsn => 'dbi:SQLite:dbname=/dev/shm/test.sqlite', + user => '', + passwd => '', + path => '/path/to.sql', + ); + +=back + +=cut + +sub new { + my $class = shift; + my $self = {@_}; + bless($self, $class); + + my $arg = {@_}; + + my $sql = read_file $self->path; + + my $log = $self->_get_logger; + $log->debug( "dsn: ", $self->dsn ); + + my $dbh = DBI->connect( $self->dsn, $self->user, $self->passwd, { RaiseError => 1 } ); + + $log->debug( "sql ",$self->path, "\n", $sql ); + + my $sth = $dbh->prepare( $sql ); + $sth->execute; + + # XXX this should really be in fetch_rec, but DBD::SQLite doesn't return + # $sth->rows correctly, and we really need number of rows... + $self->{size} = 0; + + while ( my $row = $sth->fetchrow_hashref ) { + push @{ $self->{_rec} }, $row; + $self->{size}++; + } + + $log->info( $self->dsn, " query produced ", $self->size, " records"); + + $self ? return $self : return undef; +} + +=head2 fetch_rec + +Return record with ID C<$mfn> from database + + my $rec = $input->fetch_rec( $mfn, $filter_coderef ); + +=head3 FIXME + +Records are always returned sequentially, ignoring C<$mfn> and filter + +=cut + +sub fetch_rec { + my ( $self, $mfn, $filter_coderef ) = @_; + + my $rec = { '000' => [ $mfn ] }; + my $row = $self->{_rec}->[$mfn-1] || die "no record $mfn"; + foreach my $c ( keys %$row ) { + $rec->{$c} = [ $row->{$c} ]; + } + return $rec; +} + + +=head2 size + +Return number of records in database + + my $size = $input->size; + +=cut + +sub size { + my $self = shift; + return $self->{size}; +} + +=head1 AUTHOR + +Dobrica Pavlinusic, C<< >> + +=head1 COPYRIGHT & LICENSE + +Copyright 2011 Dobrica Pavlinusic, All Rights Reserved. + +This program is free software; you can redistribute it and/or modify it +under the same terms as Perl itself. + +=cut + +1; # End of WebPAC::Input::DBI