8 our $VERSION = q(1.0004);
10 use Fcntl qw( :flock );
14 use FileHandle::Fmode ();
17 use DBM::Deep::Engine;
21 # Setup constants for users to pass to new()
23 sub TYPE_HASH () { DBM::Deep::Engine->SIG_HASH }
24 sub TYPE_ARRAY () { DBM::Deep::Engine->SIG_ARRAY }
26 # This is used in all the children of this class in their TIE<type> methods.
33 $proto->_throw_error( "Odd number of parameters to " . (caller(1))[2] );
38 unless ( eval { local $SIG{'__DIE__'}; %{$_[0]} || 1 } ) {
39 $proto->_throw_error( "Not a hashref in args to " . (caller(1))[2] );
44 $args = { file => shift };
52 # Class constructor method for Perl OO interface.
53 # Calls tie() and returns blessed reference to tied hash or array,
54 # providing a hybrid OO/tie interface.
57 my $args = $class->_get_args( @_ );
60 # Check if we want a tied hash or array.
63 if (defined($args->{type}) && $args->{type} eq TYPE_ARRAY) {
64 $class = 'DBM::Deep::Array';
65 require DBM::Deep::Array;
66 tie @$self, $class, %$args;
69 $class = 'DBM::Deep::Hash';
70 require DBM::Deep::Hash;
71 tie %$self, $class, %$args;
74 return bless $self, $class;
77 # This initializer is called from the various TIE* methods. new() calls tie(),
78 # which allows for a single point of entry.
83 $args->{storage} = DBM::Deep::File->new( $args )
84 unless exists $args->{storage};
86 # locking implicitly enables autoflush
87 if ($args->{locking}) { $args->{autoflush} = 1; }
89 # These are the defaults to be optionally overridden below
99 $args->{engine} = DBM::Deep::Engine->new( { %{$args}, obj => $self } )
100 unless exists $args->{engine};
102 # Grab the parameters we want to use
103 foreach my $param ( keys %$self ) {
104 next unless exists $args->{$param};
105 $self->{$param} = $args->{$param};
109 local $SIG{'__DIE__'};
112 $self->_engine->setup_fh( $self );
113 $self->_storage->set_inode;
117 eval { local $SIG{'__DIE__'}; $self->unlock; };
126 require DBM::Deep::Hash;
127 return DBM::Deep::Hash->TIEHASH( @_ );
132 require DBM::Deep::Array;
133 return DBM::Deep::Array->TIEARRAY( @_ );
137 my $self = shift->_get_self;
138 return $self->_storage->lock( $self, @_ );
142 my $self = shift->_get_self;
143 return $self->_storage->unlock( $self, @_ );
147 my $self = shift->_get_self;
148 my ($spot, $value) = @_;
153 elsif ( eval { local $SIG{__DIE__}; $value->isa( 'DBM::Deep' ) } ) {
154 ${$spot} = $value->_repr;
155 $value->_copy_node( ${$spot} );
158 my $r = Scalar::Util::reftype( $value );
159 my $c = Scalar::Util::blessed( $value );
160 if ( $r eq 'ARRAY' ) {
161 ${$spot} = [ @{$value} ];
164 ${$spot} = { %{$value} };
166 ${$spot} = bless ${$spot}, $c
174 # die "Must be implemented in a child class\n";
178 # die "Must be implemented in a child class\n";
183 # Recursively export into standard Perl hashes and arrays.
185 my $self = shift->_get_self;
187 my $temp = $self->_repr;
190 $self->_copy_node( $temp );
193 my $classname = $self->_engine->get_classname( $self );
194 if ( defined $classname ) {
195 bless $temp, $classname;
203 # Recursively import Perl hash/array structure
205 if (!ref($_[0])) { return; } # Perl calls import() on use -- ignore
207 my $self = shift->_get_self;
210 # struct is not a reference, so just import based on our type
212 $struct = $self->_repr( @_ );
215 #XXX This isn't the best solution. Better would be to use Data::Walker,
216 #XXX but that's a lot more thinking than I want to do right now.
218 local $SIG{'__DIE__'};
219 $self->_import( Clone::clone( $struct ) );
220 }; if ( my $e = $@ ) {
227 #XXX Need to keep track of who has a fh to this file in order to
228 #XXX close them all prior to optimize on Win32/cygwin
231 # Rebuild entire database into new file, then move
232 # it back on top of original.
234 my $self = shift->_get_self;
236 #XXX Need to create a new test for this
237 # if ($self->_storage->{links} > 1) {
238 # $self->_throw_error("Cannot optimize: reference count is greater than 1");
241 #XXX Do we have to lock the tempfile?
243 my $db_temp = DBM::Deep->new(
244 file => $self->_storage->{file} . '.tmp',
245 type => $self->_type,
247 # Bring over all the parameters that we need to bring over
248 num_txns => $self->_engine->num_txns,
249 byte_size => $self->_engine->byte_size,
250 max_buckets => $self->_engine->max_buckets,
254 $self->_copy_node( $db_temp );
258 # Attempt to copy user, group and permissions over to new file
260 my @stats = stat($self->_fh);
261 my $perms = $stats[2] & 07777;
264 chown( $uid, $gid, $self->_storage->{file} . '.tmp' );
265 chmod( $perms, $self->_storage->{file} . '.tmp' );
267 # q.v. perlport for more information on this variable
268 if ( $^O eq 'MSWin32' || $^O eq 'cygwin' ) {
270 # Potential race condition when optmizing on Win32 with locking.
271 # The Windows filesystem requires that the filehandle be closed
272 # before it is overwritten with rename(). This could be redone
276 $self->_storage->close;
279 if (!rename $self->_storage->{file} . '.tmp', $self->_storage->{file}) {
280 unlink $self->_storage->{file} . '.tmp';
282 $self->_throw_error("Optimize failed: Cannot copy temp file over original: $!");
286 $self->_storage->close;
288 $self->_storage->open;
290 $self->_engine->setup_fh( $self );
298 # Make copy of object and return
300 my $self = shift->_get_self;
302 return DBM::Deep->new(
303 type => $self->_type,
304 base_offset => $self->_base_offset,
305 staleness => $self->_staleness,
306 storage => $self->_storage,
307 engine => $self->_engine,
311 #XXX Migrate this to the engine, where it really belongs and go through some
312 # API - stop poking in the innards of someone else..
314 my %is_legal_filter = map {
317 store_key store_value
318 fetch_key fetch_value
323 # Setup filter function for storing or fetching the key or value
325 my $self = shift->_get_self;
329 if ( $is_legal_filter{$type} ) {
330 $self->_storage->{"filter_$type"} = $func;
337 sub filter_store_key { $_[0]->set_filter( store_key => $_[1] ); }
338 sub filter_store_value { $_[0]->set_filter( store_value => $_[1] ); }
339 sub filter_fetch_key { $_[0]->set_filter( fetch_key => $_[1] ); }
340 sub filter_fetch_value { $_[0]->set_filter( fetch_value => $_[1] ); }
344 my $self = shift->_get_self;
345 return $self->_engine->begin_work( $self, @_ );
349 my $self = shift->_get_self;
350 return $self->_engine->rollback( $self, @_ );
354 my $self = shift->_get_self;
355 return $self->_engine->commit( $self, @_ );
363 my $self = $_[0]->_get_self;
364 return $self->{engine};
368 my $self = $_[0]->_get_self;
369 return $self->{storage};
373 my $self = $_[0]->_get_self;
374 return $self->{type};
378 my $self = $_[0]->_get_self;
379 return $self->{base_offset};
383 my $self = $_[0]->_get_self;
384 return $self->{staleness};
388 my $self = $_[0]->_get_self;
389 return $self->_storage->{fh};
397 die "DBM::Deep: $_[1]\n";
400 my @caller = caller( ++$n );
401 next if $caller[0] =~ m/^DBM::Deep/;
403 die "DBM::Deep: $_[1] at $0 line $caller[2]\n";
410 # Store single hash key/value or array element in database.
412 my $self = shift->_get_self;
413 my ($key, $value) = @_;
415 if ( !FileHandle::Fmode::is_W( $self->_fh ) ) {
416 $self->_throw_error( 'Cannot write to a readonly filehandle' );
420 # Request exclusive lock for writing
422 $self->lock( LOCK_EX );
424 # User may be storing a complex value, in which case we do not want it run
425 # through the filtering system.
426 if ( !ref($value) && $self->_storage->{filter_store_value} ) {
427 $value = $self->_storage->{filter_store_value}->( $value );
430 $self->_engine->write_value( $self, $key, $value);
439 # Fetch single value or element given plain key or array index
441 my $self = shift->_get_self;
445 # Request shared lock for reading
447 $self->lock( LOCK_SH );
449 my $result = $self->_engine->read_value( $self, $key);
453 # Filters only apply to scalar values, so the ref check is making
454 # sure the fetched bucket is a scalar, not a child hash or array.
455 return ($result && !ref($result) && $self->_storage->{filter_fetch_value})
456 ? $self->_storage->{filter_fetch_value}->($result)
462 # Delete single key/value pair or element given plain key or array index
464 my $self = shift->_get_self;
467 if ( !FileHandle::Fmode::is_W( $self->_fh ) ) {
468 $self->_throw_error( 'Cannot write to a readonly filehandle' );
472 # Request exclusive lock for writing
474 $self->lock( LOCK_EX );
479 my $value = $self->_engine->delete_key( $self, $key);
481 if (defined $value && !ref($value) && $self->_storage->{filter_fetch_value}) {
482 $value = $self->_storage->{filter_fetch_value}->($value);
492 # Check if a single key or element exists given plain key or array index
494 my $self = shift->_get_self;
498 # Request shared lock for reading
500 $self->lock( LOCK_SH );
502 my $result = $self->_engine->key_exists( $self, $key );
511 # Clear all keys from hash, or all elements from array.
513 my $self = shift->_get_self;
515 if ( !FileHandle::Fmode::is_W( $self->_fh ) ) {
516 $self->_throw_error( 'Cannot write to a readonly filehandle' );
520 # Request exclusive lock for writing
522 $self->lock( LOCK_EX );
524 #XXX Rewrite this dreck to do it in the engine as a tight loop vs.
525 # iterating over keys - such a WASTE - is this required for transactional
526 # clearning?! Surely that can be detected in the engine ...
527 if ( $self->_type eq TYPE_HASH ) {
528 my $key = $self->first_key;
530 # Retrieve the key before deleting because we depend on next_key
531 my $next_key = $self->next_key( $key );
532 $self->_engine->delete_key( $self, $key, $key );
537 my $size = $self->FETCHSIZE;
538 for my $key ( 0 .. $size - 1 ) {
539 $self->_engine->delete_key( $self, $key, $key );
541 $self->STORESIZE( 0 );
550 # Public method aliases
552 sub put { (shift)->STORE( @_ ) }
553 sub store { (shift)->STORE( @_ ) }
554 sub get { (shift)->FETCH( @_ ) }
555 sub fetch { (shift)->FETCH( @_ ) }
556 sub delete { (shift)->DELETE( @_ ) }
557 sub exists { (shift)->EXISTS( @_ ) }
558 sub clear { (shift)->CLEAR( @_ ) }
560 sub _dump_file {shift->_get_self->_engine->_dump_file;}