6 use warnings FATAL => 'all';
8 our $VERSION = q(1.0015);
12 use DBM::Deep::Engine::File ();
14 use DBM::Deep::SQL::Util;
15 use DBM::Deep::SQL::Array;
16 use DBM::Deep::SQL::Hash;
19 '""' => sub { overload::StrVal( $_[0] ) },
22 use constant DEBUG => 0;
24 sub TYPE_HASH () { DBM::Deep::Engine->SIG_HASH }
25 sub TYPE_ARRAY () { DBM::Deep::Engine->SIG_ARRAY }
27 # This is used in all the children of this class in their TIE<type> methods.
34 $proto->_throw_error( "Odd number of parameters to " . (caller(1))[2] );
39 unless ( eval { local $SIG{'__DIE__'}; %{$_[0]} || 1 } ) {
40 $proto->_throw_error( "Not a hashref in args to " . (caller(1))[2] );
45 $args = { file => shift };
51 # Class constructor method for Perl OO interface.
52 # Calls tie() and returns blessed reference to tied hash or array,
53 # providing a hybrid OO/tie interface.
56 my $args = $class->_get_args( @_ );
59 if (exists $args->{dbi}) {
61 require DBIx::Abstract;
63 __PACKAGE__->_throw_error('DBIx::Abstract not installed. You cannot use the SQL mode.');
65 unless (UNIVERSAL::isa($args->{dbi}, 'DBIx::Abstract')) {
66 $args->{dbi} = DBIx::Abstract->connect($args->{dbi});
69 if (defined $args->{id}) {
70 unless ($args->{id} =~ /^\d+$/ && $args->{id} > 0) {
71 __PACKAGE__->_throw_error('Invalid SQL record id');
73 my $util = {dbi => $args->{dbi}};
74 bless $util, 'DBM::Deep::SQL::Util';
75 my $q = $util->_select(
77 fields => 'item_type',
78 where => {id => $args->{id}},
80 if ($q->[0]->[0] eq 'array') {
81 $args->{type} = TYPE_ARRAY;
83 elsif ($q->[0]->[0] eq 'hash') {
84 $args->{type} = TYPE_HASH;
87 DBM::Deep->_throw_error('Unknown SQL record id');
91 my $util = {dbi => $args->{dbi}};
92 bless $util, 'DBM::Deep::SQL::Util';
93 if (defined($args->{type}) && $args->{type} eq TYPE_ARRAY) {
94 $args->{id} = $util->_create('array');
97 $args->{id} = $util->_create('hash');
101 if (defined($args->{type}) && $args->{type} eq TYPE_ARRAY) {
102 $class = 'DBM::Deep::SQL::Array';
103 require DBM::Deep::SQL::Array;
104 tie @$self, $class, %$args;
105 if ($args->{prefetch}) {
106 (tied(@$self))->_prefetch();
108 return bless $self, $class;
111 $class = 'DBM::Deep::SQL::Hash';
112 require DBM::Deep::SQL::Hash;
113 tie %$self, $class, %$args;
114 if ($args->{prefetch}) {
115 (tied(%$self))->_prefetch();
117 return bless $self, $class;
122 # Check if we want a tied hash or array.
124 if (defined($args->{type}) && $args->{type} eq TYPE_ARRAY) {
125 $class = 'DBM::Deep::Array';
126 require DBM::Deep::Array;
127 tie @$self, $class, %$args;
130 $class = 'DBM::Deep::Hash';
131 require DBM::Deep::Hash;
132 tie %$self, $class, %$args;
135 return bless $self, $class;
138 # This initializer is called from the various TIE* methods. new() calls tie(),
139 # which allows for a single point of entry.
144 # locking implicitly enables autoflush
145 if ($args->{locking}) { $args->{autoflush} = 1; }
147 # These are the defaults to be optionally overridden below
150 base_offset => undef,
155 unless ( exists $args->{engine} ) {
156 my $class = exists $args->{dbi}
157 ? 'DBM::Deep::Engine::DBI'
158 : 'DBM::Deep::Engine::File';
160 $args->{engine} = $class->new({
166 # Grab the parameters we want to use
167 foreach my $param ( keys %$self ) {
168 next unless exists $args->{$param};
169 $self->{$param} = $args->{$param};
173 local $SIG{'__DIE__'};
175 $self->lock_exclusive;
176 $self->_engine->setup( $self );
180 eval { local $SIG{'__DIE__'}; $self->unlock; };
189 require DBM::Deep::Hash;
190 return DBM::Deep::Hash->TIEHASH( @_ );
195 require DBM::Deep::Array;
196 return DBM::Deep::Array->TIEARRAY( @_ );
200 my $self = shift->_get_self;
201 return $self->_engine->lock_exclusive( $self, @_ );
203 *lock = \&lock_exclusive;
205 my $self = shift->_get_self;
206 return $self->_engine->lock_shared( $self, @_ );
210 my $self = shift->_get_self;
211 return $self->_engine->unlock( $self, @_ );
215 my $self = shift->_get_self;
216 my ($spot, $value) = @_;
222 my $r = Scalar::Util::reftype( $value );
224 if ( $r eq 'ARRAY' ) {
225 $tied = tied(@$value);
227 elsif ( $r eq 'HASH' ) {
228 $tied = tied(%$value);
231 __PACKAGE__->_throw_error( "Unknown type for '$value'" );
234 if ( eval { local $SIG{__DIE__}; $tied->isa( __PACKAGE__ ) } ) {
235 ${$spot} = $tied->_repr;
236 $tied->_copy_node( ${$spot} );
239 if ( $r eq 'ARRAY' ) {
240 ${$spot} = [ @{$value} ];
243 ${$spot} = { %{$value} };
247 my $c = Scalar::Util::blessed( $value );
248 if ( defined $c && !$c->isa( __PACKAGE__ ) ) {
249 ${$spot} = bless ${$spot}, $c
257 # die "Must be implemented in a child class\n";
261 # die "Must be implemented in a child class\n";
265 my $self = shift->_get_self;
267 my $temp = $self->_repr;
269 $self->lock_exclusive;
270 $self->_copy_node( $temp );
273 my $classname = $self->_engine->get_classname( $self );
274 if ( defined $classname ) {
275 bless $temp, $classname;
281 sub _check_legality {
285 my $r = Scalar::Util::reftype( $val );
287 return $r if !defined $r || '' eq $r;
288 return $r if 'HASH' eq $r;
289 return $r if 'ARRAY' eq $r;
291 __PACKAGE__->_throw_error(
292 "Storage of references of type '$r' is not supported."
297 return if !ref $_[0]; # Perl calls import() on use -- ignore
299 my $self = shift->_get_self;
302 my $type = $self->_check_legality( $struct );
304 __PACKAGE__->_throw_error( "Cannot import a scalar" );
307 if ( substr( $type, 0, 1 ) ne $self->_type ) {
308 __PACKAGE__->_throw_error(
309 "Cannot import " . ('HASH' eq $type ? 'a hash' : 'an array')
310 . " into " . ('HASH' eq $type ? 'an array' : 'a hash')
319 my $obj = 'HASH' eq Scalar::Util::reftype( $db ) ? tied(%$db) : tied(@$db);
322 my $r = $self->_check_legality( $val );
323 if ( 'HASH' eq $r ) {
324 while ( my ($k, $v) = each %$val ) {
325 my $r = $self->_check_legality( $v );
327 my $temp = 'HASH' eq $r ? {} : [];
328 if ( my $c = Scalar::Util::blessed( $v ) ) {
331 $obj->put( $k, $temp );
332 $recurse->( $temp, $v );
339 elsif ( 'ARRAY' eq $r ) {
340 foreach my $k ( 0 .. $#$val ) {
342 my $r = $self->_check_legality( $v );
344 my $temp = 'HASH' eq $r ? {} : [];
345 if ( my $c = Scalar::Util::blessed( $v ) ) {
348 $obj->put( $k, $temp );
349 $recurse->( $temp, $v );
357 $recurse->( $self, $struct );
362 #XXX Need to keep track of who has a fh to this file in order to
363 #XXX close them all prior to optimize on Win32/cygwin
364 # Rebuild entire database into new file, then move
365 # it back on top of original.
367 my $self = shift->_get_self;
369 # Optimizing is only something we need to do when we're working with our
370 # own file format. Otherwise, let the other guy do the optimizations.
371 return unless $self->_engine->isa( 'DBM::Deep::Engine::File' );
373 #XXX Need to create a new test for this
374 # if ($self->_engine->storage->{links} > 1) {
375 # $self->_throw_error("Cannot optimize: reference count is greater than 1");
378 #XXX Do we have to lock the tempfile?
380 #XXX Should we use tempfile() here instead of a hard-coded name?
381 my $temp_filename = $self->_engine->storage->{file} . '.tmp';
382 my $db_temp = __PACKAGE__->new(
383 file => $temp_filename,
384 type => $self->_type,
386 # Bring over all the parameters that we need to bring over
387 ( map { $_ => $self->_engine->$_ } qw(
388 byte_size max_buckets data_sector_size num_txns
392 $self->lock_exclusive;
393 $self->_engine->clear_cache;
394 $self->_copy_node( $db_temp );
395 $db_temp->_engine->storage->close;
399 # Attempt to copy user, group and permissions over to new file
401 $self->_engine->storage->copy_stats( $temp_filename );
403 # q.v. perlport for more information on this variable
404 if ( $^O eq 'MSWin32' || $^O eq 'cygwin' ) {
406 # Potential race condition when optmizing on Win32 with locking.
407 # The Windows filesystem requires that the filehandle be closed
408 # before it is overwritten with rename(). This could be redone
412 $self->_engine->storage->close;
415 if (!rename $temp_filename, $self->_engine->storage->{file}) {
416 unlink $temp_filename;
418 $self->_throw_error("Optimize failed: Cannot copy temp file over original: $!");
422 $self->_engine->storage->close;
424 $self->_engine->storage->open;
425 $self->lock_exclusive;
426 $self->_engine->setup( $self );
434 # Make copy of object and return
436 my $self = shift->_get_self;
438 return __PACKAGE__->new(
439 type => $self->_type,
440 base_offset => $self->_base_offset,
441 staleness => $self->_staleness,
442 engine => $self->_engine,
446 #XXX Migrate this to the engine, where it really belongs and go through some
447 # API - stop poking in the innards of someone else..
449 my %is_legal_filter = map {
452 store_key store_value
453 fetch_key fetch_value
457 my $self = shift->_get_self;
461 if ( $is_legal_filter{$type} ) {
462 $self->_engine->storage->{"filter_$type"} = $func;
469 sub filter_store_key { $_[0]->set_filter( store_key => $_[1] ); }
470 sub filter_store_value { $_[0]->set_filter( store_value => $_[1] ); }
471 sub filter_fetch_key { $_[0]->set_filter( fetch_key => $_[1] ); }
472 sub filter_fetch_value { $_[0]->set_filter( fetch_value => $_[1] ); }
476 my $self = shift->_get_self;
477 $self->lock_exclusive;
478 my $rv = eval { $self->_engine->begin_work( $self, @_ ) };
486 my $self = shift->_get_self;
487 $self->lock_exclusive;
488 my $rv = eval { $self->_engine->rollback( $self, @_ ) };
496 my $self = shift->_get_self;
497 $self->lock_exclusive;
498 my $rv = eval { $self->_engine->commit( $self, @_ ) };
507 my $self = $_[0]->_get_self;
508 return $self->{engine};
512 my $self = $_[0]->_get_self;
513 return $self->{type};
517 my $self = $_[0]->_get_self;
518 return $self->{base_offset};
522 my $self = $_[0]->_get_self;
523 return $self->{staleness};
530 my @caller = caller( ++$n );
531 next if $caller[0] =~ m/^DBM::Deep/;
533 die "DBM::Deep: $_[1] at $0 line $caller[2]\n";
537 # Store single hash key/value or array element in database.
539 my $self = shift->_get_self;
540 my ($key, $value) = @_;
541 warn "STORE($self, '$key', '@{[defined$value?$value:'undef']}')\n" if DEBUG;
543 unless ( $self->_engine->storage->is_writable ) {
544 $self->_throw_error( 'Cannot write to a readonly filehandle' );
547 $self->lock_exclusive;
549 # User may be storing a complex value, in which case we do not want it run
550 # through the filtering system.
551 if ( !ref($value) && $self->_engine->storage->{filter_store_value} ) {
552 $value = $self->_engine->storage->{filter_store_value}->( $value );
555 $self->_engine->write_value( $self, $key, $value );
562 # Fetch single value or element given plain key or array index
564 my $self = shift->_get_self;
566 warn "FETCH($self, '$key')\n" if DEBUG;
570 my $result = $self->_engine->read_value( $self, $key );
574 # Filters only apply to scalar values, so the ref check is making
575 # sure the fetched bucket is a scalar, not a child hash or array.
576 return ($result && !ref($result) && $self->_engine->storage->{filter_fetch_value})
577 ? $self->_engine->storage->{filter_fetch_value}->($result)
581 # Delete single key/value pair or element given plain key or array index
583 my $self = shift->_get_self;
585 warn "DELETE($self, '$key')\n" if DEBUG;
587 unless ( $self->_engine->storage->is_writable ) {
588 $self->_throw_error( 'Cannot write to a readonly filehandle' );
591 $self->lock_exclusive;
596 my $value = $self->_engine->delete_key( $self, $key);
598 if (defined $value && !ref($value) && $self->_engine->storage->{filter_fetch_value}) {
599 $value = $self->_engine->storage->{filter_fetch_value}->($value);
607 # Check if a single key or element exists given plain key or array index
609 my $self = shift->_get_self;
611 warn "EXISTS($self, '$key')\n" if DEBUG;
615 my $result = $self->_engine->key_exists( $self, $key );
622 # Clear all keys from hash, or all elements from array.
624 my $self = shift->_get_self;
625 warn "CLEAR($self)\n" if DEBUG;
627 unless ( $self->_engine->storage->is_writable ) {
628 $self->_throw_error( 'Cannot write to a readonly filehandle' );
631 $self->lock_exclusive;
633 #XXX Rewrite this dreck to do it in the engine as a tight loop vs.
634 # iterating over keys - such a WASTE - is this required for transactional
635 # clearning?! Surely that can be detected in the engine ...
636 if ( $self->_type eq TYPE_HASH ) {
637 my $key = $self->first_key;
639 # Retrieve the key before deleting because we depend on next_key
640 my $next_key = $self->next_key( $key );
641 $self->_engine->delete_key( $self, $key, $key );
646 my $size = $self->FETCHSIZE;
647 for my $key ( 0 .. $size - 1 ) {
648 $self->_engine->delete_key( $self, $key, $key );
650 $self->STORESIZE( 0 );
658 # Public method aliases
659 sub put { (shift)->STORE( @_ ) }
660 sub get { (shift)->FETCH( @_ ) }
661 sub store { (shift)->STORE( @_ ) }
662 sub fetch { (shift)->FETCH( @_ ) }
663 sub delete { (shift)->DELETE( @_ ) }
664 sub exists { (shift)->EXISTS( @_ ) }
665 sub clear { (shift)->CLEAR( @_ ) }
667 sub _dump_file {shift->_get_self->_engine->_dump_file;}