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 # Flush the filehandle
163 my $old_fh = select $fh;
164 my $old_af = $|; $| = 1; $| = $old_af;
171 # Check signature was valid
173 unless ($signature eq SIG_FILE) {
174 $self->close_fh( $obj );
175 $obj->_throw_error("Signature not found -- file is not a Deep DB");
179 # Get our type from master index signature
181 my $tag = $self->load_tag($obj, $obj->_base_offset)
182 or $obj->_throw_error("Corrupted file, no master index record");
184 unless ($obj->{type} eq $tag->{signature}) {
185 $obj->_throw_error("File type mismatch");
188 #XXX We probably also want to store the hash algorithm name and not assume anything
189 #XXX The cool thing would be to allow a different hashing algorithm at every level
198 if ( my $fh = $obj->_root->{fh} ) {
201 $obj->_root->{fh} = undef;
208 # Given offset, signature and content, create tag and write to disk
211 my ($obj, $offset, $sig, $content) = @_;
212 my $size = length($content);
216 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
217 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
219 if ($offset == $obj->_root->{end}) {
220 $obj->_root->{end} += SIG_SIZE + $self->{data_size} + $size;
226 offset => $offset + SIG_SIZE + $self->{data_size},
233 # Given offset, load single tag and return signature, size and data
236 my ($obj, $offset) = @_;
240 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
242 #XXX I'm not sure this check will work if autoflush isn't enabled ...
246 read( $fh, $b, SIG_SIZE + $self->{data_size} );
247 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
250 read( $fh, $buffer, $size);
255 offset => $offset + SIG_SIZE + $self->{data_size},
262 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
263 # plain (undigested) key and value.
266 my ($obj, $tag, $md5, $plain_key, $value) = @_;
271 my $root = $obj->_root;
273 my $is_dbm_deep = eval { local $SIG{'__DIE__'}; $value->isa( 'DBM::Deep' ) };
274 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
279 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
281 # Updating a known md5
285 seek($fh, $subloc + SIG_SIZE + $root->{file_offset}, SEEK_SET);
287 read( $fh, $size, $self->{data_size});
288 $size = unpack($self->{data_pack}, $size);
291 # If value is a hash, array, or raw value with equal or less size, we can
292 # reuse the same content area of the database. Otherwise, we have to create
293 # a new content area at the EOF.
296 if ( $internal_ref ) {
297 $actual_length = $self->{long_size};
300 my $r = Scalar::Util::reftype( $value ) || '';
301 if ( $r eq 'HASH' || $r eq 'ARRAY' ) {
302 $actual_length = $self->{index_size};
304 # if autobless is enabled, must also take into consideration
305 # the class name, as it is stored along with key/value.
306 if ( $root->{autobless} ) {
307 my $value_class = Scalar::Util::blessed($value);
308 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
309 $actual_length += length($value_class);
313 else { $actual_length = length($value); }
316 if ($actual_length <= $size) {
320 $location = $root->{end};
323 $tag->{offset} + $offset + $self->{hash_size} + $root->{file_offset},
326 print( $fh pack($self->{long_pack}, $location) );
330 elsif ( defined $offset ) {
332 $location = $root->{end};
334 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
335 print( $fh $md5 . pack($self->{long_pack}, $location) );
337 # If bucket didn't fit into list, split into a new index level
339 $self->split_index( $obj, $md5, $tag );
341 $location = $root->{end};
346 # Seek to content area and store signature, value and plaintext key
349 seek($fh, $location + $root->{file_offset}, SEEK_SET);
352 # Write signature based on content type, set content length and write
355 my $r = Scalar::Util::reftype($value) || '';
357 if ( $internal_ref ) {
358 print( $fh SIG_INTERNAL );
359 print( $fh pack($self->{data_pack}, $self->{long_size}) );
360 print( $fh pack($self->{long_pack}, $value->_base_offset) );
361 $content_length = $self->{long_size};
365 print( $fh SIG_HASH );
366 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
367 $content_length = $self->{index_size};
369 elsif ($r eq 'ARRAY') {
370 print( $fh SIG_ARRAY );
371 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
372 $content_length = $self->{index_size};
374 elsif (!defined($value)) {
375 print( $fh SIG_NULL );
376 print( $fh pack($self->{data_pack}, 0) );
380 print( $fh SIG_DATA );
381 print( $fh pack($self->{data_pack}, length($value)) . $value );
382 $content_length = length($value);
387 # Plain key is stored AFTER value, as keys are typically fetched less often.
389 print( $fh pack($self->{data_pack}, length($plain_key)) . $plain_key );
392 # If value is blessed, preserve class name
394 if ( $root->{autobless} ) {
395 my $value_class = Scalar::Util::blessed($value);
396 if ( defined $value_class && !$value->isa( 'DBM::Deep' ) ) {
398 # Blessed ref -- will restore later
401 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
402 $content_length += 1;
403 $content_length += $self->{data_size} + length($value_class);
407 $content_length += 1;
412 # If this is a new content area, advance EOF counter
414 if ($location == $root->{end}) {
415 $root->{end} += SIG_SIZE;
416 $root->{end} += $self->{data_size} + $content_length;
417 $root->{end} += $self->{data_size} + length($plain_key);
421 # If content is a hash or array, create new child DBM::Deep object and
422 # pass each key or element to it.
424 if ( ! $internal_ref ) {
426 my $branch = DBM::Deep->new(
427 type => DBM::Deep->TYPE_HASH,
428 base_offset => $location,
431 foreach my $key (keys %{$value}) {
432 $branch->STORE( $key, $value->{$key} );
435 elsif ($r eq 'ARRAY') {
436 my $branch = DBM::Deep->new(
437 type => DBM::Deep->TYPE_ARRAY,
438 base_offset => $location,
442 foreach my $element (@{$value}) {
443 $branch->STORE( $index, $element );
452 $obj->_throw_error("Fatal error: indexing failed -- possibly due to corruption in file");
457 my ($obj, $md5, $tag) = @_;
460 my $root = $obj->_root;
461 my $keys = $tag->{content};
463 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
464 print( $fh pack($self->{long_pack}, $root->{end}) );
466 my $index_tag = $self->create_tag(
470 chr(0) x $self->{index_size},
475 $keys .= $md5 . pack($self->{long_pack}, 0);
478 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
479 my ($key, $old_subloc) = $self->_get_key_subloc( $keys, $i );
481 next BUCKET unless $key;
483 my $num = ord(substr($key, $tag->{ch} + 1, 1));
485 if ($offsets[$num]) {
486 my $offset = $offsets[$num] + SIG_SIZE + $self->{data_size};
487 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
489 read( $fh, $subkeys, $self->{bucket_list_size});
491 for (my $k=0; $k<$self->{max_buckets}; $k++) {
492 my ($temp, $subloc) = $self->_get_key_subloc( $subkeys, $k );
495 seek($fh, $offset + ($k * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
496 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
502 $offsets[$num] = $root->{end};
503 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
504 print( $fh pack($self->{long_pack}, $root->{end}) );
506 my $blist_tag = $self->create_tag($obj, $root->{end}, SIG_BLIST, chr(0) x $self->{bucket_list_size});
508 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
509 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
518 my ($obj, $subloc) = @_;
523 # Found match -- seek to offset and read signature
526 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
527 read( $fh, $signature, SIG_SIZE);
530 # If value is a hash or array, return new DBM::Deep object with correct offset
532 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
533 my $obj = DBM::Deep->new(
535 base_offset => $subloc,
539 if ($obj->_root->{autobless}) {
541 # Skip over value and plain key to see if object needs
544 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
547 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
548 if ($size) { seek($fh, $size, SEEK_CUR); }
551 read( $fh, $bless_bit, 1);
552 if (ord($bless_bit)) {
554 # Yes, object needs to be re-blessed
557 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
558 if ($size) { read( $fh, $class_name, $size); }
559 if ($class_name) { $obj = bless( $obj, $class_name ); }
565 elsif ( $signature eq SIG_INTERNAL ) {
567 read( $fh, $size, $self->{data_size});
568 $size = unpack($self->{data_pack}, $size);
572 read( $fh, $new_loc, $size );
573 $new_loc = unpack( $self->{long_pack}, $new_loc );
575 return $self->read_from_loc( $obj, $new_loc );
582 # Otherwise return actual value
584 elsif ($signature eq SIG_DATA) {
586 read( $fh, $size, $self->{data_size});
587 $size = unpack($self->{data_pack}, $size);
590 if ($size) { read( $fh, $value, $size); }
595 # Key exists, but content is null
600 sub get_bucket_value {
602 # Fetch single value given tag and MD5 digested key.
605 my ($obj, $tag, $md5) = @_;
606 my $keys = $tag->{content};
609 # Iterate through buckets, looking for a key match
612 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
613 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
617 # Hit end of list, no match
622 if ( $md5 ne $key ) {
626 return $self->read_from_loc( $obj, $subloc );
634 # Delete single key/value pair given tag and MD5 digested key.
637 my ($obj, $tag, $md5) = @_;
638 my $keys = $tag->{content};
643 # Iterate through buckets, looking for a key match
646 for (my $i=0; $i<$self->{max_buckets}; $i++) {
647 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
651 # Hit end of list, no match
656 if ( $md5 ne $key ) {
661 # Matched key -- delete bucket and return
663 seek($fh, $tag->{offset} + ($i * $self->{bucket_size}) + $obj->_root->{file_offset}, SEEK_SET);
664 print( $fh substr($keys, ($i+1) * $self->{bucket_size} ) );
665 print( $fh chr(0) x $self->{bucket_size} );
675 # Check existence of single key given tag and MD5 digested key.
678 my ($obj, $tag, $md5) = @_;
679 my $keys = $tag->{content};
682 # Iterate through buckets, looking for a key match
685 for (my $i=0; $i<$self->{max_buckets}; $i++) {
686 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
690 # Hit end of list, no match
695 if ( $md5 ne $key ) {
700 # Matched key -- return true
708 sub find_bucket_list {
710 # Locate offset for bucket list, given digested key
713 my ($obj, $md5, $args) = @_;
714 $args = {} unless $args;
717 # Locate offset for bucket list using digest index system
719 my $tag = $self->load_tag($obj, $obj->_base_offset)
720 or $self->_throw_error( "INTERNAL ERROR - Cannot find tag" );
723 while ($tag->{signature} ne SIG_BLIST) {
724 my $num = ord substr($md5, $ch, 1);
726 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
727 $tag = $self->index_lookup( $obj, $tag, $num );
730 if ( $args->{create} ) {
732 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
733 print( $fh pack($self->{long_pack}, $obj->_root->{end}) );
735 $tag = $self->create_tag(
736 $obj, $obj->_root->{end},
738 chr(0) x $self->{bucket_list_size},
741 $tag->{ref_loc} = $ref_loc;
752 $tag->{ref_loc} = $ref_loc;
762 # Given index tag, lookup single entry in index and return .
765 my ($obj, $tag, $index) = @_;
767 my $location = unpack(
771 $index * $self->{long_size},
776 if (!$location) { return; }
778 return $self->load_tag( $obj, $location );
783 # Scan index and recursively step into deeper levels, looking for next key.
786 my ($obj, $offset, $ch, $force_return_next) = @_;
788 my $tag = $self->load_tag($obj, $offset );
792 if ($tag->{signature} ne SIG_BLIST) {
793 my $content = $tag->{content};
794 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
796 for (my $index = $start; $index < 256; $index++) {
799 substr($content, $index * $self->{long_size}, $self->{long_size}),
803 my $result = $self->traverse_index(
804 $obj, $subloc, $ch + 1, $force_return_next,
807 if (defined($result)) { return $result; }
811 $obj->{return_next} = 1;
815 my $keys = $tag->{content};
816 if ($force_return_next) { $obj->{return_next} = 1; }
819 # Iterate through buckets, looking for a key match
821 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
822 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
824 # End of bucket list -- return to outer loop
826 $obj->{return_next} = 1;
829 # Located previous key -- return next one found
830 elsif ($key eq $obj->{prev_md5}) {
831 $obj->{return_next} = 1;
834 # Seek to bucket location and skip over signature
835 elsif ($obj->{return_next}) {
836 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
838 # Skip over value to get to plain key
840 read( $fh, $sig, SIG_SIZE );
843 read( $fh, $size, $self->{data_size});
844 $size = unpack($self->{data_pack}, $size);
845 if ($size) { seek($fh, $size, SEEK_CUR); }
847 # Read in plain key and return as scalar
849 read( $fh, $size, $self->{data_size});
850 $size = unpack($self->{data_pack}, $size);
851 if ($size) { read( $fh, $plain_key, $size); }
857 $obj->{return_next} = 1;
858 } # tag is a bucket list
865 # Locate next key, given digested previous one
870 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
871 $obj->{return_next} = 0;
874 # If the previous key was not specifed, start at the top and
875 # return the first one found.
877 if (!$obj->{prev_md5}) {
878 $obj->{prev_md5} = chr(0) x $self->{hash_size};
879 $obj->{return_next} = 1;
882 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
887 sub _get_key_subloc {
889 my ($keys, $idx) = @_;
891 my ($key, $subloc) = unpack(
892 "a$self->{hash_size} $self->{long_pack}",
895 ($idx * $self->{bucket_size}),
896 $self->{bucket_size},
900 return ($key, $subloc);
903 sub _find_in_buckets {
905 my ($tag, $md5) = @_;
908 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
909 my ($key, $subloc) = $self->_get_key_subloc( $tag->{content}, $i );
911 return ($subloc, $i * $self->{bucket_size}) unless $subloc;
913 next BUCKET if $key ne $md5;
915 return ($subloc, $i * $self->{bucket_size});