8 our $VERSION = q(1.0010);
10 use Fcntl qw( :flock );
13 use DBM::Deep::Engine;
17 '""' => sub { overload::StrVal( $_[0] ) },
20 use constant DEBUG => 0;
23 # Setup constants for users to pass to new()
25 sub TYPE_HASH () { DBM::Deep::Engine->SIG_HASH }
26 sub TYPE_ARRAY () { DBM::Deep::Engine->SIG_ARRAY }
28 # This is used in all the children of this class in their TIE<type> methods.
35 $proto->_throw_error( "Odd number of parameters to " . (caller(1))[2] );
40 unless ( eval { local $SIG{'__DIE__'}; %{$_[0]} || 1 } ) {
41 $proto->_throw_error( "Not a hashref in args to " . (caller(1))[2] );
46 $args = { file => shift };
54 # Class constructor method for Perl OO interface.
55 # Calls tie() and returns blessed reference to tied hash or array,
56 # providing a hybrid OO/tie interface.
59 my $args = $class->_get_args( @_ );
62 # Check if we want a tied hash or array.
65 if (defined($args->{type}) && $args->{type} eq TYPE_ARRAY) {
66 $class = 'DBM::Deep::Array';
67 require DBM::Deep::Array;
68 tie @$self, $class, %$args;
71 $class = 'DBM::Deep::Hash';
72 require DBM::Deep::Hash;
73 tie %$self, $class, %$args;
76 return bless $self, $class;
79 # This initializer is called from the various TIE* methods. new() calls tie(),
80 # which allows for a single point of entry.
85 $args->{storage} = DBM::Deep::File->new( $args )
86 unless exists $args->{storage};
88 # locking implicitly enables autoflush
89 if ($args->{locking}) { $args->{autoflush} = 1; }
91 # These are the defaults to be optionally overridden below
101 $args->{engine} = DBM::Deep::Engine->new( { %{$args}, obj => $self } )
102 unless exists $args->{engine};
104 # Grab the parameters we want to use
105 foreach my $param ( keys %$self ) {
106 next unless exists $args->{$param};
107 $self->{$param} = $args->{$param};
111 local $SIG{'__DIE__'};
114 $self->_engine->setup_fh( $self );
115 $self->_storage->set_inode;
119 eval { local $SIG{'__DIE__'}; $self->unlock; };
128 require DBM::Deep::Hash;
129 return DBM::Deep::Hash->TIEHASH( @_ );
134 require DBM::Deep::Array;
135 return DBM::Deep::Array->TIEARRAY( @_ );
139 my $self = shift->_get_self;
140 return $self->_storage->lock( $self, @_ );
144 my $self = shift->_get_self;
145 return $self->_storage->unlock( $self, @_ );
149 my $self = shift->_get_self;
150 my ($spot, $value) = @_;
155 elsif ( eval { local $SIG{__DIE__}; $value->isa( 'DBM::Deep' ) } ) {
156 ${$spot} = $value->_repr;
157 $value->_copy_node( ${$spot} );
160 my $r = Scalar::Util::reftype( $value );
161 my $c = Scalar::Util::blessed( $value );
162 if ( $r eq 'ARRAY' ) {
163 ${$spot} = [ @{$value} ];
166 ${$spot} = { %{$value} };
168 ${$spot} = bless ${$spot}, $c
176 # die "Must be implemented in a child class\n";
180 # die "Must be implemented in a child class\n";
185 # Recursively export into standard Perl hashes and arrays.
187 my $self = shift->_get_self;
189 my $temp = $self->_repr;
192 $self->_copy_node( $temp );
195 my $classname = $self->_engine->get_classname( $self );
196 if ( defined $classname ) {
197 bless $temp, $classname;
203 sub _check_legality {
207 my $r = Scalar::Util::reftype( $val );
209 return $r if !defined $r || '' eq $r;
210 return $r if 'HASH' eq $r;
211 return $r if 'ARRAY' eq $r;
213 DBM::Deep->_throw_error(
214 "Storage of references of type '$r' is not supported."
219 # Perl calls import() on use -- ignore
220 return if !ref $_[0];
222 my $self = shift->_get_self;
225 my $type = $self->_check_legality( $struct );
227 DBM::Deep->_throw_error( "Cannot import a scalar" );
230 if ( substr( $type, 0, 1 ) ne $self->_type ) {
231 DBM::Deep->_throw_error(
232 "Cannot import " . ('HASH' eq $type ? 'a hash' : 'an array')
233 . " into " . ('HASH' eq $type ? 'an array' : 'a hash')
242 my $obj = 'HASH' eq Scalar::Util::reftype( $db ) ? tied(%$db) : tied(@$db);
245 my $r = $self->_check_legality( $val );
246 if ( 'HASH' eq $r ) {
247 while ( my ($k, $v) = each %$val ) {
248 my $r = $self->_check_legality( $v );
250 my $temp = 'HASH' eq $r ? {} : [];
251 if ( my $c = Scalar::Util::blessed( $v ) ) {
254 $obj->put( $k, $temp );
255 $recurse->( $temp, $v );
262 elsif ( 'ARRAY' eq $r ) {
263 foreach my $k ( 0 .. $#$val ) {
265 my $r = $self->_check_legality( $v );
267 my $temp = 'HASH' eq $r ? {} : [];
268 if ( my $c = Scalar::Util::blessed( $v ) ) {
271 $obj->put( $k, $temp );
272 $recurse->( $temp, $v );
280 $recurse->( $self, $struct );
285 #XXX Need to keep track of who has a fh to this file in order to
286 #XXX close them all prior to optimize on Win32/cygwin
289 # Rebuild entire database into new file, then move
290 # it back on top of original.
292 my $self = shift->_get_self;
294 #XXX Need to create a new test for this
295 # if ($self->_storage->{links} > 1) {
296 # $self->_throw_error("Cannot optimize: reference count is greater than 1");
299 #XXX Do we have to lock the tempfile?
301 #XXX Should we use tempfile() here instead of a hard-coded name?
302 my $temp_filename = $self->_storage->{file} . '.tmp';
303 my $db_temp = DBM::Deep->new(
304 file => $temp_filename,
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 $self->_storage->copy_stats( $temp_filename );
323 # q.v. perlport for more information on this variable
324 if ( $^O eq 'MSWin32' || $^O eq 'cygwin' ) {
326 # Potential race condition when optmizing on Win32 with locking.
327 # The Windows filesystem requires that the filehandle be closed
328 # before it is overwritten with rename(). This could be redone
332 $self->_storage->close;
335 if (!rename $temp_filename, $self->_storage->{file}) {
336 unlink $temp_filename;
338 $self->_throw_error("Optimize failed: Cannot copy temp file over original: $!");
342 $self->_storage->close;
344 $self->_storage->open;
346 $self->_engine->setup_fh( $self );
354 # Make copy of object and return
356 my $self = shift->_get_self;
358 return DBM::Deep->new(
359 type => $self->_type,
360 base_offset => $self->_base_offset,
361 staleness => $self->_staleness,
362 storage => $self->_storage,
363 engine => $self->_engine,
367 #XXX Migrate this to the engine, where it really belongs and go through some
368 # API - stop poking in the innards of someone else..
370 my %is_legal_filter = map {
373 store_key store_value
374 fetch_key fetch_value
378 my $self = shift->_get_self;
382 if ( $is_legal_filter{$type} ) {
383 $self->_storage->{"filter_$type"} = $func;
390 sub filter_store_key { $_[0]->set_filter( store_key => $_[1] ); }
391 sub filter_store_value { $_[0]->set_filter( store_value => $_[1] ); }
392 sub filter_fetch_key { $_[0]->set_filter( fetch_key => $_[1] ); }
393 sub filter_fetch_value { $_[0]->set_filter( fetch_value => $_[1] ); }
397 my $self = shift->_get_self;
398 return $self->_engine->begin_work( $self, @_ );
402 my $self = shift->_get_self;
403 return $self->_engine->rollback( $self, @_ );
407 my $self = shift->_get_self;
408 return $self->_engine->commit( $self, @_ );
416 my $self = $_[0]->_get_self;
417 return $self->{engine};
421 my $self = $_[0]->_get_self;
422 return $self->{storage};
426 my $self = $_[0]->_get_self;
427 return $self->{type};
431 my $self = $_[0]->_get_self;
432 return $self->{base_offset};
436 my $self = $_[0]->_get_self;
437 return $self->{staleness};
447 my @caller = caller( ++$n );
448 next if $caller[0] =~ m/^DBM::Deep/;
450 die "DBM::Deep: $_[1] at $0 line $caller[2]\n";
456 # Store single hash key/value or array element in database.
458 my $self = shift->_get_self;
459 my ($key, $value) = @_;
460 warn "STORE($self, $key, $value)\n" if DEBUG;
462 unless ( $self->_storage->is_writable ) {
463 $self->_throw_error( 'Cannot write to a readonly filehandle' );
467 # Request exclusive lock for writing
469 $self->lock( LOCK_EX );
471 # User may be storing a complex value, in which case we do not want it run
472 # through the filtering system.
473 if ( !ref($value) && $self->_storage->{filter_store_value} ) {
474 $value = $self->_storage->{filter_store_value}->( $value );
477 $self->_engine->write_value( $self, $key, $value);
486 # Fetch single value or element given plain key or array index
488 my $self = shift->_get_self;
490 warn "FETCH($self,$key)\n" if DEBUG;
493 # Request shared lock for reading
495 $self->lock( LOCK_SH );
497 my $result = $self->_engine->read_value( $self, $key);
501 # Filters only apply to scalar values, so the ref check is making
502 # sure the fetched bucket is a scalar, not a child hash or array.
503 return ($result && !ref($result) && $self->_storage->{filter_fetch_value})
504 ? $self->_storage->{filter_fetch_value}->($result)
510 # Delete single key/value pair or element given plain key or array index
512 my $self = shift->_get_self;
514 warn "DELETE($self,$key)\n" if DEBUG;
516 unless ( $self->_storage->is_writable ) {
517 $self->_throw_error( 'Cannot write to a readonly filehandle' );
521 # Request exclusive lock for writing
523 $self->lock( LOCK_EX );
528 my $value = $self->_engine->delete_key( $self, $key);
530 if (defined $value && !ref($value) && $self->_storage->{filter_fetch_value}) {
531 $value = $self->_storage->{filter_fetch_value}->($value);
541 # Check if a single key or element exists given plain key or array index
543 my $self = shift->_get_self;
545 warn "EXISTS($self,$key)\n" if DEBUG;
548 # Request shared lock for reading
550 $self->lock( LOCK_SH );
552 my $result = $self->_engine->key_exists( $self, $key );
561 # Clear all keys from hash, or all elements from array.
563 my $self = shift->_get_self;
564 warn "CLEAR($self)\n" if DEBUG;
566 unless ( $self->_storage->is_writable ) {
567 $self->_throw_error( 'Cannot write to a readonly filehandle' );
571 # Request exclusive lock for writing
573 $self->lock( LOCK_EX );
575 #XXX Rewrite this dreck to do it in the engine as a tight loop vs.
576 # iterating over keys - such a WASTE - is this required for transactional
577 # clearning?! Surely that can be detected in the engine ...
578 if ( $self->_type eq TYPE_HASH ) {
579 my $key = $self->first_key;
581 # Retrieve the key before deleting because we depend on next_key
582 my $next_key = $self->next_key( $key );
583 $self->_engine->delete_key( $self, $key, $key );
588 my $size = $self->FETCHSIZE;
589 for my $key ( 0 .. $size - 1 ) {
590 $self->_engine->delete_key( $self, $key, $key );
592 $self->STORESIZE( 0 );
601 # Public method aliases
603 sub put { (shift)->STORE( @_ ) }
604 sub store { (shift)->STORE( @_ ) }
605 sub get { (shift)->FETCH( @_ ) }
606 sub fetch { (shift)->FETCH( @_ ) }
607 sub delete { (shift)->DELETE( @_ ) }
608 sub exists { (shift)->EXISTS( @_ ) }
609 sub clear { (shift)->CLEAR( @_ ) }
611 sub _dump_file {shift->_get_self->_engine->_dump_file;}