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_NULL () { 'N' }
15 sub SIG_DATA () { 'D' }
16 sub SIG_INDEX () { 'I' }
17 sub SIG_BLIST () { 'B' }
18 sub SIG_FREE () { 'F' }
31 digest => \&Digest::MD5::md5,
35 # Maximum number of buckets per list before another level of indexing is
36 # done. Increase this value for slightly greater speed, but larger database
37 # files. DO NOT decrease this value below 16, due to risk of recursive
43 if ( defined $args->{pack_size} ) {
44 if ( lc $args->{pack_size} eq 'small' ) {
45 $args->{long_size} = 2;
46 $args->{long_pack} = 'S';
48 elsif ( lc $args->{pack_size} eq 'medium' ) {
49 $args->{long_size} = 4;
50 $args->{long_pack} = 'N';
52 elsif ( lc $args->{pack_size} eq 'large' ) {
53 $args->{long_size} = 8;
54 $args->{long_pack} = 'Q';
57 die "Unknown pack_size value: '$args->{pack_size}'\n";
61 # Grab the parameters we want to use
62 foreach my $param ( keys %$self ) {
63 next unless exists $args->{$param};
64 $self->{$param} = $args->{$param};
67 if ( $self->{max_buckets} < 16 ) {
68 warn "Floor of max_buckets is 16. Setting it to 16 from '$self->{max_buckets}'\n";
69 $self->{max_buckets} = 16;
78 $self->{index_size} = (2**8) * $self->{long_size};
79 $self->{bucket_size} = $self->{hash_size} + $self->{long_size} * 2;
80 $self->{bucket_list_size} = $self->{max_buckets} * $self->{bucket_size};
85 sub write_file_header {
91 my $loc = $self->_request_space(
92 $obj, length( SIG_FILE ) + 12,
94 seek($fh, $loc + $obj->_root->{file_offset}, SEEK_SET);
98 pack('S', $self->{long_size}),
99 pack('A', $self->{long_pack}),
100 pack('S', $self->{data_size}),
101 pack('A', $self->{data_pack}),
102 pack('S', $self->{max_buckets}),
108 sub read_file_header {
114 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
116 my $bytes_read = read(
117 $fh, $buffer, length(SIG_FILE) + 12,
121 my ($signature, $version, @values) = unpack( 'A4 S S A S A S', $buffer );
122 unless ($signature eq SIG_FILE) {
123 $self->close_fh( $obj );
124 $obj->_throw_error("Signature not found -- file is not a Deep DB");
127 if ( @values < 5 || grep { !defined } @values ) {
128 die "DBM::Deep: Corrupted file - bad header\n";
131 #XXX Add warnings if values weren't set right
132 @{$self}{qw( long_size long_pack data_size data_pack max_buckets )} = @values;
142 $self->open( $obj ) if !defined $obj->_fh;
147 #XXX The duplication of calculate_sizes needs to go away
148 unless ( $obj->{base_offset} ) {
149 my $bytes_read = $self->read_file_header( $obj );
151 $self->calculate_sizes;
154 # File is empty -- write header and master index
157 $self->write_file_header( $obj );
159 $obj->{base_offset} = $self->_request_space(
160 $obj, $self->tag_size( $self->{index_size} ),
164 $obj, $obj->_base_offset, $obj->_type,
165 chr(0)x$self->{index_size},
168 # Flush the filehandle
169 my $old_fh = select $fh;
170 my $old_af = $|; $| = 1; $| = $old_af;
174 $obj->{base_offset} = $bytes_read;
177 # Get our type from master index header
179 my $tag = $self->load_tag($obj, $obj->_base_offset)
180 or $obj->_throw_error("Corrupted file, no master index record");
182 unless ($obj->{type} eq $tag->{signature}) {
183 $obj->_throw_error("File type mismatch");
188 $self->calculate_sizes;
191 #XXX We have to make sure we don't mess up when autoflush isn't turned on
192 unless ( $obj->_root->{inode} ) {
193 my @stats = stat($obj->_fh);
194 $obj->_root->{inode} = $stats[1];
195 $obj->_root->{end} = $stats[7];
205 # Open a fh to the database, create if nonexistent.
206 # Make sure file signature matches DBM::Deep spec.
211 # Theoretically, adding O_BINARY should remove the need for the binmode
212 # Of course, testing it is going to be ... interesting.
213 my $flags = O_RDWR | O_CREAT | O_BINARY;
216 my $filename = $obj->_root->{file};
217 sysopen( $fh, $filename, $flags )
218 or $obj->_throw_error("Cannot sysopen file '$filename': $!");
219 $obj->_root->{fh} = $fh;
221 # Even though we use O_BINARY, better be safe than sorry.
224 if ($obj->_root->{autoflush}) {
225 my $old = select $fh;
237 if ( my $fh = $obj->_root->{fh} ) {
240 $obj->_root->{fh} = undef;
248 return SIG_SIZE + $self->{data_size} + $size;
253 # Given offset, signature and content, create tag and write to disk
256 my ($obj, $offset, $sig, $content) = @_;
257 my $size = length( $content );
261 if ( defined $offset ) {
262 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
265 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
267 return unless defined $offset;
272 offset => $offset + SIG_SIZE + $self->{data_size},
279 # Given offset, load single tag and return signature, size and data
282 my ($obj, $offset) = @_;
284 # print join(':',map{$_||''}caller(1)), $/;
288 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
290 #XXX I'm not sure this check will work if autoflush isn't enabled ...
294 read( $fh, $b, SIG_SIZE + $self->{data_size} );
295 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
298 read( $fh, $buffer, $size);
303 offset => $offset + SIG_SIZE + $self->{data_size},
308 sub _get_dbm_object {
313 if ($item->isa( 'DBM::Deep' )) {
320 my $r = Scalar::Util::reftype( $item ) || '';
321 if ( $r eq 'HASH' ) {
324 my $obj = tied(%$item);
325 if ($obj->isa( 'DBM::Deep' )) {
332 elsif ( $r eq 'ARRAY' ) {
335 my $obj = tied(@$item);
336 if ($obj->isa( 'DBM::Deep' )) {
349 my ($obj, $value, $key) = @_;
351 my $is_dbm_deep = eval {
352 local $SIG{'__DIE__'};
353 $value->isa( 'DBM::Deep' );
356 my $len = SIG_SIZE + $self->{data_size}
357 + $self->{data_size} + length( $key );
359 if ( $is_dbm_deep && $value->_root eq $obj->_root ) {
360 return $len + $self->{long_size};
363 my $r = Scalar::Util::reftype( $value ) || '';
364 if ( $obj->_root->{autobless} ) {
365 # This is for the bit saying whether or not this thing is blessed.
369 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
370 if ( defined $value ) {
371 $len += length( $value );
376 $len += $self->{index_size};
378 # if autobless is enabled, must also take into consideration
379 # the class name as it is stored after the key.
380 if ( $obj->_root->{autobless} ) {
381 my $c = Scalar::Util::blessed($value);
382 if ( defined $c && !$is_dbm_deep ) {
383 $len += $self->{data_size} + length($c);
392 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
393 # plain (undigested) key and value.
396 my ($obj, $tag, $md5, $plain_key, $value) = @_;
398 # This verifies that only supported values will be stored.
400 my $r = Scalar::Util::reftype( $value );
403 last if $r eq 'HASH';
404 last if $r eq 'ARRAY';
407 "Storage of variables of type '$r' is not supported."
414 my $root = $obj->_root;
417 my $actual_length = $self->_length_needed( $obj, $value, $plain_key );
419 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
421 # $self->_release_space( $obj, $size, $subloc );
422 # Updating a known md5
423 #XXX This needs updating to use _release_space
427 if ($actual_length <= $size) {
431 $location = $self->_request_space( $obj, $actual_length );
434 $tag->{offset} + $offset
435 + $self->{hash_size} + $root->{file_offset},
438 print( $fh pack($self->{long_pack}, $location ) );
439 print( $fh pack($self->{long_pack}, $actual_length ) );
443 elsif ( defined $offset ) {
444 $location = $self->_request_space( $obj, $actual_length );
446 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
447 print( $fh $md5 . pack($self->{long_pack}, $location ) );
448 print( $fh pack($self->{long_pack}, $actual_length ) );
450 # If bucket didn't fit into list, split into a new index level
451 # split_index() will do the _request_space() call
453 $location = $self->split_index( $obj, $md5, $tag );
456 $self->write_value( $obj, $location, $plain_key, $value );
463 my ($obj, $location, $key, $value) = @_;
466 my $root = $obj->_root;
468 my $dbm_deep_obj = _get_dbm_object( $value );
469 if ( $dbm_deep_obj && $dbm_deep_obj->_root ne $obj->_root ) {
470 $obj->_throw_error( "Cannot cross-reference. Use export() instead" );
473 seek($fh, $location + $root->{file_offset}, SEEK_SET);
476 # Write signature based on content type, set content length and write
479 my $r = Scalar::Util::reftype( $value ) || '';
480 if ( $dbm_deep_obj ) {
481 $self->write_tag( $obj, undef, SIG_INTERNAL,pack($self->{long_pack}, $dbm_deep_obj->_base_offset) );
483 elsif ($r eq 'HASH') {
484 if ( !$dbm_deep_obj && tied %{$value} ) {
485 $obj->_throw_error( "Cannot store something that is tied" );
487 $self->write_tag( $obj, undef, SIG_HASH, chr(0)x$self->{index_size} );
489 elsif ($r eq 'ARRAY') {
490 if ( !$dbm_deep_obj && tied @{$value} ) {
491 $obj->_throw_error( "Cannot store something that is tied" );
493 $self->write_tag( $obj, undef, SIG_ARRAY, chr(0)x$self->{index_size} );
495 elsif (!defined($value)) {
496 $self->write_tag( $obj, undef, SIG_NULL, '' );
499 $self->write_tag( $obj, undef, SIG_DATA, $value );
503 # Plain key is stored AFTER value, as keys are typically fetched less often.
505 print( $fh pack($self->{data_pack}, length($key)) . $key );
507 # Internal references don't care about autobless
508 return 1 if $dbm_deep_obj;
511 # If value is blessed, preserve class name
513 if ( $root->{autobless} ) {
514 my $c = Scalar::Util::blessed($value);
515 if ( defined $c && !$dbm_deep_obj ) {
517 print( $fh pack($self->{data_pack}, length($c)) . $c );
525 # Tie the passed in reference so that changes to it are reflected in the
526 # datafile. The use of $location as the base_offset will act as the
527 # the linkage between parent and child.
529 # The overall assignment is a hack around the fact that just tying doesn't
530 # store the values. This may not be the wrong thing to do.
534 tie %$value, 'DBM::Deep', {
535 base_offset => $location,
540 elsif ($r eq 'ARRAY') {
542 tie @$value, 'DBM::Deep', {
543 base_offset => $location,
554 my ($obj, $md5, $tag) = @_;
557 my $root = $obj->_root;
559 my $loc = $self->_request_space(
560 $obj, $self->tag_size( $self->{index_size} ),
563 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
564 print( $fh pack($self->{long_pack}, $loc) );
566 my $index_tag = $self->write_tag(
567 $obj, $loc, SIG_INDEX,
568 chr(0)x$self->{index_size},
571 my $newtag_loc = $self->_request_space(
572 $obj, $self->tag_size( $self->{bucket_list_size} ),
575 my $keys = $tag->{content}
576 . $md5 . pack($self->{long_pack}, $newtag_loc)
577 . pack($self->{long_pack}, 0);
581 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
582 my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
584 die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
585 die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
587 my $num = ord(substr($key, $tag->{ch} + 1, 1));
590 seek($fh, $newloc[$num] + $root->{file_offset}, SEEK_SET);
592 read( $fh, $subkeys, $self->{bucket_list_size});
594 # This is looking for the first empty spot
595 my ($subloc, $offset, $size) = $self->_find_in_buckets(
596 { content => $subkeys }, '',
599 seek($fh, $newloc[$num] + $offset + $root->{file_offset}, SEEK_SET);
600 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
605 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
607 my $loc = $self->_request_space(
608 $obj, $self->tag_size( $self->{bucket_list_size} ),
611 print( $fh pack($self->{long_pack}, $loc) );
613 my $blist_tag = $self->write_tag(
614 $obj, $loc, SIG_BLIST,
615 chr(0)x$self->{bucket_list_size},
618 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
619 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
621 $newloc[$num] = $blist_tag->{offset};
624 $self->_release_space(
625 $obj, $self->tag_size( $self->{bucket_list_size} ),
626 $tag->{offset} - SIG_SIZE - $self->{data_size},
634 my ($obj, $subloc) = @_;
639 # Found match -- seek to offset and read signature
642 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
643 read( $fh, $signature, SIG_SIZE);
646 # If value is a hash or array, return new DBM::Deep object with correct offset
648 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
649 my $new_obj = DBM::Deep->new({
651 base_offset => $subloc,
655 if ($new_obj->_root->{autobless}) {
657 # Skip over value and plain key to see if object needs
660 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
663 read( $fh, $size, $self->{data_size});
664 $size = unpack($self->{data_pack}, $size);
665 if ($size) { seek($fh, $size, SEEK_CUR); }
668 read( $fh, $bless_bit, 1);
669 if (ord($bless_bit)) {
671 # Yes, object needs to be re-blessed
674 read( $fh, $size, $self->{data_size});
675 $size = unpack($self->{data_pack}, $size);
676 if ($size) { read( $fh, $class_name, $size); }
677 if ($class_name) { $new_obj = bless( $new_obj, $class_name ); }
683 elsif ( $signature eq SIG_INTERNAL ) {
685 read( $fh, $size, $self->{data_size});
686 $size = unpack($self->{data_pack}, $size);
690 read( $fh, $new_loc, $size );
691 $new_loc = unpack( $self->{long_pack}, $new_loc );
693 return $self->read_from_loc( $obj, $new_loc );
700 # Otherwise return actual value
702 elsif ($signature eq SIG_DATA) {
704 read( $fh, $size, $self->{data_size});
705 $size = unpack($self->{data_pack}, $size);
708 if ($size) { read( $fh, $value, $size); }
713 # Key exists, but content is null
718 sub get_bucket_value {
720 # Fetch single value given tag and MD5 digested key.
723 my ($obj, $tag, $md5) = @_;
725 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
727 return $self->read_from_loc( $obj, $subloc );
734 # Delete single key/value pair given tag and MD5 digested key.
737 my ($obj, $tag, $md5) = @_;
739 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
740 #XXX This needs _release_space()
743 seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
744 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
745 print( $fh chr(0) x $self->{bucket_size} );
754 # Check existence of single key given tag and MD5 digested key.
757 my ($obj, $tag, $md5) = @_;
759 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
763 sub find_bucket_list {
765 # Locate offset for bucket list, given digested key
768 my ($obj, $md5, $args) = @_;
769 $args = {} unless $args;
772 # Locate offset for bucket list using digest index system
774 my $tag = $self->load_tag($obj, $obj->_base_offset)
775 or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
778 while ($tag->{signature} ne SIG_BLIST) {
779 my $num = ord substr($md5, $ch, 1);
781 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
782 $tag = $self->index_lookup( $obj, $tag, $num );
785 return if !$args->{create};
787 my $loc = $self->_request_space(
788 $obj, $self->tag_size( $self->{bucket_list_size} ),
792 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
793 print( $fh pack($self->{long_pack}, $loc) );
795 $tag = $self->write_tag(
796 $obj, $loc, SIG_BLIST,
797 chr(0)x$self->{bucket_list_size},
800 $tag->{ref_loc} = $ref_loc;
807 $tag->{ref_loc} = $ref_loc;
815 # Given index tag, lookup single entry in index and return .
818 my ($obj, $tag, $index) = @_;
820 my $location = unpack(
824 $index * $self->{long_size},
829 if (!$location) { return; }
831 return $self->load_tag( $obj, $location );
836 # Scan index and recursively step into deeper levels, looking for next key.
839 my ($obj, $offset, $ch, $force_return_next) = @_;
841 my $tag = $self->load_tag($obj, $offset );
845 if ($tag->{signature} ne SIG_BLIST) {
846 my $content = $tag->{content};
847 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
849 for (my $idx = $start; $idx < (2**8); $idx++) {
854 $idx * $self->{long_size},
860 my $result = $self->traverse_index(
861 $obj, $subloc, $ch + 1, $force_return_next,
864 if (defined($result)) { return $result; }
868 $obj->{return_next} = 1;
872 my $keys = $tag->{content};
873 if ($force_return_next) { $obj->{return_next} = 1; }
876 # Iterate through buckets, looking for a key match
878 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
879 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
881 # End of bucket list -- return to outer loop
883 $obj->{return_next} = 1;
886 # Located previous key -- return next one found
887 elsif ($key eq $obj->{prev_md5}) {
888 $obj->{return_next} = 1;
891 # Seek to bucket location and skip over signature
892 elsif ($obj->{return_next}) {
893 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
895 # Skip over value to get to plain key
897 read( $fh, $sig, SIG_SIZE );
900 read( $fh, $size, $self->{data_size});
901 $size = unpack($self->{data_pack}, $size);
902 if ($size) { seek($fh, $size, SEEK_CUR); }
904 # Read in plain key and return as scalar
906 read( $fh, $size, $self->{data_size});
907 $size = unpack($self->{data_pack}, $size);
908 if ($size) { read( $fh, $plain_key, $size); }
914 $obj->{return_next} = 1;
915 } # tag is a bucket list
922 # Locate next key, given digested previous one
927 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
928 $obj->{return_next} = 0;
931 # If the previous key was not specifed, start at the top and
932 # return the first one found.
934 if (!$obj->{prev_md5}) {
935 $obj->{prev_md5} = chr(0) x $self->{hash_size};
936 $obj->{return_next} = 1;
939 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
944 sub _get_key_subloc {
946 my ($keys, $idx) = @_;
948 my ($key, $subloc, $size) = unpack(
949 "a$self->{hash_size} $self->{long_pack} $self->{long_pack}",
952 ($idx * $self->{bucket_size}),
953 $self->{bucket_size},
957 return ($key, $subloc, $size);
960 sub _find_in_buckets {
962 my ($tag, $md5) = @_;
965 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
966 my ($key, $subloc, $size) = $self->_get_key_subloc(
970 return ($subloc, $i * $self->{bucket_size}, $size) unless $subloc;
972 next BUCKET if $key ne $md5;
974 return ($subloc, $i * $self->{bucket_size}, $size);
982 # my ($obj, $spot, $data) = @_;
984 # my $fh = $obj->_fh;
985 # seek( $fh, $spot, SEEK_SET );
986 # print( $fh $data );
993 my ($obj, $size) = @_;
995 my $loc = $obj->_root->{end};
996 $obj->_root->{end} += $size;
1001 sub _release_space {
1003 my ($obj, $size, $loc) = @_;
1008 seek( $fh, $loc + $obj->_root->{file_offset}, SEEK_SET );
1010 . pack($self->{long_pack}, $size )
1011 . pack($self->{long_pack}, $next_loc )
1020 # This will be added in later, after more refactoring is done. This is an early
1021 # attempt at refactoring on the physical level instead of the virtual level.
1024 my ($obj, $spot, $amount, $unpack) = @_;
1027 seek( $fh, $spot + $obj->_root->{file_offset}, SEEK_SET );
1030 my $bytes_read = read( $fh, $buffer, $amount );
1033 $buffer = unpack( $unpack, $buffer );
1037 return ($buffer, $bytes_read);