1 package DBM::Deep::Engine;
5 use Fcntl qw( :DEFAULT :flock :seek );
8 # Setup file and tag signatures. These should never change.
10 sub SIG_FILE () { 'DPDB' }
11 sub SIG_INTERNAL () { 'i' }
12 sub SIG_HASH () { 'H' }
13 sub SIG_ARRAY () { 'A' }
14 sub SIG_SCALAR () { 'S' }
15 sub SIG_NULL () { 'N' }
16 sub SIG_DATA () { 'D' }
17 sub SIG_INDEX () { 'I' }
18 sub SIG_BLIST () { 'B' }
23 # Precalculate index, bucket and bucket list sizes
27 $self->{index_size} = (2**8) * $self->{long_size};
28 $self->{bucket_size} = $self->{hash_size} + $self->{long_size};
29 $self->{bucket_list_size} = $self->{max_buckets} * $self->{bucket_size};
36 # Set pack/unpack modes (see file header for more)
39 my ($long_s, $long_p, $data_s, $data_p) = @_;
42 # Set to 4 and 'N' for 32-bit offset tags (default). Theoretical limit of 4
44 # (Perl must be compiled with largefile support for files > 2 GB)
46 # Set to 8 and 'Q' for 64-bit offsets. Theoretical limit of 16 XB per file.
47 # (Perl must be compiled with largefile and 64-bit long support)
49 $self->{long_size} = $long_s ? $long_s : 4;
50 $self->{long_pack} = $long_p ? $long_p : 'N';
53 # Set to 4 and 'N' for 32-bit data length prefixes. Limit of 4 GB for each
54 # key/value. Upgrading this is possible (see above) but probably not necessary.
55 # If you need more than 4 GB for a single key or value, this module is really
58 $self->{data_size} = $data_s ? $data_s : 4;
59 $self->{data_pack} = $data_p ? $data_p : 'N';
61 return $self->precalc_sizes();
66 # Set key digest function (default is MD5)
69 my ($digest_func, $hash_size) = @_;
71 $self->{digest} = $digest_func ? $digest_func : \&Digest::MD5::md5;
72 $self->{hash_size} = $hash_size ? $hash_size : 16;
74 return $self->precalc_sizes();
87 digest => \&Digest::MD5::md5,
91 # Maximum number of buckets per list before another level of indexing is done.
92 # Increase this value for slightly greater speed, but larger database files.
93 # DO NOT decrease this value below 16, due to risk of recursive reindex overrun.
107 $self->open( $obj ) if !defined $obj->_fh;
109 #XXX We have to make sure we don't mess up when autoflush isn't turned on
110 unless ( $obj->_root->{inode} ) {
111 my @stats = stat($obj->_fh);
112 $obj->_root->{inode} = $stats[1];
113 $obj->_root->{end} = $stats[7];
121 # Open a fh to the database, create if nonexistent.
122 # Make sure file signature matches DBM::Deep spec.
127 if (defined($obj->_fh)) { $self->close_fh( $obj ); }
129 # Theoretically, adding O_BINARY should remove the need for the binmode
130 # Of course, testing it is going to be ... interesting.
131 my $flags = O_RDWR | O_CREAT | O_BINARY;
134 sysopen( $fh, $obj->_root->{file}, $flags )
135 or $obj->_throw_error("Cannot sysopen file: " . $obj->_root->{file} . ": $!");
136 $obj->_root->{fh} = $fh;
138 #XXX Can we remove this by using the right sysopen() flags?
139 # Maybe ... q.v. above
140 binmode $fh; # for win32
142 if ($obj->_root->{autoflush}) {
143 my $old = select $fh;
148 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
151 my $bytes_read = read( $fh, $signature, length(SIG_FILE));
154 # File is empty -- write signature and master index
157 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
158 print( $fh SIG_FILE);
160 $self->create_tag($obj, $obj->_base_offset, $obj->_type, chr(0) x $self->{index_size});
162 # Why is this being printed here? I'm not seeing where anything actually points to
164 #XXX $obj->_root->{end} isn't updated from these 10 bytes that are being written
165 my $plain_key = "[base]";
166 print( $fh pack($self->{data_pack}, length($plain_key)) . $plain_key );
168 # Flush the filehandle
169 my $old_fh = select $fh;
170 my $old_af = $|; $| = 1; $| = $old_af;
177 # Check signature was valid
179 unless ($signature eq SIG_FILE) {
180 $self->close_fh( $obj );
181 $obj->_throw_error("Signature not found -- file is not a Deep DB");
185 # Get our type from master index signature
187 my $tag = $self->load_tag($obj, $obj->_base_offset)
188 or $obj->_throw_error("Corrupted file, no master index record");
190 unless ($obj->{type} eq $tag->{signature}) {
191 $obj->_throw_error("File type mismatch");
194 #XXX We probably also want to store the hash algorithm name and not assume anything
195 #XXX The cool thing would be to allow a different hashing algorithm at every level
204 if ( my $fh = $obj->_root->{fh} ) {
207 $obj->_root->{fh} = undef;
214 # Given offset, signature and content, create tag and write to disk
217 my ($obj, $offset, $sig, $content) = @_;
218 my $size = length($content);
222 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
223 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
225 if ($offset == $obj->_root->{end}) {
226 $obj->_root->{end} += SIG_SIZE + $self->{data_size} + $size;
232 offset => $offset + SIG_SIZE + $self->{data_size},
239 # Given offset, load single tag and return signature, size and data
242 my ($obj, $offset) = @_;
246 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
248 #XXX I'm not sure this check will work if autoflush isn't enabled ...
252 read( $fh, $b, SIG_SIZE + $self->{data_size} );
253 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
256 read( $fh, $buffer, $size);
261 offset => $offset + SIG_SIZE + $self->{data_size},
268 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
269 # plain (undigested) key and value.
272 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.
289 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
290 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
294 # Found empty bucket (end of list). Populate and exit loop.
298 $location = $root->{end};
302 $tag->{offset} + ($i * $self->{bucket_size}) + $root->{file_offset},
306 print( $fh $md5 . pack($self->{long_pack}, $location) );
310 if ( $md5 ne $key ) {
315 # Found existing bucket with same key. Replace with new value.
319 seek($fh, $subloc + SIG_SIZE + $root->{file_offset}, SEEK_SET);
321 read( $fh, $size, $self->{data_size});
322 $size = unpack($self->{data_pack}, $size);
325 # If value is a hash, array, or raw value with equal or less size, we can
326 # reuse the same content area of the database. Otherwise, we have to create
327 # a new content area at the EOF.
330 if ( $internal_ref ) {
331 $actual_length = $self->{long_size};
334 my $r = Scalar::Util::reftype( $value ) || '';
335 if ( $r eq 'HASH' || $r eq 'ARRAY' ) {
336 $actual_length = $self->{index_size};
338 # if autobless is enabled, must also take into consideration
339 # the class name, as it is stored along with key/value.
340 if ( $root->{autobless} ) {
341 my $value_class = Scalar::Util::blessed($value);
342 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
343 $actual_length += length($value_class);
347 else { $actual_length = length($value); }
350 if ($actual_length <= $size) {
354 $location = $root->{end};
357 $tag->{offset} + ($i * $self->{bucket_size}) + $self->{hash_size} + $root->{file_offset},
360 print( $fh pack($self->{long_pack}, $location) );
367 # If bucket didn't fit into list, split into a new index level
370 $self->split_index( $obj, $md5, $tag );
372 $location = $root->{end};
376 # Seek to content area and store signature, value and plaintext key
379 seek($fh, $location + $root->{file_offset}, SEEK_SET);
382 # Write signature based on content type, set content length and write
385 my $r = Scalar::Util::reftype($value) || '';
387 if ( $internal_ref ) {
388 print( $fh SIG_INTERNAL );
389 print( $fh pack($self->{data_pack}, $self->{long_size}) );
390 print( $fh pack($self->{long_pack}, $value->_base_offset) );
391 $content_length = $self->{long_size};
395 print( $fh SIG_HASH );
396 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
397 $content_length = $self->{index_size};
399 elsif ($r eq 'ARRAY') {
400 print( $fh SIG_ARRAY );
401 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
402 $content_length = $self->{index_size};
404 elsif (!defined($value)) {
405 print( $fh SIG_NULL );
406 print( $fh pack($self->{data_pack}, 0) );
410 print( $fh SIG_DATA );
411 print( $fh pack($self->{data_pack}, length($value)) . $value );
412 $content_length = length($value);
417 # Plain key is stored AFTER value, as keys are typically fetched less often.
419 print( $fh pack($self->{data_pack}, length($plain_key)) . $plain_key );
422 # If value is blessed, preserve class name
424 if ( $root->{autobless} ) {
425 my $value_class = Scalar::Util::blessed($value);
426 if ( defined $value_class && !$value->isa( 'DBM::Deep' ) ) {
428 # Blessed ref -- will restore later
431 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
432 $content_length += 1;
433 $content_length += $self->{data_size} + length($value_class);
437 $content_length += 1;
442 # If this is a new content area, advance EOF counter
444 if ($location == $root->{end}) {
445 $root->{end} += SIG_SIZE;
446 $root->{end} += $self->{data_size} + $content_length;
447 $root->{end} += $self->{data_size} + length($plain_key);
451 # If content is a hash or array, create new child DBM::Deep object and
452 # pass each key or element to it.
454 if ( ! $internal_ref ) {
456 my $branch = DBM::Deep->new(
457 type => DBM::Deep->TYPE_HASH,
458 base_offset => $location,
461 foreach my $key (keys %{$value}) {
462 $branch->STORE( $key, $value->{$key} );
465 elsif ($r eq 'ARRAY') {
466 my $branch = DBM::Deep->new(
467 type => DBM::Deep->TYPE_ARRAY,
468 base_offset => $location,
472 foreach my $element (@{$value}) {
473 $branch->STORE( $index, $element );
482 $obj->_throw_error("Fatal error: indexing failed -- possibly due to corruption in file");
487 my ($obj, $md5, $tag) = @_;
490 my $root = $obj->_root;
491 my $keys = $tag->{content};
493 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
494 print( $fh pack($self->{long_pack}, $root->{end}) );
496 my $index_tag = $self->create_tag(
500 chr(0) x $self->{index_size},
505 $keys .= $md5 . pack($self->{long_pack}, 0);
508 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
509 my ($key, $old_subloc) = $self->_get_key_subloc( $keys, $i );
511 next BUCKET unless $key;
513 my $num = ord(substr($key, $tag->{ch} + 1, 1));
515 if ($offsets[$num]) {
516 my $offset = $offsets[$num] + SIG_SIZE + $self->{data_size};
517 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
519 read( $fh, $subkeys, $self->{bucket_list_size});
521 for (my $k=0; $k<$self->{max_buckets}; $k++) {
522 my ($temp, $subloc) = $self->_get_key_subloc( $subkeys, $k );
525 seek($fh, $offset + ($k * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
526 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
532 $offsets[$num] = $root->{end};
533 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
534 print( $fh pack($self->{long_pack}, $root->{end}) );
536 my $blist_tag = $self->create_tag($obj, $root->{end}, SIG_BLIST, chr(0) x $self->{bucket_list_size});
538 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
539 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
548 my ($obj, $subloc) = @_;
553 # Found match -- seek to offset and read signature
556 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
557 read( $fh, $signature, SIG_SIZE);
560 # If value is a hash or array, return new DBM::Deep object with correct offset
562 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
563 my $obj = DBM::Deep->new(
565 base_offset => $subloc,
569 if ($obj->_root->{autobless}) {
571 # Skip over value and plain key to see if object needs
574 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
577 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
578 if ($size) { seek($fh, $size, SEEK_CUR); }
581 read( $fh, $bless_bit, 1);
582 if (ord($bless_bit)) {
584 # Yes, object needs to be re-blessed
587 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
588 if ($size) { read( $fh, $class_name, $size); }
589 if ($class_name) { $obj = bless( $obj, $class_name ); }
595 elsif ( $signature eq SIG_INTERNAL ) {
597 read( $fh, $size, $self->{data_size});
598 $size = unpack($self->{data_pack}, $size);
602 read( $fh, $new_loc, $size );
603 $new_loc = unpack( $self->{long_pack}, $new_loc );
605 return $self->read_from_loc( $obj, $new_loc );
612 # Otherwise return actual value
614 elsif ($signature eq SIG_DATA) {
616 read( $fh, $size, $self->{data_size});
617 $size = unpack($self->{data_pack}, $size);
620 if ($size) { read( $fh, $value, $size); }
625 # Key exists, but content is null
630 sub get_bucket_value {
632 # Fetch single value given tag and MD5 digested key.
635 my ($obj, $tag, $md5) = @_;
636 my $keys = $tag->{content};
641 # Iterate through buckets, looking for a key match
644 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
645 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
649 # Hit end of list, no match
654 if ( $md5 ne $key ) {
658 return $self->read_from_loc( $obj, $subloc );
666 # Delete single key/value pair given tag and MD5 digested key.
669 my ($obj, $tag, $md5) = @_;
670 my $keys = $tag->{content};
675 # Iterate through buckets, looking for a key match
678 for (my $i=0; $i<$self->{max_buckets}; $i++) {
679 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
683 # Hit end of list, no match
688 if ( $md5 ne $key ) {
693 # Matched key -- delete bucket and return
695 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $obj->_root->{file_offset}, SEEK_SET);
696 print( $fh substr($keys, ($i+1) * $self->{bucket_size} ) );
697 print( $fh chr(0) x $self->{bucket_size} );
707 # Check existence of single key given tag and MD5 digested key.
710 my ($obj, $tag, $md5) = @_;
711 my $keys = $tag->{content};
714 # Iterate through buckets, looking for a key match
717 for (my $i=0; $i<$self->{max_buckets}; $i++) {
718 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
722 # Hit end of list, no match
727 if ( $md5 ne $key ) {
732 # Matched key -- return true
740 sub find_bucket_list {
742 # Locate offset for bucket list, given digested key
745 my ($obj, $md5, $args) = @_;
746 $args = {} unless $args;
749 # Locate offset for bucket list using digest index system
751 my $tag = $self->load_tag($obj, $obj->_base_offset)
752 or $self->_throw_error( "INTERNAL ERROR - Cannot find tag" );
755 while ($tag->{signature} ne SIG_BLIST) {
756 my $num = ord substr($md5, $ch, 1);
758 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
759 $tag = $self->index_lookup( $obj, $tag, $num );
762 if ( $args->{create} ) {
764 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
765 print( $fh pack($self->{long_pack}, $obj->_root->{end}) );
767 $tag = $self->create_tag(
768 $obj, $obj->_root->{end},
770 chr(0) x $self->{bucket_list_size},
773 $tag->{ref_loc} = $ref_loc;
784 $tag->{ref_loc} = $ref_loc;
794 # Given index tag, lookup single entry in index and return .
797 my ($obj, $tag, $index) = @_;
799 my $location = unpack(
803 $index * $self->{long_size},
808 if (!$location) { return; }
810 return $self->load_tag( $obj, $location );
815 # Scan index and recursively step into deeper levels, looking for next key.
818 my ($obj, $offset, $ch, $force_return_next) = @_;
820 my $tag = $self->load_tag($obj, $offset );
824 if ($tag->{signature} ne SIG_BLIST) {
825 my $content = $tag->{content};
826 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
828 for (my $index = $start; $index < 256; $index++) {
831 substr($content, $index * $self->{long_size}, $self->{long_size}),
835 my $result = $self->traverse_index(
836 $obj, $subloc, $ch + 1, $force_return_next,
839 if (defined($result)) { return $result; }
843 $obj->{return_next} = 1;
847 my $keys = $tag->{content};
848 if ($force_return_next) { $obj->{return_next} = 1; }
851 # Iterate through buckets, looking for a key match
853 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
854 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
856 # End of bucket list -- return to outer loop
858 $obj->{return_next} = 1;
861 # Located previous key -- return next one found
862 elsif ($key eq $obj->{prev_md5}) {
863 $obj->{return_next} = 1;
866 # Seek to bucket location and skip over signature
867 elsif ($obj->{return_next}) {
868 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
870 # Skip over value to get to plain key
872 read( $fh, $sig, SIG_SIZE );
875 read( $fh, $size, $self->{data_size});
876 $size = unpack($self->{data_pack}, $size);
877 if ($size) { seek($fh, $size, SEEK_CUR); }
879 # Read in plain key and return as scalar
881 read( $fh, $size, $self->{data_size});
882 $size = unpack($self->{data_pack}, $size);
883 if ($size) { read( $fh, $plain_key, $size); }
889 $obj->{return_next} = 1;
890 } # tag is a bucket list
897 # Locate next key, given digested previous one
902 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
903 $obj->{return_next} = 0;
906 # If the previous key was not specifed, start at the top and
907 # return the first one found.
909 if (!$obj->{prev_md5}) {
910 $obj->{prev_md5} = chr(0) x $self->{hash_size};
911 $obj->{return_next} = 1;
914 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
919 sub _get_key_subloc {
921 my ($keys, $idx) = @_;
923 my ($key, $subloc) = unpack(
924 "a$self->{hash_size} $self->{long_pack}",
927 ($idx * $self->{bucket_size}),
928 $self->{bucket_size},
932 return ($key, $subloc);