1 package DBM::Deep::Engine;
6 use Fcntl qw( :DEFAULT :flock :seek );
10 # Precalculate index, bucket and bucket list sizes
14 $self->{index_size} = (2**8) * $self->{long_size};
15 $self->{bucket_size} = $self->{hash_size} + $self->{long_size};
16 $self->{bucket_list_size} = $self->{max_buckets} * $self->{bucket_size};
23 # Set pack/unpack modes (see file header for more)
26 my ($long_s, $long_p, $data_s, $data_p) = @_;
29 # Set to 4 and 'N' for 32-bit offset tags (default). Theoretical limit of 4 GB per file.
30 # (Perl must be compiled with largefile support for files > 2 GB)
32 # Set to 8 and 'Q' for 64-bit offsets. Theoretical limit of 16 XB per file.
33 # (Perl must be compiled with largefile and 64-bit long support)
35 $self->{long_size} = $long_s ? $long_s : 4;
36 $self->{long_pack} = $long_p ? $long_p : 'N';
39 # Set to 4 and 'N' for 32-bit data length prefixes. Limit of 4 GB for each key/value.
40 # Upgrading this is possible (see above) but probably not necessary. If you need
41 # more than 4 GB for a single key or value, this module is really not for you :-)
43 $self->{data_size} = $data_s ? $data_s : 4;
44 $self->{data_pack} = $data_p ? $data_p : 'N';
46 return $self->precalc_sizes();
51 # Set key digest function (default is MD5)
54 my ($digest_func, $hash_size) = @_;
56 $self->{digest} = $digest_func ? $digest_func : \&Digest::MD5::md5;
57 $self->{hash_size} = $hash_size ? $hash_size : 16;
59 return $self->precalc_sizes();
72 digest => \&Digest::MD5::md5,
76 # Maximum number of buckets per list before another level of indexing is done.
77 # Increase this value for slightly greater speed, but larger database files.
78 # DO NOT decrease this value below 16, due to risk of recursive reindex overrun.
92 $self->open( $obj ) if !defined $obj->_fh;
94 #XXX We have to make sure we don't mess up when autoflush isn't turned on
95 unless ( $obj->_root->{inode} ) {
96 my @stats = stat($obj->_fh);
97 $obj->_root->{inode} = $stats[1];
98 $obj->_root->{end} = $stats[7];
106 # Open a fh to the database, create if nonexistent.
107 # Make sure file signature matches DBM::Deep spec.
112 if (defined($obj->_fh)) { $self->close_fh( $obj ); }
114 # Theoretically, adding O_BINARY should remove the need for the binmode
115 # Of course, testing it is going to be ... interesting.
116 my $flags = O_RDWR | O_CREAT | O_BINARY;
119 sysopen( $fh, $obj->_root->{file}, $flags )
120 or $obj->_throw_error("Cannot sysopen file: " . $obj->_root->{file} . ": $!");
121 $obj->_root->{fh} = $fh;
123 #XXX Can we remove this by using the right sysopen() flags?
124 # Maybe ... q.v. above
125 binmode $fh; # for win32
127 if ($obj->_root->{autoflush}) {
128 my $old = select $fh;
133 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
136 my $bytes_read = read( $fh, $signature, length(DBM::Deep->SIG_FILE));
139 # File is empty -- write signature and master index
142 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
143 print( $fh DBM::Deep->SIG_FILE);
145 $self->create_tag($obj, $obj->_base_offset, $obj->_type, chr(0) x $self->{index_size});
147 # Why is this being printed here? I'm not seeing where anything actually points to
149 #XXX $obj->_root->{end} isn't updated from these 10 bytes that are being written
150 my $plain_key = "[base]";
151 print( $fh pack($self->{data_pack}, length($plain_key)) . $plain_key );
153 # Flush the filehandle
154 my $old_fh = select $fh;
155 my $old_af = $|; $| = 1; $| = $old_af;
162 # Check signature was valid
164 unless ($signature eq DBM::Deep->SIG_FILE) {
165 $self->close_fh( $obj );
166 $obj->_throw_error("Signature not found -- file is not a Deep DB");
170 # Get our type from master index signature
172 my $tag = $self->load_tag($obj, $obj->_base_offset)
173 or $obj->_throw_error("Corrupted file, no master index record");
175 unless ($obj->{type} eq $tag->{signature}) {
176 $obj->_throw_error("File type mismatch");
179 #XXX We probably also want to store the hash algorithm name and not assume anything
180 #XXX The cool thing would be to allow a different hashing algorithm at every level
189 if ( my $fh = $obj->_root->{fh} ) {
192 $obj->_root->{fh} = undef;
199 # Given offset, signature and content, create tag and write to disk
202 my ($obj, $offset, $sig, $content) = @_;
203 my $size = length($content);
207 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
208 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
210 if ($offset == $obj->_root->{end}) {
211 $obj->_root->{end} += DBM::Deep->SIG_SIZE + $self->{data_size} + $size;
217 offset => $offset + DBM::Deep->SIG_SIZE + $self->{data_size},
224 # Given offset, load single tag and return signature, size and data
227 my ($obj, $offset) = @_;
231 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
233 #XXX I'm not sure this check will work given autoflush ...
237 read( $fh, $b, DBM::Deep->SIG_SIZE + $self->{data_size} );
238 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
241 read( $fh, $buffer, $size);
246 offset => $offset + DBM::Deep->SIG_SIZE + $self->{data_size},
253 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
254 # plain (undigested) key and value.
257 my ($obj, $tag, $md5, $plain_key, $value) = @_;
258 my $keys = $tag->{content};
262 my $root = $obj->_root;
264 my $is_dbm_deep = eval { local $SIG{'__DIE__'}; $value->isa( 'DBM::Deep' ) };
265 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
270 # Iterate through buckets, seeing if this is a new entry or a replace.
272 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
273 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
276 # Found empty bucket (end of list). Populate and exit loop.
280 $location = $internal_ref
281 ? $value->_base_offset
283 print "NEW: $location\n";
285 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
286 print( $fh $md5 . pack($self->{long_pack}, $location) );
290 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
293 # Found existing bucket with same key. Replace with new value.
298 $location = $value->_base_offset;
299 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
300 print( $fh $md5 . pack($self->{long_pack}, $location) );
304 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $root->{file_offset}, SEEK_SET);
306 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
309 # If value is a hash, array, or raw value with equal or less size, we can
310 # reuse the same content area of the database. Otherwise, we have to create
311 # a new content area at the EOF.
314 my $r = Scalar::Util::reftype( $value ) || '';
315 if ( $r eq 'HASH' || $r eq 'ARRAY' ) {
316 $actual_length = $self->{index_size};
318 # if autobless is enabled, must also take into consideration
319 # the class name, as it is stored along with key/value.
320 if ( $root->{autobless} ) {
321 my $value_class = Scalar::Util::blessed($value);
322 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
323 $actual_length += length($value_class);
327 else { $actual_length = length($value); }
329 if ($actual_length <= $size) {
333 $location = $root->{end};
334 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $self->{hash_size} + $root->{file_offset}, SEEK_SET);
335 print( $fh pack($self->{long_pack}, $location) );
343 # If this is an internal reference, return now.
344 # No need to write value or plain key
351 # If bucket didn't fit into list, split into a new index level
354 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
355 print( $fh pack($self->{long_pack}, $root->{end}) );
357 my $index_tag = $self->create_tag($obj, $root->{end}, DBM::Deep->SIG_INDEX, chr(0) x $self->{index_size});
360 $keys .= $md5 . pack($self->{long_pack}, 0);
362 for (my $i=0; $i<=$self->{max_buckets}; $i++) {
363 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
365 my $old_subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) +
366 $self->{hash_size}, $self->{long_size}));
367 my $num = ord(substr($key, $tag->{ch} + 1, 1));
369 if ($offsets[$num]) {
370 my $offset = $offsets[$num] + DBM::Deep->SIG_SIZE + $self->{data_size};
371 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
373 read( $fh, $subkeys, $self->{bucket_list_size});
375 for (my $k=0; $k<$self->{max_buckets}; $k++) {
376 my $subloc = unpack($self->{long_pack}, substr($subkeys, ($k * $self->{bucket_size}) +
377 $self->{hash_size}, $self->{long_size}));
379 seek($fh, $offset + ($k * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
380 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
386 $offsets[$num] = $root->{end};
387 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
388 print( $fh pack($self->{long_pack}, $root->{end}) );
390 my $blist_tag = $self->create_tag($obj, $root->{end}, DBM::Deep->SIG_BLIST, chr(0) x $self->{bucket_list_size});
392 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
393 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
398 $location ||= $root->{end};
399 } # re-index bucket list
402 # Seek to content area and store signature, value and plaintext key
406 seek($fh, $location + $root->{file_offset}, SEEK_SET);
409 # Write signature based on content type, set content length and write actual value.
411 my $r = Scalar::Util::reftype($value) || '';
413 print( $fh DBM::Deep->TYPE_HASH );
414 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
415 $content_length = $self->{index_size};
417 elsif ($r eq 'ARRAY') {
418 print( $fh DBM::Deep->TYPE_ARRAY );
419 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
420 $content_length = $self->{index_size};
422 elsif (!defined($value)) {
423 print( $fh DBM::Deep->SIG_NULL );
424 print( $fh pack($self->{data_pack}, 0) );
428 print( $fh DBM::Deep->SIG_DATA );
429 print( $fh pack($self->{data_pack}, length($value)) . $value );
430 $content_length = length($value);
434 # Plain key is stored AFTER value, as keys are typically fetched less often.
436 print( $fh pack($self->{data_pack}, length($plain_key)) . $plain_key );
439 # If value is blessed, preserve class name
441 if ( $root->{autobless} ) {
442 my $value_class = Scalar::Util::blessed($value);
443 if ( defined $value_class && $value_class ne 'DBM::Deep' ) {
445 # Blessed ref -- will restore later
448 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
449 $content_length += 1;
450 $content_length += $self->{data_size} + length($value_class);
454 $content_length += 1;
459 # If this is a new content area, advance EOF counter
461 if ($location == $root->{end}) {
462 $root->{end} += DBM::Deep->SIG_SIZE;
463 $root->{end} += $self->{data_size} + $content_length;
464 $root->{end} += $self->{data_size} + length($plain_key);
468 # If content is a hash or array, create new child DBM::Deep object and
469 # pass each key or element to it.
472 my $branch = DBM::Deep->new(
473 type => DBM::Deep->TYPE_HASH,
474 base_offset => $location,
477 foreach my $key (keys %{$value}) {
478 $branch->STORE( $key, $value->{$key} );
481 elsif ($r eq 'ARRAY') {
482 my $branch = DBM::Deep->new(
483 type => DBM::Deep->TYPE_ARRAY,
484 base_offset => $location,
488 foreach my $element (@{$value}) {
489 $branch->STORE( $index, $element );
497 $obj->_throw_error("Fatal error: indexing failed -- possibly due to corruption in file");
500 sub get_bucket_value {
502 # Fetch single value given tag and MD5 digested key.
505 my ($obj, $tag, $md5) = @_;
506 my $keys = $tag->{content};
511 # Iterate through buckets, looking for a key match
514 for (my $i=0; $i<$self->{max_buckets}; $i++) {
515 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
516 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
520 # Hit end of list, no match
525 if ( $md5 ne $key ) {
530 # Found match -- seek to offset and read signature
533 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
534 read( $fh, $signature, DBM::Deep->SIG_SIZE);
537 # If value is a hash or array, return new DBM::Deep object with correct offset
539 if (($signature eq DBM::Deep->TYPE_HASH) || ($signature eq DBM::Deep->TYPE_ARRAY)) {
540 my $obj = DBM::Deep->new(
542 base_offset => $subloc,
546 if ($obj->_root->{autobless}) {
548 # Skip over value and plain key to see if object needs
551 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
554 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
555 if ($size) { seek($fh, $size, SEEK_CUR); }
558 read( $fh, $bless_bit, 1);
559 if (ord($bless_bit)) {
561 # Yes, object needs to be re-blessed
564 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
565 if ($size) { read( $fh, $class_name, $size); }
566 if ($class_name) { $obj = bless( $obj, $class_name ); }
574 # Otherwise return actual value
576 elsif ($signature eq DBM::Deep->SIG_DATA) {
579 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
580 if ($size) { read( $fh, $value, $size); }
585 # Key exists, but content is null
595 # Delete single key/value pair given tag and MD5 digested key.
598 my ($obj, $tag, $md5) = @_;
599 my $keys = $tag->{content};
604 # Iterate through buckets, looking for a key match
607 for (my $i=0; $i<$self->{max_buckets}; $i++) {
608 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
609 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
613 # Hit end of list, no match
618 if ( $md5 ne $key ) {
623 # Matched key -- delete bucket and return
625 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $obj->_root->{file_offset}, SEEK_SET);
626 print( $fh substr($keys, ($i+1) * $self->{bucket_size} ) );
627 print( $fh chr(0) x $self->{bucket_size} );
637 # Check existence of single key given tag and MD5 digested key.
640 my ($obj, $tag, $md5) = @_;
641 my $keys = $tag->{content};
644 # Iterate through buckets, looking for a key match
647 for (my $i=0; $i<$self->{max_buckets}; $i++) {
648 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
649 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
653 # Hit end of list, no match
658 if ( $md5 ne $key ) {
663 # Matched key -- return true
671 sub find_bucket_list {
673 # Locate offset for bucket list, given digested key
676 my ($obj, $md5, $args) = @_;
677 $args = {} unless $args;
680 # Locate offset for bucket list using digest index system
682 my $tag = $self->load_tag($obj, $obj->_base_offset)
683 or $self->_throw_error( "INTERNAL ERROR - Cannot find tag" );
684 #print $obj->_base_offset, " : $tag->{signature} : $tag->{offset} : $tag->{size}\n";
687 while ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
688 my $num = ord substr($md5, $ch, 1);
690 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
691 $tag = $self->index_lookup( $obj, $tag, $num );
694 if ( $args->{create} ) {
696 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
697 print( $fh pack($self->{long_pack}, $obj->_root->{end}) );
699 $tag = $self->create_tag(
700 $obj, $obj->_root->{end},
701 DBM::Deep->SIG_BLIST,
702 chr(0) x $self->{bucket_list_size},
705 $tag->{ref_loc} = $ref_loc;
716 $tag->{ref_loc} = $ref_loc;
726 # Given index tag, lookup single entry in index and return .
729 my ($obj, $tag, $index) = @_;
731 my $location = unpack(
735 $index * $self->{long_size},
740 if (!$location) { return; }
742 return $self->load_tag( $obj, $location );
747 # Scan index and recursively step into deeper levels, looking for next key.
750 my ($obj, $offset, $ch, $force_return_next) = @_;
752 my $tag = $self->load_tag($obj, $offset );
756 if ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
757 my $content = $tag->{content};
758 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
760 for (my $index = $start; $index < 256; $index++) {
763 substr($content, $index * $self->{long_size}, $self->{long_size}),
767 my $result = $self->traverse_index(
768 $obj, $subloc, $ch + 1, $force_return_next,
771 if (defined($result)) { return $result; }
775 $obj->{return_next} = 1;
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});
791 ($i * $self->{bucket_size}) + $self->{hash_size},
798 # End of bucket list -- return to outer loop
800 $obj->{return_next} = 1;
803 elsif ($key eq $obj->{prev_md5}) {
805 # Located previous key -- return next one found
807 $obj->{return_next} = 1;
810 elsif ($obj->{return_next}) {
812 # Seek to bucket location and skip over signature
814 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $obj->_root->{file_offset}, SEEK_SET);
817 # Skip over value to get to plain key
820 read( $fh, $size, $self->{data_size});
821 $size = unpack($self->{data_pack}, $size);
822 if ($size) { seek($fh, $size, SEEK_CUR); }
825 # Read in plain key and return as scalar
828 read( $fh, $size, $self->{data_size});
829 $size = unpack($self->{data_pack}, $size);
830 if ($size) { read( $fh, $plain_key, $size); }
836 $obj->{return_next} = 1;
837 } # tag is a bucket list
844 # Locate next key, given digested previous one
849 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
850 $obj->{return_next} = 0;
853 # If the previous key was not specifed, start at the top and
854 # return the first one found.
856 if (!$obj->{prev_md5}) {
857 $obj->{prev_md5} = chr(0) x $self->{hash_size};
858 $obj->{return_next} = 1;
861 return $self->traverse_index( $obj, $obj->_base_offset, 0 );