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
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
40 # key/value. Upgrading this is possible (see above) but probably not necessary.
41 # If you need more than 4 GB for a single key or value, this module is really
44 $self->{data_size} = $data_s ? $data_s : 4;
45 $self->{data_pack} = $data_p ? $data_p : 'N';
47 return $self->precalc_sizes();
52 # Set key digest function (default is MD5)
55 my ($digest_func, $hash_size) = @_;
57 $self->{digest} = $digest_func ? $digest_func : \&Digest::MD5::md5;
58 $self->{hash_size} = $hash_size ? $hash_size : 16;
60 return $self->precalc_sizes();
73 digest => \&Digest::MD5::md5,
77 # Maximum number of buckets per list before another level of indexing is done.
78 # Increase this value for slightly greater speed, but larger database files.
79 # DO NOT decrease this value below 16, due to risk of recursive reindex overrun.
93 $self->open( $obj ) if !defined $obj->_fh;
95 #XXX We have to make sure we don't mess up when autoflush isn't turned on
96 unless ( $obj->_root->{inode} ) {
97 my @stats = stat($obj->_fh);
98 $obj->_root->{inode} = $stats[1];
99 $obj->_root->{end} = $stats[7];
107 # Open a fh to the database, create if nonexistent.
108 # Make sure file signature matches DBM::Deep spec.
113 if (defined($obj->_fh)) { $self->close_fh( $obj ); }
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 )
121 or $obj->_throw_error("Cannot sysopen file: " . $obj->_root->{file} . ": $!");
122 $obj->_root->{fh} = $fh;
124 #XXX Can we remove this by using the right sysopen() flags?
125 # Maybe ... q.v. above
126 binmode $fh; # for win32
128 if ($obj->_root->{autoflush}) {
129 my $old = select $fh;
134 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
137 my $bytes_read = read( $fh, $signature, length(DBM::Deep->SIG_FILE));
140 # File is empty -- write signature and master index
143 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
144 print( $fh DBM::Deep->SIG_FILE);
146 $self->create_tag($obj, $obj->_base_offset, $obj->_type, chr(0) x $self->{index_size});
148 # Why is this being printed here? I'm not seeing where anything actually points to
150 #XXX $obj->_root->{end} isn't updated from these 10 bytes that are being written
151 my $plain_key = "[base]";
152 print( $fh pack($self->{data_pack}, length($plain_key)) . $plain_key );
154 # Flush the filehandle
155 my $old_fh = select $fh;
156 my $old_af = $|; $| = 1; $| = $old_af;
163 # Check signature was valid
165 unless ($signature eq DBM::Deep->SIG_FILE) {
166 $self->close_fh( $obj );
167 $obj->_throw_error("Signature not found -- file is not a Deep DB");
171 # Get our type from master index signature
173 my $tag = $self->load_tag($obj, $obj->_base_offset)
174 or $obj->_throw_error("Corrupted file, no master index record");
176 unless ($obj->{type} eq $tag->{signature}) {
177 $obj->_throw_error("File type mismatch");
180 #XXX We probably also want to store the hash algorithm name and not assume anything
181 #XXX The cool thing would be to allow a different hashing algorithm at every level
190 if ( my $fh = $obj->_root->{fh} ) {
193 $obj->_root->{fh} = undef;
200 # Given offset, signature and content, create tag and write to disk
203 my ($obj, $offset, $sig, $content) = @_;
204 my $size = length($content);
208 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
209 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
211 if ($offset == $obj->_root->{end}) {
212 $obj->_root->{end} += DBM::Deep->SIG_SIZE + $self->{data_size} + $size;
218 offset => $offset + DBM::Deep->SIG_SIZE + $self->{data_size},
225 # Given offset, load single tag and return signature, size and data
228 my ($obj, $offset) = @_;
232 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
234 #XXX I'm not sure this check will work if autoflush isn't enabled ...
238 read( $fh, $b, DBM::Deep->SIG_SIZE + $self->{data_size} );
239 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
242 read( $fh, $buffer, $size);
247 offset => $offset + DBM::Deep->SIG_SIZE + $self->{data_size},
254 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
255 # plain (undigested) key and value.
258 my ($obj, $tag, $md5, $plain_key, $value) = @_;
260 my $keys = $tag->{content};
264 my $root = $obj->_root;
266 my $is_dbm_deep = eval { local $SIG{'__DIE__'}; $value->isa( 'DBM::Deep' ) };
267 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
272 # Iterate through buckets, seeing if this is a new entry or a replace.
275 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
276 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
280 # Found empty bucket (end of list). Populate and exit loop.
284 $location = $internal_ref
285 ? $value->_base_offset
287 print "NEW: $location\n";
291 $tag->{offset} + ($i * $self->{bucket_size}) + $root->{file_offset},
295 print( $fh $md5 . pack($self->{long_pack}, $location) );
299 if ( $md5 ne $key ) {
304 # Found existing bucket with same key. Replace with new value.
309 $location = $value->_base_offset;
310 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
311 print( $fh $md5 . pack($self->{long_pack}, $location) );
315 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $root->{file_offset}, SEEK_SET);
317 read( $fh, $size, $self->{data_size});
318 $size = unpack($self->{data_pack}, $size);
321 # If value is a hash, array, or raw value with equal or less size, we can
322 # reuse the same content area of the database. Otherwise, we have to create
323 # a new content area at the EOF.
326 my $r = Scalar::Util::reftype( $value ) || '';
327 if ( $r eq 'HASH' || $r eq 'ARRAY' ) {
328 $actual_length = $self->{index_size};
330 # if autobless is enabled, must also take into consideration
331 # the class name, as it is stored along with key/value.
332 if ( $root->{autobless} ) {
333 my $value_class = Scalar::Util::blessed($value);
334 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
335 $actual_length += length($value_class);
339 else { $actual_length = length($value); }
341 if ($actual_length <= $size) {
345 $location = $root->{end};
346 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $self->{hash_size} + $root->{file_offset}, SEEK_SET);
347 print( $fh pack($self->{long_pack}, $location) );
354 # If this is an internal reference, return now.
355 # No need to write value or plain key
357 #XXX We need to store the key as a reference to the internal spot
363 # If bucket didn't fit into list, split into a new index level
366 # re-index bucket list
368 $self->split_index( $obj, $md5, $tag );
370 $location = $root->{end};
374 # Seek to content area and store signature, value and plaintext key
378 seek($fh, $location + $root->{file_offset}, SEEK_SET);
381 # Write signature based on content type, set content length and write actual value.
383 my $r = Scalar::Util::reftype($value) || '';
385 print( $fh DBM::Deep->TYPE_HASH );
386 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
387 $content_length = $self->{index_size};
389 elsif ($r eq 'ARRAY') {
390 print( $fh DBM::Deep->TYPE_ARRAY );
391 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
392 $content_length = $self->{index_size};
394 elsif (!defined($value)) {
395 print( $fh DBM::Deep->SIG_NULL );
396 print( $fh pack($self->{data_pack}, 0) );
400 print( $fh DBM::Deep->SIG_DATA );
401 print( $fh pack($self->{data_pack}, length($value)) . $value );
402 $content_length = length($value);
406 # Plain key is stored AFTER value, as keys are typically fetched less often.
408 print( $fh pack($self->{data_pack}, length($plain_key)) . $plain_key );
411 # If value is blessed, preserve class name
413 if ( $root->{autobless} ) {
414 my $value_class = Scalar::Util::blessed($value);
415 if ( defined $value_class && $value_class ne 'DBM::Deep' ) {
417 # Blessed ref -- will restore later
420 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
421 $content_length += 1;
422 $content_length += $self->{data_size} + length($value_class);
426 $content_length += 1;
431 # If this is a new content area, advance EOF counter
433 if ($location == $root->{end}) {
434 $root->{end} += DBM::Deep->SIG_SIZE;
435 $root->{end} += $self->{data_size} + $content_length;
436 $root->{end} += $self->{data_size} + length($plain_key);
440 # If content is a hash or array, create new child DBM::Deep object and
441 # pass each key or element to it.
444 my $branch = DBM::Deep->new(
445 type => DBM::Deep->TYPE_HASH,
446 base_offset => $location,
449 foreach my $key (keys %{$value}) {
450 $branch->STORE( $key, $value->{$key} );
453 elsif ($r eq 'ARRAY') {
454 my $branch = DBM::Deep->new(
455 type => DBM::Deep->TYPE_ARRAY,
456 base_offset => $location,
460 foreach my $element (@{$value}) {
461 $branch->STORE( $index, $element );
469 $obj->_throw_error("Fatal error: indexing failed -- possibly due to corruption in file");
474 my ($obj, $md5, $tag) = @_;
477 my $root = $obj->_root;
478 my $keys = $tag->{content};
480 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
481 print( $fh pack($self->{long_pack}, $root->{end}) );
483 my $index_tag = $self->create_tag(
486 DBM::Deep->SIG_INDEX,
487 chr(0) x $self->{index_size},
492 $keys .= $md5 . pack($self->{long_pack}, 0);
495 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
496 my ($key, $old_subloc) = $self->_get_key_subloc( $keys, $i );
498 next BUCKET unless $key;
500 my $num = ord(substr($key, $tag->{ch} + 1, 1));
502 if ($offsets[$num]) {
503 my $offset = $offsets[$num] + DBM::Deep->SIG_SIZE + $self->{data_size};
504 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
506 read( $fh, $subkeys, $self->{bucket_list_size});
508 for (my $k=0; $k<$self->{max_buckets}; $k++) {
509 my ($temp, $subloc) = $self->_get_key_subloc( $subkeys, $k );
512 seek($fh, $offset + ($k * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
513 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
519 $offsets[$num] = $root->{end};
520 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
521 print( $fh pack($self->{long_pack}, $root->{end}) );
523 my $blist_tag = $self->create_tag($obj, $root->{end}, DBM::Deep->SIG_BLIST, chr(0) x $self->{bucket_list_size});
525 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
526 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
533 sub get_bucket_value {
535 # Fetch single value given tag and MD5 digested key.
538 my ($obj, $tag, $md5) = @_;
539 my $keys = $tag->{content};
544 # Iterate through buckets, looking for a key match
547 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
548 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
552 # Hit end of list, no match
557 if ( $md5 ne $key ) {
562 # Found match -- seek to offset and read signature
565 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
566 read( $fh, $signature, DBM::Deep->SIG_SIZE);
569 # If value is a hash or array, return new DBM::Deep object with correct offset
571 if (($signature eq DBM::Deep->TYPE_HASH) || ($signature eq DBM::Deep->TYPE_ARRAY)) {
572 my $obj = DBM::Deep->new(
574 base_offset => $subloc,
578 if ($obj->_root->{autobless}) {
580 # Skip over value and plain key to see if object needs
583 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
586 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
587 if ($size) { seek($fh, $size, SEEK_CUR); }
590 read( $fh, $bless_bit, 1);
591 if (ord($bless_bit)) {
593 # Yes, object needs to be re-blessed
596 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
597 if ($size) { read( $fh, $class_name, $size); }
598 if ($class_name) { $obj = bless( $obj, $class_name ); }
606 # Otherwise return actual value
608 elsif ($signature eq DBM::Deep->SIG_DATA) {
610 read( $fh, $size, $self->{data_size});
611 $size = unpack($self->{data_pack}, $size);
614 if ($size) { read( $fh, $value, $size); }
619 # Key exists, but content is null
629 # Delete single key/value pair given tag and MD5 digested key.
632 my ($obj, $tag, $md5) = @_;
633 my $keys = $tag->{content};
638 # Iterate through buckets, looking for a key match
641 for (my $i=0; $i<$self->{max_buckets}; $i++) {
642 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
646 # Hit end of list, no match
651 if ( $md5 ne $key ) {
656 # Matched key -- delete bucket and return
658 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $obj->_root->{file_offset}, SEEK_SET);
659 print( $fh substr($keys, ($i+1) * $self->{bucket_size} ) );
660 print( $fh chr(0) x $self->{bucket_size} );
670 # Check existence of single key given tag and MD5 digested key.
673 my ($obj, $tag, $md5) = @_;
674 my $keys = $tag->{content};
677 # Iterate through buckets, looking for a key match
680 for (my $i=0; $i<$self->{max_buckets}; $i++) {
681 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
685 # Hit end of list, no match
690 if ( $md5 ne $key ) {
695 # Matched key -- return true
703 sub find_bucket_list {
705 # Locate offset for bucket list, given digested key
708 my ($obj, $md5, $args) = @_;
709 $args = {} unless $args;
712 # Locate offset for bucket list using digest index system
714 my $tag = $self->load_tag($obj, $obj->_base_offset)
715 or $self->_throw_error( "INTERNAL ERROR - Cannot find tag" );
716 #print $obj->_base_offset, " : $tag->{signature} : $tag->{offset} : $tag->{size}\n";
719 while ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
720 my $num = ord substr($md5, $ch, 1);
722 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
723 $tag = $self->index_lookup( $obj, $tag, $num );
726 if ( $args->{create} ) {
728 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
729 print( $fh pack($self->{long_pack}, $obj->_root->{end}) );
731 $tag = $self->create_tag(
732 $obj, $obj->_root->{end},
733 DBM::Deep->SIG_BLIST,
734 chr(0) x $self->{bucket_list_size},
737 $tag->{ref_loc} = $ref_loc;
748 $tag->{ref_loc} = $ref_loc;
758 # Given index tag, lookup single entry in index and return .
761 my ($obj, $tag, $index) = @_;
763 my $location = unpack(
767 $index * $self->{long_size},
772 if (!$location) { return; }
774 return $self->load_tag( $obj, $location );
779 # Scan index and recursively step into deeper levels, looking for next key.
782 my ($obj, $offset, $ch, $force_return_next) = @_;
784 my $tag = $self->load_tag($obj, $offset );
788 if ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
789 my $content = $tag->{content};
790 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
792 for (my $index = $start; $index < 256; $index++) {
795 substr($content, $index * $self->{long_size}, $self->{long_size}),
799 my $result = $self->traverse_index(
800 $obj, $subloc, $ch + 1, $force_return_next,
803 if (defined($result)) { return $result; }
807 $obj->{return_next} = 1;
811 my $keys = $tag->{content};
812 if ($force_return_next) { $obj->{return_next} = 1; }
815 # Iterate through buckets, looking for a key match
817 for (my $i=0; $i<$self->{max_buckets}; $i++) {
818 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
822 # End of bucket list -- return to outer loop
824 $obj->{return_next} = 1;
827 elsif ($key eq $obj->{prev_md5}) {
829 # Located previous key -- return next one found
831 $obj->{return_next} = 1;
834 elsif ($obj->{return_next}) {
836 # Seek to bucket location and skip over signature
838 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $obj->_root->{file_offset}, SEEK_SET);
841 # Skip over value to get to plain key
844 read( $fh, $size, $self->{data_size});
845 $size = unpack($self->{data_pack}, $size);
846 if ($size) { seek($fh, $size, SEEK_CUR); }
849 # Read in plain key and return as scalar
852 read( $fh, $size, $self->{data_size});
853 $size = unpack($self->{data_pack}, $size);
854 if ($size) { read( $fh, $plain_key, $size); }
860 $obj->{return_next} = 1;
861 } # tag is a bucket list
868 # Locate next key, given digested previous one
873 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
874 $obj->{return_next} = 0;
877 # If the previous key was not specifed, start at the top and
878 # return the first one found.
880 if (!$obj->{prev_md5}) {
881 $obj->{prev_md5} = chr(0) x $self->{hash_size};
882 $obj->{return_next} = 1;
885 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
890 sub _get_key_subloc {
892 my ($keys, $idx) = @_;
894 my ($key, $subloc) = unpack(
895 "a$self->{hash_size} $self->{long_pack}",
898 ($idx * $self->{bucket_size}),
899 $self->{bucket_size},
903 return ($key, $subloc);