1 package DBM::Deep::Engine;
5 use Fcntl qw( :DEFAULT :flock :seek );
9 # Precalculate index, bucket and bucket list sizes
13 $self->{index_size} = (2**8) * $self->{long_size};
14 $self->{bucket_size} = $self->{hash_size} + $self->{long_size};
15 $self->{bucket_list_size} = $self->{max_buckets} * $self->{bucket_size};
22 # Set pack/unpack modes (see file header for more)
25 my ($long_s, $long_p, $data_s, $data_p) = @_;
28 # Set to 4 and 'N' for 32-bit offset tags (default). Theoretical limit of 4 GB per file.
29 # (Perl must be compiled with largefile support for files > 2 GB)
31 # Set to 8 and 'Q' for 64-bit offsets. Theoretical limit of 16 XB per file.
32 # (Perl must be compiled with largefile and 64-bit long support)
34 $self->{long_size} = $long_s ? $long_s : 4;
35 $self->{long_pack} = $long_p ? $long_p : 'N';
38 # Set to 4 and 'N' for 32-bit data length prefixes. Limit of 4 GB for each key/value.
39 # Upgrading this is possible (see above) but probably not necessary. If you need
40 # more than 4 GB for a single key or value, this module is really not for you :-)
42 $self->{data_size} = $data_s ? $data_s : 4;
43 $self->{data_pack} = $data_p ? $data_p : 'N';
45 return $self->precalc_sizes();
50 # Set key digest function (default is MD5)
53 my ($digest_func, $hash_size) = @_;
55 $self->{digest} = $digest_func ? $digest_func : \&Digest::MD5::md5;
56 $self->{hash_size} = $hash_size ? $hash_size : 16;
58 return $self->precalc_sizes();
71 digest => \&Digest::MD5::md5,
75 # Maximum number of buckets per list before another level of indexing is done.
76 # Increase this value for slightly greater speed, but larger database files.
77 # DO NOT decrease this value below 16, due to risk of recursive reindex overrun.
91 $self->open( $obj ) if !defined $obj->_fh;
93 #XXX Is {end} busted? Can't we just seek( $fh, 0, SEEK_END ) ?
94 unless ( $obj->_root->{inode} ) {
95 my @stats = stat($obj->_fh);
96 $obj->_root->{inode} = $stats[1];
97 $obj->_root->{end} = $stats[7];
105 # Open a fh to the database, create if nonexistent.
106 # Make sure file signature matches DBM::Deep spec.
111 if (defined($obj->_fh)) { $self->close_fh( $obj ); }
114 local $SIG{'__DIE__'};
115 # Theoretically, adding O_BINARY should remove the need for the binmode
116 # Of course, testing it is going to be ... interesting.
117 my $flags = O_RDWR | O_CREAT | O_BINARY;
120 sysopen( $fh, $obj->_root->{file}, $flags )
122 $obj->_root->{fh} = $fh;
123 }; if ($@ ) { $obj->_throw_error( "Received error: $@\n" ); }
124 if (! defined($obj->_fh)) {
125 return $obj->_throw_error("Cannot sysopen file: " . $obj->_root->{file} . ": $!");
130 #XXX Can we remove this by using the right sysopen() flags?
131 # Maybe ... q.v. above
132 binmode $fh; # for win32
134 if ($obj->_root->{autoflush}) {
135 my $old = select $fh;
140 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
143 my $bytes_read = read( $fh, $signature, length(DBM::Deep->SIG_FILE));
146 # File is empty -- write signature and master index
149 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
150 print( $fh DBM::Deep->SIG_FILE);
152 $self->create_tag($obj, $obj->_base_offset, $obj->_type, chr(0) x $self->{index_size});
154 my $plain_key = "[base]";
155 print( $fh pack($self->{data_pack}, length($plain_key)) . $plain_key );
157 # Flush the filehandle
158 my $old_fh = select $fh;
159 my $old_af = $|; $| = 1; $| = $old_af;
166 # Check signature was valid
168 unless ($signature eq DBM::Deep->SIG_FILE) {
169 $self->close_fh( $obj );
170 return $obj->_throw_error("Signature not found -- file is not a Deep DB");
174 # Get our type from master index signature
176 my $tag = $self->load_tag($obj, $obj->_base_offset);
178 return $obj->_throw_error("Corrupted file, no master index record");
181 if ($obj->{type} ne $tag->{signature}) {
182 return $obj->_throw_error("File type mismatch");
185 #XXX We probably also want to store the hash algorithm name and not assume anything
186 #XXX The cool thing would be to allow a different hashing algorithm at every level
195 if ( my $fh = $obj->_root->{fh} ) {
198 $obj->_root->{fh} = undef;
205 # Given offset, signature and content, create tag and write to disk
208 my ($obj, $offset, $sig, $content) = @_;
209 my $size = length($content);
213 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
214 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
216 if ($offset == $obj->_root->{end}) {
217 $obj->_root->{end} += DBM::Deep->SIG_SIZE + $self->{data_size} + $size;
223 offset => $offset + DBM::Deep->SIG_SIZE + $self->{data_size},
230 # Given offset, load single tag and return signature, size and data
233 my ($obj, $offset) = @_;
237 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
238 if (eof $fh) { return undef; }
241 read( $fh, $b, DBM::Deep->SIG_SIZE + $self->{data_size} );
242 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
245 read( $fh, $buffer, $size);
250 offset => $offset + DBM::Deep->SIG_SIZE + $self->{data_size},
257 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
258 # plain (undigested) key and value.
261 my ($obj, $tag, $md5, $plain_key, $value) = @_;
262 my $keys = $tag->{content};
266 my $root = $obj->_root;
268 my $is_dbm_deep = eval { local $SIG{'__DIE__'}; $value->isa( 'DBM::Deep' ) };
269 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
274 # Iterate through buckets, seeing if this is a new entry or a replace.
276 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
277 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
280 # Found empty bucket (end of list). Populate and exit loop.
284 $location = $internal_ref
285 ? $value->_base_offset
288 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
289 print( $fh $md5 . pack($self->{long_pack}, $location) );
293 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
296 # Found existing bucket with same key. Replace with new value.
301 $location = $value->_base_offset;
302 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
303 print( $fh $md5 . pack($self->{long_pack}, $location) );
307 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $root->{file_offset}, SEEK_SET);
309 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
312 # If value is a hash, array, or raw value with equal or less size, we can
313 # reuse the same content area of the database. Otherwise, we have to create
314 # a new content area at the EOF.
317 my $r = Scalar::Util::reftype( $value ) || '';
318 if ( $r eq 'HASH' || $r eq 'ARRAY' ) {
319 $actual_length = $self->{index_size};
321 # if autobless is enabled, must also take into consideration
322 # the class name, as it is stored along with key/value.
323 if ( $root->{autobless} ) {
324 my $value_class = Scalar::Util::blessed($value);
325 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
326 $actual_length += length($value_class);
330 else { $actual_length = length($value); }
332 if ($actual_length <= $size) {
336 $location = $root->{end};
337 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $self->{hash_size} + $root->{file_offset}, SEEK_SET);
338 print( $fh pack($self->{long_pack}, $location) );
346 # If this is an internal reference, return now.
347 # No need to write value or plain key
354 # If bucket didn't fit into list, split into a new index level
357 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
358 print( $fh pack($self->{long_pack}, $root->{end}) );
360 my $index_tag = $self->create_tag($obj, $root->{end}, DBM::Deep->SIG_INDEX, chr(0) x $self->{index_size});
363 $keys .= $md5 . pack($self->{long_pack}, 0);
365 for (my $i=0; $i<=$self->{max_buckets}; $i++) {
366 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
368 my $old_subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) +
369 $self->{hash_size}, $self->{long_size}));
370 my $num = ord(substr($key, $tag->{ch} + 1, 1));
372 if ($offsets[$num]) {
373 my $offset = $offsets[$num] + DBM::Deep->SIG_SIZE + $self->{data_size};
374 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
376 read( $fh, $subkeys, $self->{bucket_list_size});
378 for (my $k=0; $k<$self->{max_buckets}; $k++) {
379 my $subloc = unpack($self->{long_pack}, substr($subkeys, ($k * $self->{bucket_size}) +
380 $self->{hash_size}, $self->{long_size}));
382 seek($fh, $offset + ($k * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
383 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
389 $offsets[$num] = $root->{end};
390 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
391 print( $fh pack($self->{long_pack}, $root->{end}) );
393 my $blist_tag = $self->create_tag($obj, $root->{end}, DBM::Deep->SIG_BLIST, chr(0) x $self->{bucket_list_size});
395 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
396 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
401 $location ||= $root->{end};
402 } # re-index bucket list
405 # Seek to content area and store signature, value and plaintext key
409 seek($fh, $location + $root->{file_offset}, SEEK_SET);
412 # Write signature based on content type, set content length and write actual value.
414 my $r = Scalar::Util::reftype($value) || '';
416 print( $fh DBM::Deep->TYPE_HASH );
417 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
418 $content_length = $self->{index_size};
420 elsif ($r eq 'ARRAY') {
421 print( $fh DBM::Deep->TYPE_ARRAY );
422 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
423 $content_length = $self->{index_size};
425 elsif (!defined($value)) {
426 print( $fh DBM::Deep->SIG_NULL );
427 print( $fh pack($self->{data_pack}, 0) );
431 print( $fh DBM::Deep->SIG_DATA );
432 print( $fh pack($self->{data_pack}, length($value)) . $value );
433 $content_length = length($value);
437 # Plain key is stored AFTER value, as keys are typically fetched less often.
439 print( $fh pack($self->{data_pack}, length($plain_key)) . $plain_key );
442 # If value is blessed, preserve class name
444 if ( $root->{autobless} ) {
445 my $value_class = Scalar::Util::blessed($value);
446 if ( defined $value_class && $value_class ne 'DBM::Deep' ) {
448 # Blessed ref -- will restore later
451 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
452 $content_length += 1;
453 $content_length += $self->{data_size} + length($value_class);
457 $content_length += 1;
462 # If this is a new content area, advance EOF counter
464 if ($location == $root->{end}) {
465 $root->{end} += DBM::Deep->SIG_SIZE;
466 $root->{end} += $self->{data_size} + $content_length;
467 $root->{end} += $self->{data_size} + length($plain_key);
471 # If content is a hash or array, create new child DBM::Deep object and
472 # pass each key or element to it.
475 my $branch = DBM::Deep->new(
476 type => DBM::Deep->TYPE_HASH,
477 base_offset => $location,
480 foreach my $key (keys %{$value}) {
481 $branch->STORE( $key, $value->{$key} );
484 elsif ($r eq 'ARRAY') {
485 my $branch = DBM::Deep->new(
486 type => DBM::Deep->TYPE_ARRAY,
487 base_offset => $location,
491 foreach my $element (@{$value}) {
492 $branch->STORE( $index, $element );
500 return $obj->_throw_error("Fatal error: indexing failed -- possibly due to corruption in file");
503 sub get_bucket_value {
505 # Fetch single value given tag and MD5 digested key.
508 my ($obj, $tag, $md5) = @_;
509 my $keys = $tag->{content};
514 # Iterate through buckets, looking for a key match
517 for (my $i=0; $i<$self->{max_buckets}; $i++) {
518 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
519 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
523 # Hit end of list, no match
528 if ( $md5 ne $key ) {
533 # Found match -- seek to offset and read signature
536 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
537 read( $fh, $signature, DBM::Deep->SIG_SIZE);
540 # If value is a hash or array, return new DBM::Deep object with correct offset
542 if (($signature eq DBM::Deep->TYPE_HASH) || ($signature eq DBM::Deep->TYPE_ARRAY)) {
543 my $obj = DBM::Deep->new(
545 base_offset => $subloc,
549 if ($obj->_root->{autobless}) {
551 # Skip over value and plain key to see if object needs
554 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
557 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
558 if ($size) { seek($fh, $size, SEEK_CUR); }
561 read( $fh, $bless_bit, 1);
562 if (ord($bless_bit)) {
564 # Yes, object needs to be re-blessed
567 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
568 if ($size) { read( $fh, $class_name, $size); }
569 if ($class_name) { $obj = bless( $obj, $class_name ); }
577 # Otherwise return actual value
579 elsif ($signature eq DBM::Deep->SIG_DATA) {
582 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
583 if ($size) { read( $fh, $value, $size); }
588 # Key exists, but content is null
598 # Delete single key/value pair given tag and MD5 digested key.
601 my ($obj, $tag, $md5) = @_;
602 my $keys = $tag->{content};
607 # Iterate through buckets, looking for a key match
610 for (my $i=0; $i<$self->{max_buckets}; $i++) {
611 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
612 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
616 # Hit end of list, no match
621 if ( $md5 ne $key ) {
626 # Matched key -- delete bucket and return
628 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $obj->_root->{file_offset}, SEEK_SET);
629 print( $fh substr($keys, ($i+1) * $self->{bucket_size} ) );
630 print( $fh chr(0) x $self->{bucket_size} );
640 # Check existence of single key given tag and MD5 digested key.
643 my ($obj, $tag, $md5) = @_;
644 my $keys = $tag->{content};
647 # Iterate through buckets, looking for a key match
650 for (my $i=0; $i<$self->{max_buckets}; $i++) {
651 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
652 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
656 # Hit end of list, no match
661 if ( $md5 ne $key ) {
666 # Matched key -- return true
674 sub find_bucket_list {
676 # Locate offset for bucket list, given digested key
679 my ($obj, $md5, $args) = @_;
680 $args = {} unless $args;
683 # Locate offset for bucket list using digest index system
686 my $tag = $self->load_tag($obj, $obj->_base_offset);
688 return $self->_throw_error( "INTERNAL ERROR - Cannot find tag" );
691 while ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
692 my $num = ord substr($md5, $ch, 1);
694 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
695 $tag = $self->index_lookup( $obj, $tag, $num );
698 if ( $args->{create} ) {
700 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
701 print( $fh pack($self->{long_pack}, $obj->_root->{end}) );
703 $tag = $self->create_tag(
704 $obj, $obj->_root->{end},
705 DBM::Deep->SIG_BLIST,
706 chr(0) x $self->{bucket_list_size},
709 $tag->{ref_loc} = $ref_loc;
720 $tag->{ref_loc} = $ref_loc;
730 # Given index tag, lookup single entry in index and return .
733 my ($obj, $tag, $index) = @_;
735 my $location = unpack(
739 $index * $self->{long_size},
744 if (!$location) { return; }
746 return $self->load_tag( $obj, $location );
751 # Scan index and recursively step into deeper levels, looking for next key.
754 my ($obj, $offset, $ch, $force_return_next) = @_;
755 $force_return_next = undef unless $force_return_next;
757 my $tag = $self->load_tag($obj, $offset );
761 if ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
762 my $content = $tag->{content};
764 if ($obj->{return_next}) { $start = 0; }
765 else { $start = ord(substr($obj->{prev_md5}, $ch, 1)); }
767 for (my $index = $start; $index < 256; $index++) {
768 my $subloc = unpack($self->{long_pack}, substr($content, $index * $self->{long_size}, $self->{long_size}) );
770 my $result = $self->traverse_index( $obj, $subloc, $ch + 1, $force_return_next );
771 if (defined($result)) { return $result; }
775 $obj->{return_next} = 1;
778 elsif ($tag->{signature} eq DBM::Deep->SIG_BLIST) {
779 my $keys = $tag->{content};
780 if ($force_return_next) { $obj->{return_next} = 1; }
783 # Iterate through buckets, looking for a key match
785 for (my $i=0; $i<$self->{max_buckets}; $i++) {
786 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
787 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
791 # End of bucket list -- return to outer loop
793 $obj->{return_next} = 1;
796 elsif ($key eq $obj->{prev_md5}) {
798 # Located previous key -- return next one found
800 $obj->{return_next} = 1;
803 elsif ($obj->{return_next}) {
805 # Seek to bucket location and skip over signature
807 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $obj->_root->{file_offset}, SEEK_SET);
810 # Skip over value to get to plain key
813 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
814 if ($size) { seek($fh, $size, SEEK_CUR); }
817 # Read in plain key and return as scalar
820 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
821 if ($size) { read( $fh, $plain_key, $size); }
827 $obj->{return_next} = 1;
828 } # tag is a bucket list
835 # Locate next key, given digested previous one
840 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
841 $obj->{return_next} = 0;
844 # If the previous key was not specifed, start at the top and
845 # return the first one found.
847 if (!$obj->{prev_md5}) {
848 $obj->{prev_md5} = chr(0) x $self->{hash_size};
849 $obj->{return_next} = 1;
852 return $self->traverse_index( $obj, $obj->_base_offset, 0 );