8 our $VERSION = q(1.0006);
10 use Fcntl qw( :flock );
13 use FileHandle::Fmode ();
16 use DBM::Deep::Engine;
20 '""' => sub { overload::StrVal( $_[0] ) },
24 # Setup constants for users to pass to new()
26 sub TYPE_HASH () { DBM::Deep::Engine->SIG_HASH }
27 sub TYPE_ARRAY () { DBM::Deep::Engine->SIG_ARRAY }
29 # This is used in all the children of this class in their TIE<type> methods.
36 $proto->_throw_error( "Odd number of parameters to " . (caller(1))[2] );
41 unless ( eval { local $SIG{'__DIE__'}; %{$_[0]} || 1 } ) {
42 $proto->_throw_error( "Not a hashref in args to " . (caller(1))[2] );
47 $args = { file => shift };
55 # Class constructor method for Perl OO interface.
56 # Calls tie() and returns blessed reference to tied hash or array,
57 # providing a hybrid OO/tie interface.
60 my $args = $class->_get_args( @_ );
63 # Check if we want a tied hash or array.
66 if (defined($args->{type}) && $args->{type} eq TYPE_ARRAY) {
67 $class = 'DBM::Deep::Array';
68 require DBM::Deep::Array;
69 tie @$self, $class, %$args;
72 $class = 'DBM::Deep::Hash';
73 require DBM::Deep::Hash;
74 tie %$self, $class, %$args;
77 return bless $self, $class;
80 # This initializer is called from the various TIE* methods. new() calls tie(),
81 # which allows for a single point of entry.
86 $args->{storage} = DBM::Deep::File->new( $args )
87 unless exists $args->{storage};
89 # locking implicitly enables autoflush
90 if ($args->{locking}) { $args->{autoflush} = 1; }
92 # These are the defaults to be optionally overridden below
102 $args->{engine} = DBM::Deep::Engine->new( { %{$args}, obj => $self } )
103 unless exists $args->{engine};
105 # Grab the parameters we want to use
106 foreach my $param ( keys %$self ) {
107 next unless exists $args->{$param};
108 $self->{$param} = $args->{$param};
112 local $SIG{'__DIE__'};
115 $self->_engine->setup_fh( $self );
116 $self->_storage->set_inode;
120 eval { local $SIG{'__DIE__'}; $self->unlock; };
129 require DBM::Deep::Hash;
130 return DBM::Deep::Hash->TIEHASH( @_ );
135 require DBM::Deep::Array;
136 return DBM::Deep::Array->TIEARRAY( @_ );
140 my $self = shift->_get_self;
141 return $self->_storage->lock( $self, @_ );
145 my $self = shift->_get_self;
146 return $self->_storage->unlock( $self, @_ );
150 my $self = shift->_get_self;
151 my ($spot, $value) = @_;
156 elsif ( eval { local $SIG{__DIE__}; $value->isa( 'DBM::Deep' ) } ) {
157 ${$spot} = $value->_repr;
158 $value->_copy_node( ${$spot} );
161 my $r = Scalar::Util::reftype( $value );
162 my $c = Scalar::Util::blessed( $value );
163 if ( $r eq 'ARRAY' ) {
164 ${$spot} = [ @{$value} ];
167 ${$spot} = { %{$value} };
169 ${$spot} = bless ${$spot}, $c
177 # die "Must be implemented in a child class\n";
181 # die "Must be implemented in a child class\n";
186 # Recursively export into standard Perl hashes and arrays.
188 my $self = shift->_get_self;
190 my $temp = $self->_repr;
193 $self->_copy_node( $temp );
196 my $classname = $self->_engine->get_classname( $self );
197 if ( defined $classname ) {
198 bless $temp, $classname;
204 sub _check_legality {
208 my $r = Scalar::Util::reftype( $val );
210 return $r if !defined $r || '' eq $r;
211 return $r if 'HASH' eq $r;
212 return $r if 'ARRAY' eq $r;
214 DBM::Deep->_throw_error(
215 "Storage of references of type '$r' is not supported."
220 # Perl calls import() on use -- ignore
221 return if !ref $_[0];
223 my $self = shift->_get_self;
226 my $type = $self->_check_legality( $struct );
228 DBM::Deep->_throw_error( "Cannot import a scalar" );
231 if ( substr( $type, 0, 1 ) ne $self->_type ) {
232 DBM::Deep->_throw_error(
233 "Cannot import " . ('HASH' eq $type ? 'a hash' : 'an array')
234 . " into " . ('HASH' eq $type ? 'an array' : 'a hash')
243 my $obj = 'HASH' eq Scalar::Util::reftype( $db ) ? tied(%$db) : tied(@$db);
246 my $r = $self->_check_legality( $val );
247 if ( 'HASH' eq $r ) {
248 while ( my ($k, $v) = each %$val ) {
249 my $r = $self->_check_legality( $v );
251 my $temp = 'HASH' eq $r ? {} : [];
252 if ( my $c = Scalar::Util::blessed( $v ) ) {
255 $obj->put( $k, $temp );
256 $recurse->( $temp, $v );
263 elsif ( 'ARRAY' eq $r ) {
264 foreach my $k ( 0 .. $#$val ) {
266 my $r = $self->_check_legality( $v );
268 my $temp = 'HASH' eq $r ? {} : [];
269 if ( my $c = Scalar::Util::blessed( $v ) ) {
272 $obj->put( $k, $temp );
273 $recurse->( $temp, $v );
281 $recurse->( $self, $struct );
286 #XXX Need to keep track of who has a fh to this file in order to
287 #XXX close them all prior to optimize on Win32/cygwin
290 # Rebuild entire database into new file, then move
291 # it back on top of original.
293 my $self = shift->_get_self;
295 #XXX Need to create a new test for this
296 # if ($self->_storage->{links} > 1) {
297 # $self->_throw_error("Cannot optimize: reference count is greater than 1");
300 #XXX Do we have to lock the tempfile?
302 #XXX Should we use tempfile() here instead of a hard-coded name?
303 my $db_temp = DBM::Deep->new(
304 file => $self->_storage->{file} . '.tmp',
305 type => $self->_type,
307 # Bring over all the parameters that we need to bring over
308 ( map { $_ => $self->_engine->$_ } qw(
309 byte_size max_buckets data_sector_size num_txns
314 $self->_engine->clear_cache;
315 $self->_copy_node( $db_temp );
319 # Attempt to copy user, group and permissions over to new file
321 my @stats = stat($self->_fh);
322 my $perms = $stats[2] & 07777;
325 chown( $uid, $gid, $self->_storage->{file} . '.tmp' );
326 chmod( $perms, $self->_storage->{file} . '.tmp' );
328 # q.v. perlport for more information on this variable
329 if ( $^O eq 'MSWin32' || $^O eq 'cygwin' ) {
331 # Potential race condition when optmizing on Win32 with locking.
332 # The Windows filesystem requires that the filehandle be closed
333 # before it is overwritten with rename(). This could be redone
337 $self->_storage->close;
340 if (!rename $self->_storage->{file} . '.tmp', $self->_storage->{file}) {
341 unlink $self->_storage->{file} . '.tmp';
343 $self->_throw_error("Optimize failed: Cannot copy temp file over original: $!");
347 $self->_storage->close;
349 $self->_storage->open;
351 $self->_engine->setup_fh( $self );
359 # Make copy of object and return
361 my $self = shift->_get_self;
363 return DBM::Deep->new(
364 type => $self->_type,
365 base_offset => $self->_base_offset,
366 staleness => $self->_staleness,
367 storage => $self->_storage,
368 engine => $self->_engine,
372 #XXX Migrate this to the engine, where it really belongs and go through some
373 # API - stop poking in the innards of someone else..
375 my %is_legal_filter = map {
378 store_key store_value
379 fetch_key fetch_value
383 my $self = shift->_get_self;
387 if ( $is_legal_filter{$type} ) {
388 $self->_storage->{"filter_$type"} = $func;
395 sub filter_store_key { $_[0]->set_filter( store_key => $_[1] ); }
396 sub filter_store_value { $_[0]->set_filter( store_value => $_[1] ); }
397 sub filter_fetch_key { $_[0]->set_filter( fetch_key => $_[1] ); }
398 sub filter_fetch_value { $_[0]->set_filter( fetch_value => $_[1] ); }
402 my $self = shift->_get_self;
403 return $self->_engine->begin_work( $self, @_ );
407 my $self = shift->_get_self;
408 return $self->_engine->rollback( $self, @_ );
412 my $self = shift->_get_self;
413 return $self->_engine->commit( $self, @_ );
421 my $self = $_[0]->_get_self;
422 return $self->{engine};
426 my $self = $_[0]->_get_self;
427 return $self->{storage};
431 my $self = $_[0]->_get_self;
432 return $self->{type};
436 my $self = $_[0]->_get_self;
437 return $self->{base_offset};
441 my $self = $_[0]->_get_self;
442 return $self->{staleness};
446 my $self = $_[0]->_get_self;
447 return $self->_storage->{fh};
457 my @caller = caller( ++$n );
458 next if $caller[0] =~ m/^DBM::Deep/;
460 die "DBM::Deep: $_[1] at $0 line $caller[2]\n";
466 # Store single hash key/value or array element in database.
468 my $self = shift->_get_self;
469 my ($key, $value) = @_;
471 if ( !FileHandle::Fmode::is_W( $self->_fh ) ) {
472 $self->_throw_error( 'Cannot write to a readonly filehandle' );
476 # Request exclusive lock for writing
478 $self->lock( LOCK_EX );
480 # User may be storing a complex value, in which case we do not want it run
481 # through the filtering system.
482 if ( !ref($value) && $self->_storage->{filter_store_value} ) {
483 $value = $self->_storage->{filter_store_value}->( $value );
486 $self->_engine->write_value( $self, $key, $value);
495 # Fetch single value or element given plain key or array index
497 my $self = shift->_get_self;
501 # Request shared lock for reading
503 $self->lock( LOCK_SH );
505 my $result = $self->_engine->read_value( $self, $key);
509 # Filters only apply to scalar values, so the ref check is making
510 # sure the fetched bucket is a scalar, not a child hash or array.
511 return ($result && !ref($result) && $self->_storage->{filter_fetch_value})
512 ? $self->_storage->{filter_fetch_value}->($result)
518 # Delete single key/value pair or element given plain key or array index
520 my $self = shift->_get_self;
523 if ( !FileHandle::Fmode::is_W( $self->_fh ) ) {
524 $self->_throw_error( 'Cannot write to a readonly filehandle' );
528 # Request exclusive lock for writing
530 $self->lock( LOCK_EX );
535 my $value = $self->_engine->delete_key( $self, $key);
537 if (defined $value && !ref($value) && $self->_storage->{filter_fetch_value}) {
538 $value = $self->_storage->{filter_fetch_value}->($value);
548 # Check if a single key or element exists given plain key or array index
550 my $self = shift->_get_self;
554 # Request shared lock for reading
556 $self->lock( LOCK_SH );
558 my $result = $self->_engine->key_exists( $self, $key );
567 # Clear all keys from hash, or all elements from array.
569 my $self = shift->_get_self;
571 if ( !FileHandle::Fmode::is_W( $self->_fh ) ) {
572 $self->_throw_error( 'Cannot write to a readonly filehandle' );
576 # Request exclusive lock for writing
578 $self->lock( LOCK_EX );
580 #XXX Rewrite this dreck to do it in the engine as a tight loop vs.
581 # iterating over keys - such a WASTE - is this required for transactional
582 # clearning?! Surely that can be detected in the engine ...
583 if ( $self->_type eq TYPE_HASH ) {
584 my $key = $self->first_key;
586 # Retrieve the key before deleting because we depend on next_key
587 my $next_key = $self->next_key( $key );
588 $self->_engine->delete_key( $self, $key, $key );
593 my $size = $self->FETCHSIZE;
594 for my $key ( 0 .. $size - 1 ) {
595 $self->_engine->delete_key( $self, $key, $key );
597 $self->STORESIZE( 0 );
606 # Public method aliases
608 sub put { (shift)->STORE( @_ ) }
609 sub store { (shift)->STORE( @_ ) }
610 sub get { (shift)->FETCH( @_ ) }
611 sub fetch { (shift)->FETCH( @_ ) }
612 sub delete { (shift)->DELETE( @_ ) }
613 sub exists { (shift)->EXISTS( @_ ) }
614 sub clear { (shift)->CLEAR( @_ ) }
616 sub _dump_file {shift->_get_self->_engine->_dump_file;}