1 package DBM::Deep::Engine;
5 use Fcntl qw( :DEFAULT :flock :seek );
8 # Set to 4 and 'N' for 32-bit offset tags (default). Theoretical limit of 4 GB per file.
9 # (Perl must be compiled with largefile support for files > 2 GB)
11 # Set to 8 and 'Q' for 64-bit offsets. Theoretical limit of 16 XB per file.
12 # (Perl must be compiled with largefile and 64-bit long support)
15 # Set to 4 and 'N' for 32-bit data length prefixes. Limit of 4 GB for each key/value.
16 # Upgrading this is possible (see above) but probably not necessary. If you need
17 # more than 4 GB for a single key or value, this module is really not for you :-)
19 our ($LONG_SIZE, $LONG_PACK, $DATA_LENGTH_SIZE, $DATA_LENGTH_PACK);
21 # Maximum number of buckets per list before another level of indexing is done.
22 # Increase this value for slightly greater speed, but larger database files.
23 # DO NOT decrease this value below 16, due to risk of recursive reindex overrun.
25 our $MAX_BUCKETS = 16;
26 our ($DIGEST_FUNC, $HASH_SIZE);
27 our ($INDEX_SIZE, $BUCKET_SIZE, $BUCKET_LIST_SIZE);
32 # Precalculate index, bucket and bucket list sizes
35 #XXX I don't like this ...
36 set_pack() unless defined $LONG_SIZE;
38 $INDEX_SIZE = 256 * $LONG_SIZE;
39 $BUCKET_SIZE = $HASH_SIZE + $LONG_SIZE;
40 $BUCKET_LIST_SIZE = $MAX_BUCKETS * $BUCKET_SIZE;
45 # Set pack/unpack modes (see file header for more)
47 my ($long_s, $long_p, $data_s, $data_p) = @_;
49 $LONG_SIZE = $long_s ? $long_s : 4;
50 $LONG_PACK = $long_p ? $long_p : 'N';
52 $DATA_LENGTH_SIZE = $data_s ? $data_s : 4;
53 $DATA_LENGTH_PACK = $data_p ? $data_p : 'N';
60 # Set key digest function (default is MD5)
62 my ($digest_func, $hash_size) = @_;
64 $DIGEST_FUNC = $digest_func ? $digest_func : \&Digest::MD5::md5;
65 $HASH_SIZE = $hash_size ? $hash_size : 16;
74 $self->open( $obj ) if !defined $obj->_fh;
76 #XXX Is {end} busted? Can't we just seek( $fh, 0, SEEK_END ) ?
77 unless ( $obj->_root->{inode} ) {
78 my @stats = stat($obj->_fh);
79 $obj->_root->{inode} = $stats[1];
80 $obj->_root->{end} = $stats[7];
88 # Open a fh to the database, create if nonexistent.
89 # Make sure file signature matches DBM::Deep spec.
94 if (defined($obj->_fh)) { $self->close( $obj ); }
97 local $SIG{'__DIE__'};
98 # Theoretically, adding O_BINARY should remove the need for the binmode
99 # Of course, testing it is going to be ... interesting.
100 my $flags = O_RDWR | O_CREAT | O_BINARY;
103 sysopen( $fh, $obj->_root->{file}, $flags )
105 $obj->_root->{fh} = $fh;
106 }; if ($@ ) { $obj->_throw_error( "Received error: $@\n" ); }
107 if (! defined($obj->_fh)) {
108 return $obj->_throw_error("Cannot sysopen file: " . $obj->_root->{file} . ": $!");
113 #XXX Can we remove this by using the right sysopen() flags?
114 # Maybe ... q.v. above
115 binmode $fh; # for win32
117 if ($obj->_root->{autoflush}) {
118 my $old = select $fh;
123 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
126 my $bytes_read = read( $fh, $signature, length(DBM::Deep->SIG_FILE));
129 # File is empty -- write signature and master index
132 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
133 print( $fh DBM::Deep->SIG_FILE);
134 $self->create_tag($obj, $obj->_base_offset, $obj->_type, chr(0) x $INDEX_SIZE);
136 my $plain_key = "[base]";
137 print( $fh pack($DATA_LENGTH_PACK, length($plain_key)) . $plain_key );
139 # Flush the filehandle
140 my $old_fh = select $fh;
141 my $old_af = $|; $| = 1; $| = $old_af;
148 # Check signature was valid
150 unless ($signature eq DBM::Deep->SIG_FILE) {
151 $self->close( $obj );
152 return $obj->_throw_error("Signature not found -- file is not a Deep DB");
156 # Get our type from master index signature
158 my $tag = $self->load_tag($obj, $obj->_base_offset);
160 #XXX We probably also want to store the hash algorithm name and not assume anything
161 #XXX The cool thing would be to allow a different hashing algorithm at every level
164 return $obj->_throw_error("Corrupted file, no master index record");
166 if ($obj->{type} ne $tag->{signature}) {
167 return $obj->_throw_error("File type mismatch");
177 if ( my $fh = $obj->_root->{fh} ) {
180 $obj->_root->{fh} = undef;
187 # Given offset, signature and content, create tag and write to disk
190 my ($obj, $offset, $sig, $content) = @_;
191 my $size = length($content);
195 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
196 print( $fh $sig . pack($DATA_LENGTH_PACK, $size) . $content );
198 if ($offset == $obj->_root->{end}) {
199 $obj->_root->{end} += DBM::Deep->SIG_SIZE + $DATA_LENGTH_SIZE + $size;
205 offset => $offset + DBM::Deep->SIG_SIZE + $DATA_LENGTH_SIZE,
212 # Given offset, load single tag and return signature, size and data
215 my ($obj, $offset) = @_;
219 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
220 if (eof $fh) { return undef; }
223 read( $fh, $b, DBM::Deep->SIG_SIZE + $DATA_LENGTH_SIZE );
224 my ($sig, $size) = unpack( "A $DATA_LENGTH_PACK", $b );
227 read( $fh, $buffer, $size);
232 offset => $offset + DBM::Deep->SIG_SIZE + $DATA_LENGTH_SIZE,
239 # Given index tag, lookup single entry in index and return .
242 my ($obj, $tag, $index) = @_;
244 my $location = unpack($LONG_PACK, substr($tag->{content}, $index * $LONG_SIZE, $LONG_SIZE) );
245 if (!$location) { return; }
247 return $self->load_tag( $obj, $location );
252 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
253 # plain (undigested) key and value.
256 my ($obj, $tag, $md5, $plain_key, $value) = @_;
257 my $keys = $tag->{content};
261 my $root = $obj->_root;
263 my $is_dbm_deep = eval { local $SIG{'__DIE__'}; $value->isa( 'DBM::Deep' ) };
264 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
269 # Iterate through buckets, seeing if this is a new entry or a replace.
271 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
272 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
275 # Found empty bucket (end of list). Populate and exit loop.
279 $location = $internal_ref
280 ? $value->_base_offset
283 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE) + $root->{file_offset}, SEEK_SET);
284 print( $fh $md5 . pack($LONG_PACK, $location) );
288 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
291 # Found existing bucket with same key. Replace with new value.
296 $location = $value->_base_offset;
297 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE) + $root->{file_offset}, SEEK_SET);
298 print( $fh $md5 . pack($LONG_PACK, $location) );
302 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $root->{file_offset}, SEEK_SET);
304 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
307 # If value is a hash, array, or raw value with equal or less size, we can
308 # reuse the same content area of the database. Otherwise, we have to create
309 # a new content area at the EOF.
312 my $r = Scalar::Util::reftype( $value ) || '';
313 if ( $r eq 'HASH' || $r eq 'ARRAY' ) {
314 $actual_length = $INDEX_SIZE;
316 # if autobless is enabled, must also take into consideration
317 # the class name, as it is stored along with key/value.
318 if ( $root->{autobless} ) {
319 my $value_class = Scalar::Util::blessed($value);
320 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
321 $actual_length += length($value_class);
325 else { $actual_length = length($value); }
327 if ($actual_length <= $size) {
331 $location = $root->{end};
332 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE) + $HASH_SIZE + $root->{file_offset}, SEEK_SET);
333 print( $fh pack($LONG_PACK, $location) );
341 # If this is an internal reference, return now.
342 # No need to write value or plain key
349 # If bucket didn't fit into list, split into a new index level
352 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
353 print( $fh pack($LONG_PACK, $root->{end}) );
355 my $index_tag = $self->create_tag($obj, $root->{end}, DBM::Deep->SIG_INDEX, chr(0) x $INDEX_SIZE);
358 $keys .= $md5 . pack($LONG_PACK, 0);
360 for (my $i=0; $i<=$MAX_BUCKETS; $i++) {
361 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
363 my $old_subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) +
364 $HASH_SIZE, $LONG_SIZE));
365 my $num = ord(substr($key, $tag->{ch} + 1, 1));
367 if ($offsets[$num]) {
368 my $offset = $offsets[$num] + DBM::Deep->SIG_SIZE + $DATA_LENGTH_SIZE;
369 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
371 read( $fh, $subkeys, $BUCKET_LIST_SIZE);
373 for (my $k=0; $k<$MAX_BUCKETS; $k++) {
374 my $subloc = unpack($LONG_PACK, substr($subkeys, ($k * $BUCKET_SIZE) +
375 $HASH_SIZE, $LONG_SIZE));
377 seek($fh, $offset + ($k * $BUCKET_SIZE) + $root->{file_offset}, SEEK_SET);
378 print( $fh $key . pack($LONG_PACK, $old_subloc || $root->{end}) );
384 $offsets[$num] = $root->{end};
385 seek($fh, $index_tag->{offset} + ($num * $LONG_SIZE) + $root->{file_offset}, SEEK_SET);
386 print( $fh pack($LONG_PACK, $root->{end}) );
388 my $blist_tag = $self->create_tag($obj, $root->{end}, DBM::Deep->SIG_BLIST, chr(0) x $BUCKET_LIST_SIZE);
390 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
391 print( $fh $key . pack($LONG_PACK, $old_subloc || $root->{end}) );
396 $location ||= $root->{end};
397 } # re-index bucket list
400 # Seek to content area and store signature, value and plaintext key
404 seek($fh, $location + $root->{file_offset}, SEEK_SET);
407 # Write signature based on content type, set content length and write actual value.
409 my $r = Scalar::Util::reftype($value) || '';
411 print( $fh DBM::Deep->TYPE_HASH );
412 print( $fh pack($DATA_LENGTH_PACK, $INDEX_SIZE) . chr(0) x $INDEX_SIZE );
413 $content_length = $INDEX_SIZE;
415 elsif ($r eq 'ARRAY') {
416 print( $fh DBM::Deep->TYPE_ARRAY );
417 print( $fh pack($DATA_LENGTH_PACK, $INDEX_SIZE) . chr(0) x $INDEX_SIZE );
418 $content_length = $INDEX_SIZE;
420 elsif (!defined($value)) {
421 print( $fh DBM::Deep->SIG_NULL );
422 print( $fh pack($DATA_LENGTH_PACK, 0) );
426 print( $fh DBM::Deep->SIG_DATA );
427 print( $fh pack($DATA_LENGTH_PACK, length($value)) . $value );
428 $content_length = length($value);
432 # Plain key is stored AFTER value, as keys are typically fetched less often.
434 print( $fh pack($DATA_LENGTH_PACK, length($plain_key)) . $plain_key );
437 # If value is blessed, preserve class name
439 if ( $root->{autobless} ) {
440 my $value_class = Scalar::Util::blessed($value);
441 if ( defined $value_class && $value_class ne 'DBM::Deep' ) {
443 # Blessed ref -- will restore later
446 print( $fh pack($DATA_LENGTH_PACK, length($value_class)) . $value_class );
447 $content_length += 1;
448 $content_length += $DATA_LENGTH_SIZE + length($value_class);
452 $content_length += 1;
457 # If this is a new content area, advance EOF counter
459 if ($location == $root->{end}) {
460 $root->{end} += DBM::Deep->SIG_SIZE;
461 $root->{end} += $DATA_LENGTH_SIZE + $content_length;
462 $root->{end} += $DATA_LENGTH_SIZE + length($plain_key);
466 # If content is a hash or array, create new child DBM::Deep object and
467 # pass each key or element to it.
470 my $branch = DBM::Deep->new(
471 type => DBM::Deep->TYPE_HASH,
472 base_offset => $location,
475 foreach my $key (keys %{$value}) {
476 $branch->STORE( $key, $value->{$key} );
479 elsif ($r eq 'ARRAY') {
480 my $branch = DBM::Deep->new(
481 type => DBM::Deep->TYPE_ARRAY,
482 base_offset => $location,
486 foreach my $element (@{$value}) {
487 $branch->STORE( $index, $element );
495 return $obj->_throw_error("Fatal error: indexing failed -- possibly due to corruption in file");
498 sub get_bucket_value {
500 # Fetch single value given tag and MD5 digested key.
503 my ($obj, $tag, $md5) = @_;
504 my $keys = $tag->{content};
509 # Iterate through buckets, looking for a key match
512 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
513 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
514 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
518 # Hit end of list, no match
523 if ( $md5 ne $key ) {
528 # Found match -- seek to offset and read signature
531 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
532 read( $fh, $signature, DBM::Deep->SIG_SIZE);
535 # If value is a hash or array, return new DBM::Deep object with correct offset
537 if (($signature eq DBM::Deep->TYPE_HASH) || ($signature eq DBM::Deep->TYPE_ARRAY)) {
538 my $obj = DBM::Deep->new(
540 base_offset => $subloc,
544 if ($obj->_root->{autobless}) {
546 # Skip over value and plain key to see if object needs
549 seek($fh, $DATA_LENGTH_SIZE + $INDEX_SIZE, SEEK_CUR);
552 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
553 if ($size) { seek($fh, $size, SEEK_CUR); }
556 read( $fh, $bless_bit, 1);
557 if (ord($bless_bit)) {
559 # Yes, object needs to be re-blessed
562 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
563 if ($size) { read( $fh, $class_name, $size); }
564 if ($class_name) { $obj = bless( $obj, $class_name ); }
572 # Otherwise return actual value
574 elsif ($signature eq DBM::Deep->SIG_DATA) {
577 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
578 if ($size) { read( $fh, $value, $size); }
583 # Key exists, but content is null
593 # Delete single key/value pair given tag and MD5 digested key.
596 my ($obj, $tag, $md5) = @_;
597 my $keys = $tag->{content};
602 # Iterate through buckets, looking for a key match
605 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
606 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
607 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
611 # Hit end of list, no match
616 if ( $md5 ne $key ) {
621 # Matched key -- delete bucket and return
623 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE) + $obj->_root->{file_offset}, SEEK_SET);
624 print( $fh substr($keys, ($i+1) * $BUCKET_SIZE ) );
625 print( $fh chr(0) x $BUCKET_SIZE );
635 # Check existence of single key given tag and MD5 digested key.
638 my ($obj, $tag, $md5) = @_;
639 my $keys = $tag->{content};
642 # Iterate through buckets, looking for a key match
645 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
646 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
647 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
651 # Hit end of list, no match
656 if ( $md5 ne $key ) {
661 # Matched key -- return true
669 sub find_bucket_list {
671 # Locate offset for bucket list, given digested key
674 my ($obj, $md5) = @_;
677 # Locate offset for bucket list using digest index system
680 my $tag = $self->load_tag($obj, $obj->_base_offset);
681 if (!$tag) { return; }
683 while ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
684 $tag = $self->index_lookup($obj, $tag, ord(substr($md5, $ch, 1)));
685 if (!$tag) { return; }
694 # Scan index and recursively step into deeper levels, looking for next key.
697 my ($obj, $offset, $ch, $force_return_next) = @_;
698 $force_return_next = undef unless $force_return_next;
700 my $tag = $self->load_tag($obj, $offset );
704 if ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
705 my $content = $tag->{content};
707 if ($obj->{return_next}) { $start = 0; }
708 else { $start = ord(substr($obj->{prev_md5}, $ch, 1)); }
710 for (my $index = $start; $index < 256; $index++) {
711 my $subloc = unpack($LONG_PACK, substr($content, $index * $LONG_SIZE, $LONG_SIZE) );
713 my $result = $self->traverse_index( $obj, $subloc, $ch + 1, $force_return_next );
714 if (defined($result)) { return $result; }
718 $obj->{return_next} = 1;
721 elsif ($tag->{signature} eq DBM::Deep->SIG_BLIST) {
722 my $keys = $tag->{content};
723 if ($force_return_next) { $obj->{return_next} = 1; }
726 # Iterate through buckets, looking for a key match
728 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
729 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
730 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
734 # End of bucket list -- return to outer loop
736 $obj->{return_next} = 1;
739 elsif ($key eq $obj->{prev_md5}) {
741 # Located previous key -- return next one found
743 $obj->{return_next} = 1;
746 elsif ($obj->{return_next}) {
748 # Seek to bucket location and skip over signature
750 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $obj->_root->{file_offset}, SEEK_SET);
753 # Skip over value to get to plain key
756 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
757 if ($size) { seek($fh, $size, SEEK_CUR); }
760 # Read in plain key and return as scalar
763 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
764 if ($size) { read( $fh, $plain_key, $size); }
770 $obj->{return_next} = 1;
771 } # tag is a bucket list
778 # Locate next key, given digested previous one
783 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
784 $obj->{return_next} = 0;
787 # If the previous key was not specifed, start at the top and
788 # return the first one found.
790 if (!$obj->{prev_md5}) {
791 $obj->{prev_md5} = chr(0) x $HASH_SIZE;
792 $obj->{return_next} = 1;
795 return $self->traverse_index( $obj, $obj->_base_offset, 0 );