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 We have to make sure we don't mess up when autoflush isn't turned on
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 ); }
113 # Theoretically, adding O_BINARY should remove the need for the binmode
114 # Of course, testing it is going to be ... interesting.
115 my $flags = O_RDWR | O_CREAT | O_BINARY;
118 sysopen( $fh, $obj->_root->{file}, $flags )
119 or $obj->_throw_error("Cannot sysopen file: " . $obj->_root->{file} . ": $!");
120 $obj->_root->{fh} = $fh;
122 #XXX Can we remove this by using the right sysopen() flags?
123 # Maybe ... q.v. above
124 binmode $fh; # for win32
126 if ($obj->_root->{autoflush}) {
127 my $old = select $fh;
132 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
135 my $bytes_read = read( $fh, $signature, length(DBM::Deep->SIG_FILE));
138 # File is empty -- write signature and master index
141 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
142 print( $fh DBM::Deep->SIG_FILE);
144 $self->create_tag($obj, $obj->_base_offset, $obj->_type, chr(0) x $self->{index_size});
146 my $plain_key = "[base]";
147 print( $fh pack($self->{data_pack}, length($plain_key)) . $plain_key );
149 # Flush the filehandle
150 my $old_fh = select $fh;
151 my $old_af = $|; $| = 1; $| = $old_af;
158 # Check signature was valid
160 unless ($signature eq DBM::Deep->SIG_FILE) {
161 $self->close_fh( $obj );
162 return $obj->_throw_error("Signature not found -- file is not a Deep DB");
166 # Get our type from master index signature
168 my $tag = $self->load_tag($obj, $obj->_base_offset);
170 return $obj->_throw_error("Corrupted file, no master index record");
173 if ($obj->{type} ne $tag->{signature}) {
174 return $obj->_throw_error("File type mismatch");
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
187 if ( my $fh = $obj->_root->{fh} ) {
190 $obj->_root->{fh} = undef;
197 # Given offset, signature and content, create tag and write to disk
200 my ($obj, $offset, $sig, $content) = @_;
201 my $size = length($content);
205 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
206 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
208 if ($offset == $obj->_root->{end}) {
209 $obj->_root->{end} += DBM::Deep->SIG_SIZE + $self->{data_size} + $size;
215 offset => $offset + DBM::Deep->SIG_SIZE + $self->{data_size},
222 # Given offset, load single tag and return signature, size and data
225 my ($obj, $offset) = @_;
229 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
230 if (eof $fh) { return undef; }
233 read( $fh, $b, DBM::Deep->SIG_SIZE + $self->{data_size} );
234 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
237 read( $fh, $buffer, $size);
242 offset => $offset + DBM::Deep->SIG_SIZE + $self->{data_size},
249 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
250 # plain (undigested) key and value.
253 my ($obj, $tag, $md5, $plain_key, $value) = @_;
254 my $keys = $tag->{content};
258 my $root = $obj->_root;
260 my $is_dbm_deep = eval { local $SIG{'__DIE__'}; $value->isa( 'DBM::Deep' ) };
261 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
266 # Iterate through buckets, seeing if this is a new entry or a replace.
268 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
269 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
272 # Found empty bucket (end of list). Populate and exit loop.
276 $location = $internal_ref
277 ? $value->_base_offset
280 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
281 print( $fh $md5 . pack($self->{long_pack}, $location) );
285 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
288 # Found existing bucket with same key. Replace with new value.
293 $location = $value->_base_offset;
294 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
295 print( $fh $md5 . pack($self->{long_pack}, $location) );
299 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $root->{file_offset}, SEEK_SET);
301 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
304 # If value is a hash, array, or raw value with equal or less size, we can
305 # reuse the same content area of the database. Otherwise, we have to create
306 # a new content area at the EOF.
309 my $r = Scalar::Util::reftype( $value ) || '';
310 if ( $r eq 'HASH' || $r eq 'ARRAY' ) {
311 $actual_length = $self->{index_size};
313 # if autobless is enabled, must also take into consideration
314 # the class name, as it is stored along with key/value.
315 if ( $root->{autobless} ) {
316 my $value_class = Scalar::Util::blessed($value);
317 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
318 $actual_length += length($value_class);
322 else { $actual_length = length($value); }
324 if ($actual_length <= $size) {
328 $location = $root->{end};
329 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $self->{hash_size} + $root->{file_offset}, SEEK_SET);
330 print( $fh pack($self->{long_pack}, $location) );
338 # If this is an internal reference, return now.
339 # No need to write value or plain key
346 # If bucket didn't fit into list, split into a new index level
349 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
350 print( $fh pack($self->{long_pack}, $root->{end}) );
352 my $index_tag = $self->create_tag($obj, $root->{end}, DBM::Deep->SIG_INDEX, chr(0) x $self->{index_size});
355 $keys .= $md5 . pack($self->{long_pack}, 0);
357 for (my $i=0; $i<=$self->{max_buckets}; $i++) {
358 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
360 my $old_subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) +
361 $self->{hash_size}, $self->{long_size}));
362 my $num = ord(substr($key, $tag->{ch} + 1, 1));
364 if ($offsets[$num]) {
365 my $offset = $offsets[$num] + DBM::Deep->SIG_SIZE + $self->{data_size};
366 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
368 read( $fh, $subkeys, $self->{bucket_list_size});
370 for (my $k=0; $k<$self->{max_buckets}; $k++) {
371 my $subloc = unpack($self->{long_pack}, substr($subkeys, ($k * $self->{bucket_size}) +
372 $self->{hash_size}, $self->{long_size}));
374 seek($fh, $offset + ($k * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
375 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
381 $offsets[$num] = $root->{end};
382 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
383 print( $fh pack($self->{long_pack}, $root->{end}) );
385 my $blist_tag = $self->create_tag($obj, $root->{end}, DBM::Deep->SIG_BLIST, chr(0) x $self->{bucket_list_size});
387 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
388 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
393 $location ||= $root->{end};
394 } # re-index bucket list
397 # Seek to content area and store signature, value and plaintext key
401 seek($fh, $location + $root->{file_offset}, SEEK_SET);
404 # Write signature based on content type, set content length and write actual value.
406 my $r = Scalar::Util::reftype($value) || '';
408 print( $fh DBM::Deep->TYPE_HASH );
409 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
410 $content_length = $self->{index_size};
412 elsif ($r eq 'ARRAY') {
413 print( $fh DBM::Deep->TYPE_ARRAY );
414 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
415 $content_length = $self->{index_size};
417 elsif (!defined($value)) {
418 print( $fh DBM::Deep->SIG_NULL );
419 print( $fh pack($self->{data_pack}, 0) );
423 print( $fh DBM::Deep->SIG_DATA );
424 print( $fh pack($self->{data_pack}, length($value)) . $value );
425 $content_length = length($value);
429 # Plain key is stored AFTER value, as keys are typically fetched less often.
431 print( $fh pack($self->{data_pack}, length($plain_key)) . $plain_key );
434 # If value is blessed, preserve class name
436 if ( $root->{autobless} ) {
437 my $value_class = Scalar::Util::blessed($value);
438 if ( defined $value_class && $value_class ne 'DBM::Deep' ) {
440 # Blessed ref -- will restore later
443 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
444 $content_length += 1;
445 $content_length += $self->{data_size} + length($value_class);
449 $content_length += 1;
454 # If this is a new content area, advance EOF counter
456 if ($location == $root->{end}) {
457 $root->{end} += DBM::Deep->SIG_SIZE;
458 $root->{end} += $self->{data_size} + $content_length;
459 $root->{end} += $self->{data_size} + length($plain_key);
463 # If content is a hash or array, create new child DBM::Deep object and
464 # pass each key or element to it.
467 my $branch = DBM::Deep->new(
468 type => DBM::Deep->TYPE_HASH,
469 base_offset => $location,
472 foreach my $key (keys %{$value}) {
473 $branch->STORE( $key, $value->{$key} );
476 elsif ($r eq 'ARRAY') {
477 my $branch = DBM::Deep->new(
478 type => DBM::Deep->TYPE_ARRAY,
479 base_offset => $location,
483 foreach my $element (@{$value}) {
484 $branch->STORE( $index, $element );
492 return $obj->_throw_error("Fatal error: indexing failed -- possibly due to corruption in file");
495 sub get_bucket_value {
497 # Fetch single value given tag and MD5 digested key.
500 my ($obj, $tag, $md5) = @_;
501 my $keys = $tag->{content};
506 # Iterate through buckets, looking for a key match
509 for (my $i=0; $i<$self->{max_buckets}; $i++) {
510 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
511 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
515 # Hit end of list, no match
520 if ( $md5 ne $key ) {
525 # Found match -- seek to offset and read signature
528 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
529 read( $fh, $signature, DBM::Deep->SIG_SIZE);
532 # If value is a hash or array, return new DBM::Deep object with correct offset
534 if (($signature eq DBM::Deep->TYPE_HASH) || ($signature eq DBM::Deep->TYPE_ARRAY)) {
535 my $obj = DBM::Deep->new(
537 base_offset => $subloc,
541 if ($obj->_root->{autobless}) {
543 # Skip over value and plain key to see if object needs
546 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
549 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
550 if ($size) { seek($fh, $size, SEEK_CUR); }
553 read( $fh, $bless_bit, 1);
554 if (ord($bless_bit)) {
556 # Yes, object needs to be re-blessed
559 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
560 if ($size) { read( $fh, $class_name, $size); }
561 if ($class_name) { $obj = bless( $obj, $class_name ); }
569 # Otherwise return actual value
571 elsif ($signature eq DBM::Deep->SIG_DATA) {
574 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
575 if ($size) { read( $fh, $value, $size); }
580 # Key exists, but content is null
590 # Delete single key/value pair given tag and MD5 digested key.
593 my ($obj, $tag, $md5) = @_;
594 my $keys = $tag->{content};
599 # Iterate through buckets, looking for a key match
602 for (my $i=0; $i<$self->{max_buckets}; $i++) {
603 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
604 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
608 # Hit end of list, no match
613 if ( $md5 ne $key ) {
618 # Matched key -- delete bucket and return
620 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $obj->_root->{file_offset}, SEEK_SET);
621 print( $fh substr($keys, ($i+1) * $self->{bucket_size} ) );
622 print( $fh chr(0) x $self->{bucket_size} );
632 # Check existence of single key given tag and MD5 digested key.
635 my ($obj, $tag, $md5) = @_;
636 my $keys = $tag->{content};
639 # Iterate through buckets, looking for a key match
642 for (my $i=0; $i<$self->{max_buckets}; $i++) {
643 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
644 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
648 # Hit end of list, no match
653 if ( $md5 ne $key ) {
658 # Matched key -- return true
666 sub find_bucket_list {
668 # Locate offset for bucket list, given digested key
671 my ($obj, $md5, $args) = @_;
672 $args = {} unless $args;
675 # Locate offset for bucket list using digest index system
678 my $tag = $self->load_tag($obj, $obj->_base_offset);
680 return $self->_throw_error( "INTERNAL ERROR - Cannot find tag" );
683 while ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
684 my $num = ord substr($md5, $ch, 1);
686 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
687 $tag = $self->index_lookup( $obj, $tag, $num );
690 if ( $args->{create} ) {
692 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
693 print( $fh pack($self->{long_pack}, $obj->_root->{end}) );
695 $tag = $self->create_tag(
696 $obj, $obj->_root->{end},
697 DBM::Deep->SIG_BLIST,
698 chr(0) x $self->{bucket_list_size},
701 $tag->{ref_loc} = $ref_loc;
712 $tag->{ref_loc} = $ref_loc;
722 # Given index tag, lookup single entry in index and return .
725 my ($obj, $tag, $index) = @_;
727 my $location = unpack(
731 $index * $self->{long_size},
736 if (!$location) { return; }
738 return $self->load_tag( $obj, $location );
743 # Scan index and recursively step into deeper levels, looking for next key.
746 my ($obj, $offset, $ch, $force_return_next) = @_;
747 $force_return_next = undef unless $force_return_next;
749 my $tag = $self->load_tag($obj, $offset );
753 if ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
754 my $content = $tag->{content};
756 if ($obj->{return_next}) { $start = 0; }
757 else { $start = ord(substr($obj->{prev_md5}, $ch, 1)); }
759 for (my $index = $start; $index < 256; $index++) {
760 my $subloc = unpack($self->{long_pack}, substr($content, $index * $self->{long_size}, $self->{long_size}) );
762 my $result = $self->traverse_index( $obj, $subloc, $ch + 1, $force_return_next );
763 if (defined($result)) { return $result; }
767 $obj->{return_next} = 1;
770 elsif ($tag->{signature} eq DBM::Deep->SIG_BLIST) {
771 my $keys = $tag->{content};
772 if ($force_return_next) { $obj->{return_next} = 1; }
775 # Iterate through buckets, looking for a key match
777 for (my $i=0; $i<$self->{max_buckets}; $i++) {
778 my $key = substr($keys, $i * $self->{bucket_size}, $self->{hash_size});
779 my $subloc = unpack($self->{long_pack}, substr($keys, ($i * $self->{bucket_size}) + $self->{hash_size}, $self->{long_size}));
783 # End of bucket list -- return to outer loop
785 $obj->{return_next} = 1;
788 elsif ($key eq $obj->{prev_md5}) {
790 # Located previous key -- return next one found
792 $obj->{return_next} = 1;
795 elsif ($obj->{return_next}) {
797 # Seek to bucket location and skip over signature
799 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $obj->_root->{file_offset}, SEEK_SET);
802 # Skip over value to get to plain key
805 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
806 if ($size) { seek($fh, $size, SEEK_CUR); }
809 # Read in plain key and return as scalar
812 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
813 if ($size) { read( $fh, $plain_key, $size); }
819 $obj->{return_next} = 1;
820 } # tag is a bucket list
827 # Locate next key, given digested previous one
832 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
833 $obj->{return_next} = 0;
836 # If the previous key was not specifed, start at the top and
837 # return the first one found.
839 if (!$obj->{prev_md5}) {
840 $obj->{prev_md5} = chr(0) x $self->{hash_size};
841 $obj->{return_next} = 1;
844 return $self->traverse_index( $obj, $obj->_base_offset, 0 );