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);
151 $self->create_tag($obj, $obj->_base_offset, $obj->_type, chr(0) x $self->{index_size});
153 my $plain_key = "[base]";
154 print( $fh pack($self->{data_pack}, length($plain_key)) . $plain_key );
156 # Flush the filehandle
157 my $old_fh = select $fh;
158 my $old_af = $|; $| = 1; $| = $old_af;
165 # Check signature was valid
167 unless ($signature eq DBM::Deep->SIG_FILE) {
168 $self->close_fh( $obj );
169 return $obj->_throw_error("Signature not found -- file is not a Deep DB");
173 # Get our type from master index signature
175 my $tag = $self->load_tag($obj, $obj->_base_offset);
177 #XXX We probably also want to store the hash algorithm name and not assume anything
178 #XXX The cool thing would be to allow a different hashing algorithm at every level
181 return $obj->_throw_error("Corrupted file, no master index record");
183 if ($obj->{type} ne $tag->{signature}) {
184 return $obj->_throw_error("File type mismatch");
194 if ( my $fh = $obj->_root->{fh} ) {
197 $obj->_root->{fh} = undef;
204 # Given offset, signature and content, create tag and write to disk
207 my ($obj, $offset, $sig, $content) = @_;
208 my $size = length($content);
212 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
213 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
215 if ($offset == $obj->_root->{end}) {
216 $obj->_root->{end} += DBM::Deep->SIG_SIZE + $self->{data_size} + $size;
222 offset => $offset + DBM::Deep->SIG_SIZE + $self->{data_size},
229 # Given offset, load single tag and return signature, size and data
232 my ($obj, $offset) = @_;
236 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
237 if (eof $fh) { return undef; }
240 read( $fh, $b, DBM::Deep->SIG_SIZE + $self->{data_size} );
241 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
244 read( $fh, $buffer, $size);
249 offset => $offset + DBM::Deep->SIG_SIZE + $self->{data_size},
256 # Given index tag, lookup single entry in index and return .
259 my ($obj, $tag, $index) = @_;
261 my $location = unpack($self->{long_pack}, substr($tag->{content}, $index * $self->{long_size}, $self->{long_size}) );
262 if (!$location) { return; }
264 return $self->load_tag( $obj, $location );
269 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
270 # plain (undigested) key and value.
273 my ($obj, $tag, $md5, $plain_key, $value) = @_;
274 my $keys = $tag->{content};
278 my $root = $obj->_root;
280 my $is_dbm_deep = eval { local $SIG{'__DIE__'}; $value->isa( 'DBM::Deep' ) };
281 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
286 # Iterate through buckets, seeing if this is a new entry or a replace.
288 for (my $i=0; $i<$self->{max_buckets}; $i++) {
289 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
292 # Found empty bucket (end of list). Populate and exit loop.
296 $location = $internal_ref
297 ? $value->_base_offset
300 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
301 print( $fh $md5 . pack($self->{long_pack}, $location) );
305 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
308 # Found existing bucket with same key. Replace with new value.
313 $location = $value->_base_offset;
314 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
315 print( $fh $md5 . pack($self->{long_pack}, $location) );
319 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $root->{file_offset}, SEEK_SET);
321 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
324 # If value is a hash, array, or raw value with equal or less size, we can
325 # reuse the same content area of the database. Otherwise, we have to create
326 # a new content area at the EOF.
329 my $r = Scalar::Util::reftype( $value ) || '';
330 if ( $r eq 'HASH' || $r eq 'ARRAY' ) {
331 $actual_length = $self->{index_size};
333 # if autobless is enabled, must also take into consideration
334 # the class name, as it is stored along with key/value.
335 if ( $root->{autobless} ) {
336 my $value_class = Scalar::Util::blessed($value);
337 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
338 $actual_length += length($value_class);
342 else { $actual_length = length($value); }
344 if ($actual_length <= $size) {
348 $location = $root->{end};
349 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $self->{hash_size} + $root->{file_offset}, SEEK_SET);
350 print( $fh pack($self->{long_pack}, $location) );
358 # If this is an internal reference, return now.
359 # No need to write value or plain key
366 # If bucket didn't fit into list, split into a new index level
369 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
370 print( $fh pack($self->{long_pack}, $root->{end}) );
372 my $index_tag = $self->create_tag($obj, $root->{end}, DBM::Deep->SIG_INDEX, chr(0) x $self->{index_size});
375 $keys .= $md5 . pack($self->{long_pack}, 0);
377 for (my $i=0; $i<=$self->{max_buckets}; $i++) {
378 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
380 my $old_subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) +
381 $self->{hash_size}, $self->{long_size}));
382 my $num = ord(substr($key, $tag->{ch} + 1, 1));
384 if ($offsets[$num]) {
385 my $offset = $offsets[$num] + DBM::Deep->SIG_SIZE + $self->{data_size};
386 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
388 read( $fh, $subkeys, $self->{bucket_list_size});
390 for (my $k=0; $k<$self->{max_buckets}; $k++) {
391 my $subloc = unpack($self->{long_pack}, substr($subkeys, ($k * $self->{bucket_size}) +
392 $self->{hash_size}, $self->{long_size}));
394 seek($fh, $offset + ($k * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
395 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
401 $offsets[$num] = $root->{end};
402 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
403 print( $fh pack($self->{long_pack}, $root->{end}) );
405 my $blist_tag = $self->create_tag($obj, $root->{end}, DBM::Deep->SIG_BLIST, chr(0) x $self->{bucket_list_size});
407 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
408 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
413 $location ||= $root->{end};
414 } # re-index bucket list
417 # Seek to content area and store signature, value and plaintext key
421 seek($fh, $location + $root->{file_offset}, SEEK_SET);
424 # Write signature based on content type, set content length and write actual value.
426 my $r = Scalar::Util::reftype($value) || '';
428 print( $fh DBM::Deep->TYPE_HASH );
429 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
430 $content_length = $self->{index_size};
432 elsif ($r eq 'ARRAY') {
433 print( $fh DBM::Deep->TYPE_ARRAY );
434 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
435 $content_length = $self->{index_size};
437 elsif (!defined($value)) {
438 print( $fh DBM::Deep->SIG_NULL );
439 print( $fh pack($self->{data_pack}, 0) );
443 print( $fh DBM::Deep->SIG_DATA );
444 print( $fh pack($self->{data_pack}, length($value)) . $value );
445 $content_length = length($value);
449 # Plain key is stored AFTER value, as keys are typically fetched less often.
451 print( $fh pack($self->{data_pack}, length($plain_key)) . $plain_key );
454 # If value is blessed, preserve class name
456 if ( $root->{autobless} ) {
457 my $value_class = Scalar::Util::blessed($value);
458 if ( defined $value_class && $value_class ne 'DBM::Deep' ) {
460 # Blessed ref -- will restore later
463 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
464 $content_length += 1;
465 $content_length += $self->{data_size} + length($value_class);
469 $content_length += 1;
474 # If this is a new content area, advance EOF counter
476 if ($location == $root->{end}) {
477 $root->{end} += DBM::Deep->SIG_SIZE;
478 $root->{end} += $self->{data_size} + $content_length;
479 $root->{end} += $self->{data_size} + length($plain_key);
483 # If content is a hash or array, create new child DBM::Deep object and
484 # pass each key or element to it.
487 my $branch = DBM::Deep->new(
488 type => DBM::Deep->TYPE_HASH,
489 base_offset => $location,
492 foreach my $key (keys %{$value}) {
493 $branch->STORE( $key, $value->{$key} );
496 elsif ($r eq 'ARRAY') {
497 my $branch = DBM::Deep->new(
498 type => DBM::Deep->TYPE_ARRAY,
499 base_offset => $location,
503 foreach my $element (@{$value}) {
504 $branch->STORE( $index, $element );
512 return $obj->_throw_error("Fatal error: indexing failed -- possibly due to corruption in file");
515 sub get_bucket_value {
517 # Fetch single value given tag and MD5 digested key.
520 my ($obj, $tag, $md5) = @_;
521 my $keys = $tag->{content};
526 # Iterate through buckets, looking for a key match
529 for (my $i=0; $i<$self->{max_buckets}; $i++) {
530 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
531 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
535 # Hit end of list, no match
540 if ( $md5 ne $key ) {
545 # Found match -- seek to offset and read signature
548 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
549 read( $fh, $signature, DBM::Deep->SIG_SIZE);
552 # If value is a hash or array, return new DBM::Deep object with correct offset
554 if (($signature eq DBM::Deep->TYPE_HASH) || ($signature eq DBM::Deep->TYPE_ARRAY)) {
555 my $obj = DBM::Deep->new(
557 base_offset => $subloc,
561 if ($obj->_root->{autobless}) {
563 # Skip over value and plain key to see if object needs
566 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
569 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
570 if ($size) { seek($fh, $size, SEEK_CUR); }
573 read( $fh, $bless_bit, 1);
574 if (ord($bless_bit)) {
576 # Yes, object needs to be re-blessed
579 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
580 if ($size) { read( $fh, $class_name, $size); }
581 if ($class_name) { $obj = bless( $obj, $class_name ); }
589 # Otherwise return actual value
591 elsif ($signature eq DBM::Deep->SIG_DATA) {
594 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
595 if ($size) { read( $fh, $value, $size); }
600 # Key exists, but content is null
610 # Delete single key/value pair given tag and MD5 digested key.
613 my ($obj, $tag, $md5) = @_;
614 my $keys = $tag->{content};
619 # Iterate through buckets, looking for a key match
622 for (my $i=0; $i<$self->{max_buckets}; $i++) {
623 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
624 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
628 # Hit end of list, no match
633 if ( $md5 ne $key ) {
638 # Matched key -- delete bucket and return
640 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $obj->_root->{file_offset}, SEEK_SET);
641 print( $fh substr($keys, ($i+1) * $self->{bucket_size} ) );
642 print( $fh chr(0) x $self->{bucket_size} );
652 # Check existence of single key given tag and MD5 digested key.
655 my ($obj, $tag, $md5) = @_;
656 my $keys = $tag->{content};
659 # Iterate through buckets, looking for a key match
662 for (my $i=0; $i<$self->{max_buckets}; $i++) {
663 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
664 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
668 # Hit end of list, no match
673 if ( $md5 ne $key ) {
678 # Matched key -- return true
686 sub find_bucket_list {
688 # Locate offset for bucket list, given digested key
691 my ($obj, $md5) = @_;
694 # Locate offset for bucket list using digest index system
697 my $tag = $self->load_tag($obj, $obj->_base_offset);
698 if (!$tag) { return; }
700 while ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
701 $tag = $self->index_lookup($obj, $tag, ord(substr($md5, $ch, 1)));
702 if (!$tag) { return; }
711 # Scan index and recursively step into deeper levels, looking for next key.
714 my ($obj, $offset, $ch, $force_return_next) = @_;
715 $force_return_next = undef unless $force_return_next;
717 my $tag = $self->load_tag($obj, $offset );
721 if ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
722 my $content = $tag->{content};
724 if ($obj->{return_next}) { $start = 0; }
725 else { $start = ord(substr($obj->{prev_md5}, $ch, 1)); }
727 for (my $index = $start; $index < 256; $index++) {
728 my $subloc = unpack($self->{long_pack}, substr($content, $index * $self->{long_size}, $self->{long_size}) );
730 my $result = $self->traverse_index( $obj, $subloc, $ch + 1, $force_return_next );
731 if (defined($result)) { return $result; }
735 $obj->{return_next} = 1;
738 elsif ($tag->{signature} eq DBM::Deep->SIG_BLIST) {
739 my $keys = $tag->{content};
740 if ($force_return_next) { $obj->{return_next} = 1; }
743 # Iterate through buckets, looking for a key match
745 for (my $i=0; $i<$self->{max_buckets}; $i++) {
746 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
747 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
751 # End of bucket list -- return to outer loop
753 $obj->{return_next} = 1;
756 elsif ($key eq $obj->{prev_md5}) {
758 # Located previous key -- return next one found
760 $obj->{return_next} = 1;
763 elsif ($obj->{return_next}) {
765 # Seek to bucket location and skip over signature
767 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $obj->_root->{file_offset}, SEEK_SET);
770 # Skip over value to get to plain key
773 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
774 if ($size) { seek($fh, $size, SEEK_CUR); }
777 # Read in plain key and return as scalar
780 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
781 if ($size) { read( $fh, $plain_key, $size); }
787 $obj->{return_next} = 1;
788 } # tag is a bucket list
795 # Locate next key, given digested previous one
800 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
801 $obj->{return_next} = 0;
804 # If the previous key was not specifed, start at the top and
805 # return the first one found.
807 if (!$obj->{prev_md5}) {
808 $obj->{prev_md5} = chr(0) x $self->{hash_size};
809 $obj->{return_next} = 1;
812 return $self->traverse_index( $obj, $obj->_base_offset, 0 );