6 use warnings FATAL => 'all';
8 our $VERSION = q(1.0014);
13 use DBM::Deep::Engine;
16 use DBM::Deep::SQL::Util;
17 use DBM::Deep::SQL::Array;
18 use DBM::Deep::SQL::Hash;
21 '""' => sub { overload::StrVal( $_[0] ) },
24 use constant DEBUG => 0;
27 # Setup constants for users to pass to new()
29 sub TYPE_HASH () { DBM::Deep::Engine->SIG_HASH }
30 sub TYPE_ARRAY () { DBM::Deep::Engine->SIG_ARRAY }
32 # This is used in all the children of this class in their TIE<type> methods.
39 $proto->_throw_error( "Odd number of parameters to " . (caller(1))[2] );
44 unless ( eval { local $SIG{'__DIE__'}; %{$_[0]} || 1 } ) {
45 $proto->_throw_error( "Not a hashref in args to " . (caller(1))[2] );
50 $args = { file => shift };
58 # Class constructor method for Perl OO interface.
59 # Calls tie() and returns blessed reference to tied hash or array,
60 # providing a hybrid OO/tie interface.
63 my $args = $class->_get_args( @_ );
67 # Check for SQL storage
69 if (exists $args->{dbi}) {
71 require DBIx::Abstract;
73 DBM::Deep->_throw_error('DBIx::Abstract not installed. You cannot use the SQL mode.');
75 unless (UNIVERSAL::isa($args->{dbi}, 'DBIx::Abstract')) {
76 $args->{dbi} = DBIx::Abstract->connect($args->{dbi});
79 if (defined $args->{id}) {
80 unless ($args->{id} =~ /^\d+$/ && $args->{id} > 0) {
81 DBM::Deep->_throw_error('Invalid SQL record id');
83 my $util = {dbi => $args->{dbi}};
84 bless $util, 'DBM::Deep::SQL::Util';
85 my $q = $util->_select(
87 fields => 'item_type',
88 where => {id => $args->{id}},
90 if ($q->[0]->[0] eq 'array') {
91 $args->{type} = TYPE_ARRAY;
93 elsif ($q->[0]->[0] eq 'hash') {
94 $args->{type} = TYPE_HASH;
97 DBM::Deep->_throw_error('Unknown SQL record id');
101 my $util = {dbi => $args->{dbi}};
102 bless $util, 'DBM::Deep::SQL::Util';
103 if (defined($args->{type}) && $args->{type} eq TYPE_ARRAY) {
104 $args->{id} = $util->_create('array');
107 $args->{id} = $util->_create('hash');
111 if (defined($args->{type}) && $args->{type} eq TYPE_ARRAY) {
112 $class = 'DBM::Deep::SQL::Array';
113 require DBM::Deep::SQL::Array;
114 tie @$self, $class, %$args;
115 if ($args->{prefetch}) {
116 (tied(@$self))->_prefetch();
118 return bless $self, $class;
121 $class = 'DBM::Deep::SQL::Hash';
122 require DBM::Deep::SQL::Hash;
123 tie %$self, $class, %$args;
124 if ($args->{prefetch}) {
125 (tied(%$self))->_prefetch();
127 return bless $self, $class;
132 # Check if we want a tied hash or array.
134 if (defined($args->{type}) && $args->{type} eq TYPE_ARRAY) {
135 $class = 'DBM::Deep::Array';
136 require DBM::Deep::Array;
137 tie @$self, $class, %$args;
140 $class = 'DBM::Deep::Hash';
141 require DBM::Deep::Hash;
142 tie %$self, $class, %$args;
145 return bless $self, $class;
148 # This initializer is called from the various TIE* methods. new() calls tie(),
149 # which allows for a single point of entry.
154 # locking implicitly enables autoflush
155 if ($args->{locking}) { $args->{autoflush} = 1; }
157 # These are the defaults to be optionally overridden below
160 base_offset => undef,
165 $args->{engine} = DBM::Deep::Engine->new( { %{$args}, obj => $self } )
166 unless exists $args->{engine};
168 # Grab the parameters we want to use
169 foreach my $param ( keys %$self ) {
170 next unless exists $args->{$param};
171 $self->{$param} = $args->{$param};
175 local $SIG{'__DIE__'};
177 $self->lock_exclusive;
178 $self->_engine->setup_fh( $self );
182 eval { local $SIG{'__DIE__'}; $self->unlock; };
191 require DBM::Deep::Hash;
192 return DBM::Deep::Hash->TIEHASH( @_ );
197 require DBM::Deep::Array;
198 return DBM::Deep::Array->TIEARRAY( @_ );
202 my $self = shift->_get_self;
203 return $self->_engine->lock_exclusive( $self, @_ );
205 *lock = \&lock_exclusive;
207 my $self = shift->_get_self;
208 return $self->_engine->lock_shared( $self, @_ );
212 my $self = shift->_get_self;
213 return $self->_engine->unlock( $self, @_ );
217 my $self = shift->_get_self;
218 my ($spot, $value) = @_;
224 # This assumes hash or array only. This is a bad assumption moving forward.
226 my $r = Scalar::Util::reftype( $value );
228 if ( $r eq 'ARRAY' ) {
229 $tied = tied(@$value);
232 $tied = tied(%$value);
235 if ( eval { local $SIG{__DIE__}; $tied->isa( 'DBM::Deep' ) } ) {
236 ${$spot} = $tied->_repr;
237 $tied->_copy_node( ${$spot} );
240 if ( $r eq 'ARRAY' ) {
241 ${$spot} = [ @{$value} ];
244 ${$spot} = { %{$value} };
248 my $c = Scalar::Util::blessed( $value );
249 if ( defined $c && !$c->isa( 'DBM::Deep') ) {
250 ${$spot} = bless ${$spot}, $c
258 # die "Must be implemented in a child class\n";
262 # die "Must be implemented in a child class\n";
267 # Recursively export into standard Perl hashes and arrays.
269 my $self = shift->_get_self;
271 my $temp = $self->_repr;
273 $self->lock_exclusive;
274 $self->_copy_node( $temp );
277 my $classname = $self->_engine->get_classname( $self );
278 if ( defined $classname ) {
279 bless $temp, $classname;
285 sub _check_legality {
289 my $r = Scalar::Util::reftype( $val );
291 return $r if !defined $r || '' eq $r;
292 return $r if 'HASH' eq $r;
293 return $r if 'ARRAY' eq $r;
295 DBM::Deep->_throw_error(
296 "Storage of references of type '$r' is not supported."
301 # Perl calls import() on use -- ignore
302 return if !ref $_[0];
304 my $self = shift->_get_self;
307 my $type = $self->_check_legality( $struct );
309 DBM::Deep->_throw_error( "Cannot import a scalar" );
312 if ( substr( $type, 0, 1 ) ne $self->_type ) {
313 DBM::Deep->_throw_error(
314 "Cannot import " . ('HASH' eq $type ? 'a hash' : 'an array')
315 . " into " . ('HASH' eq $type ? 'an array' : 'a hash')
324 my $obj = 'HASH' eq Scalar::Util::reftype( $db ) ? tied(%$db) : tied(@$db);
327 my $r = $self->_check_legality( $val );
328 if ( 'HASH' eq $r ) {
329 while ( my ($k, $v) = each %$val ) {
330 my $r = $self->_check_legality( $v );
332 my $temp = 'HASH' eq $r ? {} : [];
333 if ( my $c = Scalar::Util::blessed( $v ) ) {
336 $obj->put( $k, $temp );
337 $recurse->( $temp, $v );
344 elsif ( 'ARRAY' eq $r ) {
345 foreach my $k ( 0 .. $#$val ) {
347 my $r = $self->_check_legality( $v );
349 my $temp = 'HASH' eq $r ? {} : [];
350 if ( my $c = Scalar::Util::blessed( $v ) ) {
353 $obj->put( $k, $temp );
354 $recurse->( $temp, $v );
362 $recurse->( $self, $struct );
367 #XXX Need to keep track of who has a fh to this file in order to
368 #XXX close them all prior to optimize on Win32/cygwin
371 # Rebuild entire database into new file, then move
372 # it back on top of original.
374 my $self = shift->_get_self;
376 #XXX Need to create a new test for this
377 # if ($self->_engine->storage->{links} > 1) {
378 # $self->_throw_error("Cannot optimize: reference count is greater than 1");
381 #XXX Do we have to lock the tempfile?
383 #XXX Should we use tempfile() here instead of a hard-coded name?
384 my $temp_filename = $self->_engine->storage->{file} . '.tmp';
385 my $db_temp = DBM::Deep->new(
386 file => $temp_filename,
387 type => $self->_type,
389 # Bring over all the parameters that we need to bring over
390 ( map { $_ => $self->_engine->$_ } qw(
391 byte_size max_buckets data_sector_size num_txns
395 $self->lock_exclusive;
396 $self->_engine->clear_cache;
397 $self->_copy_node( $db_temp );
398 $db_temp->_engine->storage->close;
402 # Attempt to copy user, group and permissions over to new file
404 $self->_engine->storage->copy_stats( $temp_filename );
406 # q.v. perlport for more information on this variable
407 if ( $^O eq 'MSWin32' || $^O eq 'cygwin' ) {
409 # Potential race condition when optmizing on Win32 with locking.
410 # The Windows filesystem requires that the filehandle be closed
411 # before it is overwritten with rename(). This could be redone
415 $self->_engine->storage->close;
418 if (!rename $temp_filename, $self->_engine->storage->{file}) {
419 unlink $temp_filename;
421 $self->_throw_error("Optimize failed: Cannot copy temp file over original: $!");
425 $self->_engine->storage->close;
427 $self->_engine->storage->open;
428 $self->lock_exclusive;
429 $self->_engine->setup_fh( $self );
437 # Make copy of object and return
439 my $self = shift->_get_self;
441 return DBM::Deep->new(
442 type => $self->_type,
443 base_offset => $self->_base_offset,
444 staleness => $self->_staleness,
445 engine => $self->_engine,
449 #XXX Migrate this to the engine, where it really belongs and go through some
450 # API - stop poking in the innards of someone else..
452 my %is_legal_filter = map {
455 store_key store_value
456 fetch_key fetch_value
460 my $self = shift->_get_self;
464 if ( $is_legal_filter{$type} ) {
465 $self->_engine->storage->{"filter_$type"} = $func;
472 sub filter_store_key { $_[0]->set_filter( store_key => $_[1] ); }
473 sub filter_store_value { $_[0]->set_filter( store_value => $_[1] ); }
474 sub filter_fetch_key { $_[0]->set_filter( fetch_key => $_[1] ); }
475 sub filter_fetch_value { $_[0]->set_filter( fetch_value => $_[1] ); }
479 my $self = shift->_get_self;
480 $self->lock_exclusive;
481 my $rv = eval { $self->_engine->begin_work( $self, @_ ) };
489 my $self = shift->_get_self;
490 $self->lock_exclusive;
491 my $rv = eval { $self->_engine->rollback( $self, @_ ) };
499 my $self = shift->_get_self;
500 $self->lock_exclusive;
501 my $rv = eval { $self->_engine->commit( $self, @_ ) };
513 my $self = $_[0]->_get_self;
514 return $self->{engine};
518 my $self = $_[0]->_get_self;
519 return $self->{type};
523 my $self = $_[0]->_get_self;
524 return $self->{base_offset};
528 my $self = $_[0]->_get_self;
529 return $self->{staleness};
539 my @caller = caller( ++$n );
540 next if $caller[0] =~ m/^DBM::Deep/;
542 die "DBM::Deep: $_[1] at $0 line $caller[2]\n";
548 # Store single hash key/value or array element in database.
550 my $self = shift->_get_self;
551 my ($key, $value) = @_;
552 warn "STORE($self, '$key', '@{[defined$value?$value:'undef']}')\n" if DEBUG;
554 unless ( $self->_engine->storage->is_writable ) {
555 $self->_throw_error( 'Cannot write to a readonly filehandle' );
558 $self->lock_exclusive;
560 # User may be storing a complex value, in which case we do not want it run
561 # through the filtering system.
562 if ( !ref($value) && $self->_engine->storage->{filter_store_value} ) {
563 $value = $self->_engine->storage->{filter_store_value}->( $value );
566 $self->_engine->write_value( $self, $key, $value);
575 # Fetch single value or element given plain key or array index
577 my $self = shift->_get_self;
579 warn "FETCH($self, '$key')\n" if DEBUG;
583 my $result = $self->_engine->read_value( $self, $key);
587 # Filters only apply to scalar values, so the ref check is making
588 # sure the fetched bucket is a scalar, not a child hash or array.
589 return ($result && !ref($result) && $self->_engine->storage->{filter_fetch_value})
590 ? $self->_engine->storage->{filter_fetch_value}->($result)
596 # Delete single key/value pair or element given plain key or array index
598 my $self = shift->_get_self;
600 warn "DELETE($self, '$key')\n" if DEBUG;
602 unless ( $self->_engine->storage->is_writable ) {
603 $self->_throw_error( 'Cannot write to a readonly filehandle' );
606 $self->lock_exclusive;
611 my $value = $self->_engine->delete_key( $self, $key);
613 if (defined $value && !ref($value) && $self->_engine->storage->{filter_fetch_value}) {
614 $value = $self->_engine->storage->{filter_fetch_value}->($value);
624 # Check if a single key or element exists given plain key or array index
626 my $self = shift->_get_self;
628 warn "EXISTS($self, '$key')\n" if DEBUG;
632 my $result = $self->_engine->key_exists( $self, $key );
641 # Clear all keys from hash, or all elements from array.
643 my $self = shift->_get_self;
644 warn "CLEAR($self)\n" if DEBUG;
646 unless ( $self->_engine->storage->is_writable ) {
647 $self->_throw_error( 'Cannot write to a readonly filehandle' );
650 $self->lock_exclusive;
652 #XXX Rewrite this dreck to do it in the engine as a tight loop vs.
653 # iterating over keys - such a WASTE - is this required for transactional
654 # clearning?! Surely that can be detected in the engine ...
655 if ( $self->_type eq TYPE_HASH ) {
656 my $key = $self->first_key;
658 # Retrieve the key before deleting because we depend on next_key
659 my $next_key = $self->next_key( $key );
660 $self->_engine->delete_key( $self, $key, $key );
665 my $size = $self->FETCHSIZE;
666 for my $key ( 0 .. $size - 1 ) {
667 $self->_engine->delete_key( $self, $key, $key );
669 $self->STORESIZE( 0 );
678 # Public method aliases
680 sub put { (shift)->STORE( @_ ) }
681 sub store { (shift)->STORE( @_ ) }
682 sub get { (shift)->FETCH( @_ ) }
683 sub fetch { (shift)->FETCH( @_ ) }
684 sub delete { (shift)->DELETE( @_ ) }
685 sub exists { (shift)->EXISTS( @_ ) }
686 sub clear { (shift)->CLEAR( @_ ) }
688 sub _dump_file {shift->_get_self->_engine->_dump_file;}