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;
72 # Open a fh to the database, create if nonexistent.
73 # Make sure file signature matches DBM::Deep spec.
78 if (defined($obj->_fh)) { $self->close( $obj ); }
81 local $SIG{'__DIE__'};
82 # Theoretically, adding O_BINARY should remove the need for the binmode
83 # Of course, testing it is going to be ... interesting.
84 my $flags = O_RDWR | O_CREAT | O_BINARY;
87 sysopen( $fh, $obj->_root->{file}, $flags )
89 $obj->_root->{fh} = $fh;
90 }; if ($@ ) { $obj->_throw_error( "Received error: $@\n" ); }
91 if (! defined($obj->_fh)) {
92 return $obj->_throw_error("Cannot sysopen file: " . $obj->_root->{file} . ": $!");
97 #XXX Can we remove this by using the right sysopen() flags?
98 # Maybe ... q.v. above
99 binmode $fh; # for win32
101 if ($obj->_root->{autoflush}) {
102 my $old = select $fh;
107 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
110 my $bytes_read = read( $fh, $signature, length(DBM::Deep->SIG_FILE));
113 # File is empty -- write signature and master index
116 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
117 print( $fh DBM::Deep->SIG_FILE);
118 $self->create_tag($obj, $obj->_base_offset, $obj->_type, chr(0) x $INDEX_SIZE);
120 my $plain_key = "[base]";
121 print( $fh pack($DATA_LENGTH_PACK, length($plain_key)) . $plain_key );
123 # Flush the filehandle
124 my $old_fh = select $fh;
125 my $old_af = $|; $| = 1; $| = $old_af;
128 my @stats = stat($fh);
129 $obj->_root->{inode} = $stats[1];
130 $obj->_root->{end} = $stats[7];
136 # Check signature was valid
138 unless ($signature eq DBM::Deep->SIG_FILE) {
139 $self->close( $obj );
140 return $obj->_throw_error("Signature not found -- file is not a Deep DB");
143 my @stats = stat($fh);
144 $obj->_root->{inode} = $stats[1];
145 $obj->_root->{end} = $stats[7];
148 # Get our type from master index signature
150 my $tag = $self->load_tag($obj, $obj->_base_offset);
152 #XXX We probably also want to store the hash algorithm name and not assume anything
153 #XXX The cool thing would be to allow a different hashing algorithm at every level
156 return $obj->_throw_error("Corrupted file, no master index record");
158 if ($obj->{type} ne $tag->{signature}) {
159 return $obj->_throw_error("File type mismatch");
169 if ( my $fh = $obj->_root->{fh} ) {
172 $obj->_root->{fh} = undef;
179 # Given offset, signature and content, create tag and write to disk
182 my ($obj, $offset, $sig, $content) = @_;
183 my $size = length($content);
187 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
188 print( $fh $sig . pack($DATA_LENGTH_PACK, $size) . $content );
190 if ($offset == $obj->_root->{end}) {
191 $obj->_root->{end} += DBM::Deep->SIG_SIZE + $DATA_LENGTH_SIZE + $size;
197 offset => $offset + DBM::Deep->SIG_SIZE + $DATA_LENGTH_SIZE,
204 # Given offset, load single tag and return signature, size and data
207 my ($obj, $offset) = @_;
211 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
212 if (eof $fh) { return undef; }
215 read( $fh, $b, DBM::Deep->SIG_SIZE + $DATA_LENGTH_SIZE );
216 my ($sig, $size) = unpack( "A $DATA_LENGTH_PACK", $b );
219 read( $fh, $buffer, $size);
224 offset => $offset + DBM::Deep->SIG_SIZE + $DATA_LENGTH_SIZE,
231 # Given index tag, lookup single entry in index and return .
234 my ($obj, $tag, $index) = @_;
236 my $location = unpack($LONG_PACK, substr($tag->{content}, $index * $LONG_SIZE, $LONG_SIZE) );
237 if (!$location) { return; }
239 return $self->load_tag( $obj, $location );
244 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
245 # plain (undigested) key and value.
248 my ($obj, $tag, $md5, $plain_key, $value) = @_;
249 my $keys = $tag->{content};
253 my $root = $obj->_root;
255 my $is_dbm_deep = eval { local $SIG{'__DIE__'}; $value->isa( 'DBM::Deep' ) };
256 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
261 # Iterate through buckets, seeing if this is a new entry or a replace.
263 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
264 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
267 # Found empty bucket (end of list). Populate and exit loop.
271 $location = $internal_ref
272 ? $value->_base_offset
275 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE) + $root->{file_offset}, SEEK_SET);
276 print( $fh $md5 . pack($LONG_PACK, $location) );
280 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
283 # Found existing bucket with same key. Replace with new value.
288 $location = $value->_base_offset;
289 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE) + $root->{file_offset}, SEEK_SET);
290 print( $fh $md5 . pack($LONG_PACK, $location) );
294 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $root->{file_offset}, SEEK_SET);
296 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
299 # If value is a hash, array, or raw value with equal or less size, we can
300 # reuse the same content area of the database. Otherwise, we have to create
301 # a new content area at the EOF.
304 my $r = Scalar::Util::reftype( $value ) || '';
305 if ( $r eq 'HASH' || $r eq 'ARRAY' ) {
306 $actual_length = $INDEX_SIZE;
308 # if autobless is enabled, must also take into consideration
309 # the class name, as it is stored along with key/value.
310 if ( $root->{autobless} ) {
311 my $value_class = Scalar::Util::blessed($value);
312 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
313 $actual_length += length($value_class);
317 else { $actual_length = length($value); }
319 if ($actual_length <= $size) {
323 $location = $root->{end};
324 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE) + $HASH_SIZE + $root->{file_offset}, SEEK_SET);
325 print( $fh pack($LONG_PACK, $location) );
333 # If this is an internal reference, return now.
334 # No need to write value or plain key
341 # If bucket didn't fit into list, split into a new index level
344 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
345 print( $fh pack($LONG_PACK, $root->{end}) );
347 my $index_tag = $self->create_tag($obj, $root->{end}, DBM::Deep->SIG_INDEX, chr(0) x $INDEX_SIZE);
350 $keys .= $md5 . pack($LONG_PACK, 0);
352 for (my $i=0; $i<=$MAX_BUCKETS; $i++) {
353 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
355 my $old_subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) +
356 $HASH_SIZE, $LONG_SIZE));
357 my $num = ord(substr($key, $tag->{ch} + 1, 1));
359 if ($offsets[$num]) {
360 my $offset = $offsets[$num] + DBM::Deep->SIG_SIZE + $DATA_LENGTH_SIZE;
361 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
363 read( $fh, $subkeys, $BUCKET_LIST_SIZE);
365 for (my $k=0; $k<$MAX_BUCKETS; $k++) {
366 my $subloc = unpack($LONG_PACK, substr($subkeys, ($k * $BUCKET_SIZE) +
367 $HASH_SIZE, $LONG_SIZE));
369 seek($fh, $offset + ($k * $BUCKET_SIZE) + $root->{file_offset}, SEEK_SET);
370 print( $fh $key . pack($LONG_PACK, $old_subloc || $root->{end}) );
376 $offsets[$num] = $root->{end};
377 seek($fh, $index_tag->{offset} + ($num * $LONG_SIZE) + $root->{file_offset}, SEEK_SET);
378 print( $fh pack($LONG_PACK, $root->{end}) );
380 my $blist_tag = $self->create_tag($obj, $root->{end}, DBM::Deep->SIG_BLIST, chr(0) x $BUCKET_LIST_SIZE);
382 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
383 print( $fh $key . pack($LONG_PACK, $old_subloc || $root->{end}) );
388 $location ||= $root->{end};
389 } # re-index bucket list
392 # Seek to content area and store signature, value and plaintext key
396 seek($fh, $location + $root->{file_offset}, SEEK_SET);
399 # Write signature based on content type, set content length and write actual value.
401 my $r = Scalar::Util::reftype($value) || '';
403 print( $fh DBM::Deep->TYPE_HASH );
404 print( $fh pack($DATA_LENGTH_PACK, $INDEX_SIZE) . chr(0) x $INDEX_SIZE );
405 $content_length = $INDEX_SIZE;
407 elsif ($r eq 'ARRAY') {
408 print( $fh DBM::Deep->TYPE_ARRAY );
409 print( $fh pack($DATA_LENGTH_PACK, $INDEX_SIZE) . chr(0) x $INDEX_SIZE );
410 $content_length = $INDEX_SIZE;
412 elsif (!defined($value)) {
413 print( $fh DBM::Deep->SIG_NULL );
414 print( $fh pack($DATA_LENGTH_PACK, 0) );
418 print( $fh DBM::Deep->SIG_DATA );
419 print( $fh pack($DATA_LENGTH_PACK, length($value)) . $value );
420 $content_length = length($value);
424 # Plain key is stored AFTER value, as keys are typically fetched less often.
426 print( $fh pack($DATA_LENGTH_PACK, length($plain_key)) . $plain_key );
429 # If value is blessed, preserve class name
431 if ( $root->{autobless} ) {
432 my $value_class = Scalar::Util::blessed($value);
433 if ( defined $value_class && $value_class ne 'DBM::Deep' ) {
435 # Blessed ref -- will restore later
438 print( $fh pack($DATA_LENGTH_PACK, length($value_class)) . $value_class );
439 $content_length += 1;
440 $content_length += $DATA_LENGTH_SIZE + length($value_class);
444 $content_length += 1;
449 # If this is a new content area, advance EOF counter
451 if ($location == $root->{end}) {
452 $root->{end} += DBM::Deep->SIG_SIZE;
453 $root->{end} += $DATA_LENGTH_SIZE + $content_length;
454 $root->{end} += $DATA_LENGTH_SIZE + length($plain_key);
458 # If content is a hash or array, create new child DBM::Deep object and
459 # pass each key or element to it.
462 my $branch = DBM::Deep->new(
463 type => DBM::Deep->TYPE_HASH,
464 base_offset => $location,
467 foreach my $key (keys %{$value}) {
468 $branch->STORE( $key, $value->{$key} );
471 elsif ($r eq 'ARRAY') {
472 my $branch = DBM::Deep->new(
473 type => DBM::Deep->TYPE_ARRAY,
474 base_offset => $location,
478 foreach my $element (@{$value}) {
479 $branch->STORE( $index, $element );
487 return $obj->_throw_error("Fatal error: indexing failed -- possibly due to corruption in file");
490 sub get_bucket_value {
492 # Fetch single value given tag and MD5 digested key.
495 my ($obj, $tag, $md5) = @_;
496 my $keys = $tag->{content};
501 # Iterate through buckets, looking for a key match
504 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
505 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
506 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
510 # Hit end of list, no match
515 if ( $md5 ne $key ) {
520 # Found match -- seek to offset and read signature
523 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
524 read( $fh, $signature, DBM::Deep->SIG_SIZE);
527 # If value is a hash or array, return new DBM::Deep object with correct offset
529 if (($signature eq DBM::Deep->TYPE_HASH) || ($signature eq DBM::Deep->TYPE_ARRAY)) {
530 my $obj = DBM::Deep->new(
532 base_offset => $subloc,
536 if ($obj->_root->{autobless}) {
538 # Skip over value and plain key to see if object needs
541 seek($fh, $DATA_LENGTH_SIZE + $INDEX_SIZE, SEEK_CUR);
544 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
545 if ($size) { seek($fh, $size, SEEK_CUR); }
548 read( $fh, $bless_bit, 1);
549 if (ord($bless_bit)) {
551 # Yes, object needs to be re-blessed
554 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
555 if ($size) { read( $fh, $class_name, $size); }
556 if ($class_name) { $obj = bless( $obj, $class_name ); }
564 # Otherwise return actual value
566 elsif ($signature eq DBM::Deep->SIG_DATA) {
569 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
570 if ($size) { read( $fh, $value, $size); }
575 # Key exists, but content is null
585 # Delete single key/value pair given tag and MD5 digested key.
588 my ($obj, $tag, $md5) = @_;
589 my $keys = $tag->{content};
594 # Iterate through buckets, looking for a key match
597 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
598 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
599 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
603 # Hit end of list, no match
608 if ( $md5 ne $key ) {
613 # Matched key -- delete bucket and return
615 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE) + $obj->_root->{file_offset}, SEEK_SET);
616 print( $fh substr($keys, ($i+1) * $BUCKET_SIZE ) );
617 print( $fh chr(0) x $BUCKET_SIZE );
627 # Check existence of single key given tag and MD5 digested key.
630 my ($obj, $tag, $md5) = @_;
631 my $keys = $tag->{content};
634 # Iterate through buckets, looking for a key match
637 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
638 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
639 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
643 # Hit end of list, no match
648 if ( $md5 ne $key ) {
653 # Matched key -- return true
661 sub find_bucket_list {
663 # Locate offset for bucket list, given digested key
666 my ($obj, $md5) = @_;
669 # Locate offset for bucket list using digest index system
672 my $tag = $self->load_tag($obj, $obj->_base_offset);
673 if (!$tag) { return; }
675 while ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
676 $tag = $self->index_lookup($obj, $tag, ord(substr($md5, $ch, 1)));
677 if (!$tag) { return; }
686 # Scan index and recursively step into deeper levels, looking for next key.
689 my ($obj, $offset, $ch, $force_return_next) = @_;
690 $force_return_next = undef unless $force_return_next;
692 my $tag = $self->load_tag($obj, $offset );
696 if ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
697 my $content = $tag->{content};
699 if ($obj->{return_next}) { $start = 0; }
700 else { $start = ord(substr($obj->{prev_md5}, $ch, 1)); }
702 for (my $index = $start; $index < 256; $index++) {
703 my $subloc = unpack($LONG_PACK, substr($content, $index * $LONG_SIZE, $LONG_SIZE) );
705 my $result = $self->traverse_index( $obj, $subloc, $ch + 1, $force_return_next );
706 if (defined($result)) { return $result; }
710 $obj->{return_next} = 1;
713 elsif ($tag->{signature} eq DBM::Deep->SIG_BLIST) {
714 my $keys = $tag->{content};
715 if ($force_return_next) { $obj->{return_next} = 1; }
718 # Iterate through buckets, looking for a key match
720 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
721 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
722 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
726 # End of bucket list -- return to outer loop
728 $obj->{return_next} = 1;
731 elsif ($key eq $obj->{prev_md5}) {
733 # Located previous key -- return next one found
735 $obj->{return_next} = 1;
738 elsif ($obj->{return_next}) {
740 # Seek to bucket location and skip over signature
742 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $obj->_root->{file_offset}, SEEK_SET);
745 # Skip over value to get to plain key
748 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
749 if ($size) { seek($fh, $size, SEEK_CUR); }
752 # Read in plain key and return as scalar
755 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
756 if ($size) { read( $fh, $plain_key, $size); }
762 $obj->{return_next} = 1;
763 } # tag is a bucket list
770 # Locate next key, given digested previous one
775 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
776 $obj->{return_next} = 0;
779 # If the previous key was not specifed, start at the top and
780 # return the first one found.
782 if (!$obj->{prev_md5}) {
783 $obj->{prev_md5} = chr(0) x $HASH_SIZE;
784 $obj->{return_next} = 1;
787 return $self->traverse_index( $obj, $obj->_base_offset, 0 );