package IPC::SharedHash::DBDSQLite; use strict; use warnings; use DBI; use DBD::SQLite; use Storable qw(nfreeze thaw); my $DB_NAME = 'SQLite'; sub new { my $class = shift; my $self = {}; my %options = @_; $self->{'SCALARS_ONLY'} = 1; my $dbh = DBI->connect_cached( 'dbi:SQLite:dbname=' . $options{'DIRECTORY'} . '/' . $DB_NAME, '', '', { AutoCommit => 0 }) || die; $dbh->{'RaiseError'} = 1; $dbh->do('PRAGMA synchronous = OFF'); unless ( $dbh->tables( '', '', 'shared_hash', '' ) ) { $dbh->do( 'create table shared_hash ( a_key text primary key, value text )'); } my $fetch_sth = $dbh->prepare('select value from shared_hash where a_key = ?'); my $store_sth = $dbh->prepare('replace into shared_hash (a_key, value) values (?, ?)'); $self->{'dbh'} = $dbh; $self->{'fetch'} = $fetch_sth; $self->{'store'} = $store_sth; bless $self, $class; return $self; } sub fetch { my $self = shift; my ($key) = @_; $self->{'fetch'}->execute($key); my $value; $self->{'fetch'}->bind_columns( \$value ); $self->{'fetch'}->fetch(); $self->{'fetch'}->finish(); if ( $self->{'SCALARS_ONLY'} ) { return $value; } else { if ( defined $value ) { return thaw($value); } } } sub store { my $self = shift; my ( $key, $value ) = @_; if ( !$self->{'SCALARS_ONLY'} ) { warn $self->{'SCALARS_ONLY'}; $value = nfreeze($value); } $self->{'store'}->execute( $key, $value ); $self->{'dbh'}->commit(); } sub DESTROY { my $self = shift; $self->{'dbh'}->disconnect(); } 1; #### #!/usr/bin/perl use strict; use warnings; use IPC::SharedHash::DBDSQLite; my $hash = IPC::SharedHash::DBDSQLite->new( DIRECTORY => '/tmp', SCALARS_ONLY => 1, ); for ( 0 .. 10000 ) { $hash->store( "key$_", $_ ); my $return = $hash->fetch("key$_"); die "bad return: $return" unless $return == $_; }