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 N 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 ( if @values < 5 || grep { !defined } @values ) {
128 die "DBM::Deep: Corrupted file - bad header\n";
130 @{$self}{qw( long_size long_pack data_size data_pack max_buckets )} = @values;
140 $self->open( $obj ) if !defined $obj->_fh;
145 #XXX The duplication of calculate_sizes needs to go away
146 unless ( $obj->{base_offset} ) {
147 my $bytes_read = $self->read_file_header( $obj );
149 $self->calculate_sizes;
152 # File is empty -- write header and master index
155 $self->write_file_header( $obj );
157 $obj->{base_offset} = $self->_request_space(
158 $obj, $self->tag_size( $self->{index_size} ),
162 $obj, $obj->_base_offset, $obj->_type,
163 chr(0)x$self->{index_size},
166 # Flush the filehandle
167 my $old_fh = select $fh;
168 my $old_af = $|; $| = 1; $| = $old_af;
172 $obj->{base_offset} = $bytes_read;
175 # Get our type from master index header
177 my $tag = $self->load_tag($obj, $obj->_base_offset)
178 or $obj->_throw_error("Corrupted file, no master index record");
180 unless ($obj->{type} eq $tag->{signature}) {
181 $obj->_throw_error("File type mismatch");
186 $self->calculate_sizes;
189 #XXX We have to make sure we don't mess up when autoflush isn't turned on
190 unless ( $obj->_root->{inode} ) {
191 my @stats = stat($obj->_fh);
192 $obj->_root->{inode} = $stats[1];
193 $obj->_root->{end} = $stats[7];
203 # Open a fh to the database, create if nonexistent.
204 # Make sure file signature matches DBM::Deep spec.
209 # Theoretically, adding O_BINARY should remove the need for the binmode
210 # Of course, testing it is going to be ... interesting.
211 my $flags = O_RDWR | O_CREAT | O_BINARY;
214 my $filename = $obj->_root->{file};
215 sysopen( $fh, $filename, $flags )
216 or $obj->_throw_error("Cannot sysopen file '$filename': $!");
217 $obj->_root->{fh} = $fh;
219 # Even though we use O_BINARY, better be safe than sorry.
222 if ($obj->_root->{autoflush}) {
223 my $old = select $fh;
235 if ( my $fh = $obj->_root->{fh} ) {
238 $obj->_root->{fh} = undef;
246 return SIG_SIZE + $self->{data_size} + $size;
251 # Given offset, signature and content, create tag and write to disk
254 my ($obj, $offset, $sig, $content) = @_;
255 my $size = length( $content );
259 if ( defined $offset ) {
260 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
263 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
265 return unless defined $offset;
270 offset => $offset + SIG_SIZE + $self->{data_size},
277 # Given offset, load single tag and return signature, size and data
280 my ($obj, $offset) = @_;
282 # print join(':',map{$_||''}caller(1)), $/;
286 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
288 #XXX I'm not sure this check will work if autoflush isn't enabled ...
292 read( $fh, $b, SIG_SIZE + $self->{data_size} );
293 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
296 read( $fh, $buffer, $size);
301 offset => $offset + SIG_SIZE + $self->{data_size},
306 sub _get_dbm_object {
311 if ($item->isa( 'DBM::Deep' )) {
318 my $r = Scalar::Util::reftype( $item ) || '';
319 if ( $r eq 'HASH' ) {
322 my $obj = tied(%$item);
323 if ($obj->isa( 'DBM::Deep' )) {
330 elsif ( $r eq 'ARRAY' ) {
333 my $obj = tied(@$item);
334 if ($obj->isa( 'DBM::Deep' )) {
347 my ($obj, $value, $key) = @_;
349 my $is_dbm_deep = eval {
350 local $SIG{'__DIE__'};
351 $value->isa( 'DBM::Deep' );
354 my $len = SIG_SIZE + $self->{data_size}
355 + $self->{data_size} + length( $key );
357 if ( $is_dbm_deep && $value->_root eq $obj->_root ) {
358 return $len + $self->{long_size};
361 my $r = Scalar::Util::reftype( $value ) || '';
362 if ( $obj->_root->{autobless} ) {
363 # This is for the bit saying whether or not this thing is blessed.
367 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
368 if ( defined $value ) {
369 $len += length( $value );
374 $len += $self->{index_size};
376 # if autobless is enabled, must also take into consideration
377 # the class name as it is stored after the key.
378 if ( $obj->_root->{autobless} ) {
379 my $c = Scalar::Util::blessed($value);
380 if ( defined $c && !$is_dbm_deep ) {
381 $len += $self->{data_size} + length($c);
390 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
391 # plain (undigested) key and value.
394 my ($obj, $tag, $md5, $plain_key, $value) = @_;
396 # This verifies that only supported values will be stored.
398 my $r = Scalar::Util::reftype( $value );
401 last if $r eq 'HASH';
402 last if $r eq 'ARRAY';
405 "Storage of variables of type '$r' is not supported."
412 my $root = $obj->_root;
415 my $actual_length = $self->_length_needed( $obj, $value, $plain_key );
417 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
419 # $self->_release_space( $obj, $size, $subloc );
420 # Updating a known md5
421 #XXX This needs updating to use _release_space
425 if ($actual_length <= $size) {
429 $location = $self->_request_space( $obj, $actual_length );
432 $tag->{offset} + $offset
433 + $self->{hash_size} + $root->{file_offset},
436 print( $fh pack($self->{long_pack}, $location ) );
437 print( $fh pack($self->{long_pack}, $actual_length ) );
441 elsif ( defined $offset ) {
442 $location = $self->_request_space( $obj, $actual_length );
444 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
445 print( $fh $md5 . pack($self->{long_pack}, $location ) );
446 print( $fh pack($self->{long_pack}, $actual_length ) );
448 # If bucket didn't fit into list, split into a new index level
449 # split_index() will do the _request_space() call
451 $location = $self->split_index( $obj, $md5, $tag );
454 $self->write_value( $obj, $location, $plain_key, $value );
461 my ($obj, $location, $key, $value) = @_;
464 my $root = $obj->_root;
466 my $dbm_deep_obj = _get_dbm_object( $value );
467 if ( $dbm_deep_obj && $dbm_deep_obj->_root ne $obj->_root ) {
468 $obj->_throw_error( "Cannot cross-reference. Use export() instead" );
471 seek($fh, $location + $root->{file_offset}, SEEK_SET);
474 # Write signature based on content type, set content length and write
477 my $r = Scalar::Util::reftype( $value ) || '';
478 if ( $dbm_deep_obj ) {
479 $self->write_tag( $obj, undef, SIG_INTERNAL,pack($self->{long_pack}, $dbm_deep_obj->_base_offset) );
481 elsif ($r eq 'HASH') {
482 if ( !$dbm_deep_obj && tied %{$value} ) {
483 $obj->_throw_error( "Cannot store something that is tied" );
485 $self->write_tag( $obj, undef, SIG_HASH, chr(0)x$self->{index_size} );
487 elsif ($r eq 'ARRAY') {
488 if ( !$dbm_deep_obj && tied @{$value} ) {
489 $obj->_throw_error( "Cannot store something that is tied" );
491 $self->write_tag( $obj, undef, SIG_ARRAY, chr(0)x$self->{index_size} );
493 elsif (!defined($value)) {
494 $self->write_tag( $obj, undef, SIG_NULL, '' );
497 $self->write_tag( $obj, undef, SIG_DATA, $value );
501 # Plain key is stored AFTER value, as keys are typically fetched less often.
503 print( $fh pack($self->{data_pack}, length($key)) . $key );
505 # Internal references don't care about autobless
506 return 1 if $dbm_deep_obj;
509 # If value is blessed, preserve class name
511 if ( $root->{autobless} ) {
512 my $c = Scalar::Util::blessed($value);
513 if ( defined $c && !$dbm_deep_obj ) {
515 print( $fh pack($self->{data_pack}, length($c)) . $c );
523 # Tie the passed in reference so that changes to it are reflected in the
524 # datafile. The use of $location as the base_offset will act as the
525 # the linkage between parent and child.
527 # The overall assignment is a hack around the fact that just tying doesn't
528 # store the values. This may not be the wrong thing to do.
532 tie %$value, 'DBM::Deep', {
533 base_offset => $location,
538 elsif ($r eq 'ARRAY') {
540 tie @$value, 'DBM::Deep', {
541 base_offset => $location,
552 my ($obj, $md5, $tag) = @_;
555 my $root = $obj->_root;
557 my $loc = $self->_request_space(
558 $obj, $self->tag_size( $self->{index_size} ),
561 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
562 print( $fh pack($self->{long_pack}, $loc) );
564 my $index_tag = $self->write_tag(
565 $obj, $loc, SIG_INDEX,
566 chr(0)x$self->{index_size},
569 my $newtag_loc = $self->_request_space(
570 $obj, $self->tag_size( $self->{bucket_list_size} ),
573 my $keys = $tag->{content}
574 . $md5 . pack($self->{long_pack}, $newtag_loc)
575 . pack($self->{long_pack}, 0);
579 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
580 my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
582 die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
583 die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
585 my $num = ord(substr($key, $tag->{ch} + 1, 1));
588 seek($fh, $newloc[$num] + $root->{file_offset}, SEEK_SET);
590 read( $fh, $subkeys, $self->{bucket_list_size});
592 # This is looking for the first empty spot
593 my ($subloc, $offset, $size) = $self->_find_in_buckets(
594 { content => $subkeys }, '',
597 seek($fh, $newloc[$num] + $offset + $root->{file_offset}, SEEK_SET);
598 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
603 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
605 my $loc = $self->_request_space(
606 $obj, $self->tag_size( $self->{bucket_list_size} ),
609 print( $fh pack($self->{long_pack}, $loc) );
611 my $blist_tag = $self->write_tag(
612 $obj, $loc, SIG_BLIST,
613 chr(0)x$self->{bucket_list_size},
616 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
617 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
619 $newloc[$num] = $blist_tag->{offset};
622 $self->_release_space(
623 $obj, $self->tag_size( $self->{bucket_list_size} ),
624 $tag->{offset} - SIG_SIZE - $self->{data_size},
632 my ($obj, $subloc) = @_;
637 # Found match -- seek to offset and read signature
640 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
641 read( $fh, $signature, SIG_SIZE);
644 # If value is a hash or array, return new DBM::Deep object with correct offset
646 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
647 my $new_obj = DBM::Deep->new({
649 base_offset => $subloc,
653 if ($new_obj->_root->{autobless}) {
655 # Skip over value and plain key to see if object needs
658 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
661 read( $fh, $size, $self->{data_size});
662 $size = unpack($self->{data_pack}, $size);
663 if ($size) { seek($fh, $size, SEEK_CUR); }
666 read( $fh, $bless_bit, 1);
667 if (ord($bless_bit)) {
669 # Yes, object needs to be re-blessed
672 read( $fh, $size, $self->{data_size});
673 $size = unpack($self->{data_pack}, $size);
674 if ($size) { read( $fh, $class_name, $size); }
675 if ($class_name) { $new_obj = bless( $new_obj, $class_name ); }
681 elsif ( $signature eq SIG_INTERNAL ) {
683 read( $fh, $size, $self->{data_size});
684 $size = unpack($self->{data_pack}, $size);
688 read( $fh, $new_loc, $size );
689 $new_loc = unpack( $self->{long_pack}, $new_loc );
691 return $self->read_from_loc( $obj, $new_loc );
698 # Otherwise return actual value
700 elsif ($signature eq SIG_DATA) {
702 read( $fh, $size, $self->{data_size});
703 $size = unpack($self->{data_pack}, $size);
706 if ($size) { read( $fh, $value, $size); }
711 # Key exists, but content is null
716 sub get_bucket_value {
718 # Fetch single value given tag and MD5 digested key.
721 my ($obj, $tag, $md5) = @_;
723 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
725 return $self->read_from_loc( $obj, $subloc );
732 # Delete single key/value pair given tag and MD5 digested key.
735 my ($obj, $tag, $md5) = @_;
737 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
738 #XXX This needs _release_space()
741 seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
742 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
743 print( $fh chr(0) x $self->{bucket_size} );
752 # Check existence of single key given tag and MD5 digested key.
755 my ($obj, $tag, $md5) = @_;
757 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
761 sub find_bucket_list {
763 # Locate offset for bucket list, given digested key
766 my ($obj, $md5, $args) = @_;
767 $args = {} unless $args;
770 # Locate offset for bucket list using digest index system
772 my $tag = $self->load_tag($obj, $obj->_base_offset)
773 or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
776 while ($tag->{signature} ne SIG_BLIST) {
777 my $num = ord substr($md5, $ch, 1);
779 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
780 $tag = $self->index_lookup( $obj, $tag, $num );
783 return if !$args->{create};
785 my $loc = $self->_request_space(
786 $obj, $self->tag_size( $self->{bucket_list_size} ),
790 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
791 print( $fh pack($self->{long_pack}, $loc) );
793 $tag = $self->write_tag(
794 $obj, $loc, SIG_BLIST,
795 chr(0)x$self->{bucket_list_size},
798 $tag->{ref_loc} = $ref_loc;
805 $tag->{ref_loc} = $ref_loc;
813 # Given index tag, lookup single entry in index and return .
816 my ($obj, $tag, $index) = @_;
818 my $location = unpack(
822 $index * $self->{long_size},
827 if (!$location) { return; }
829 return $self->load_tag( $obj, $location );
834 # Scan index and recursively step into deeper levels, looking for next key.
837 my ($obj, $offset, $ch, $force_return_next) = @_;
839 my $tag = $self->load_tag($obj, $offset );
843 if ($tag->{signature} ne SIG_BLIST) {
844 my $content = $tag->{content};
845 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
847 for (my $idx = $start; $idx < (2**8); $idx++) {
852 $idx * $self->{long_size},
858 my $result = $self->traverse_index(
859 $obj, $subloc, $ch + 1, $force_return_next,
862 if (defined($result)) { return $result; }
866 $obj->{return_next} = 1;
870 my $keys = $tag->{content};
871 if ($force_return_next) { $obj->{return_next} = 1; }
874 # Iterate through buckets, looking for a key match
876 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
877 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
879 # End of bucket list -- return to outer loop
881 $obj->{return_next} = 1;
884 # Located previous key -- return next one found
885 elsif ($key eq $obj->{prev_md5}) {
886 $obj->{return_next} = 1;
889 # Seek to bucket location and skip over signature
890 elsif ($obj->{return_next}) {
891 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
893 # Skip over value to get to plain key
895 read( $fh, $sig, SIG_SIZE );
898 read( $fh, $size, $self->{data_size});
899 $size = unpack($self->{data_pack}, $size);
900 if ($size) { seek($fh, $size, SEEK_CUR); }
902 # Read in plain key and return as scalar
904 read( $fh, $size, $self->{data_size});
905 $size = unpack($self->{data_pack}, $size);
906 if ($size) { read( $fh, $plain_key, $size); }
912 $obj->{return_next} = 1;
913 } # tag is a bucket list
920 # Locate next key, given digested previous one
925 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
926 $obj->{return_next} = 0;
929 # If the previous key was not specifed, start at the top and
930 # return the first one found.
932 if (!$obj->{prev_md5}) {
933 $obj->{prev_md5} = chr(0) x $self->{hash_size};
934 $obj->{return_next} = 1;
937 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
942 sub _get_key_subloc {
944 my ($keys, $idx) = @_;
946 my ($key, $subloc, $size) = unpack(
947 "a$self->{hash_size} $self->{long_pack} $self->{long_pack}",
950 ($idx * $self->{bucket_size}),
951 $self->{bucket_size},
955 return ($key, $subloc, $size);
958 sub _find_in_buckets {
960 my ($tag, $md5) = @_;
963 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
964 my ($key, $subloc, $size) = $self->_get_key_subloc(
968 return ($subloc, $i * $self->{bucket_size}, $size) unless $subloc;
970 next BUCKET if $key ne $md5;
972 return ($subloc, $i * $self->{bucket_size}, $size);
980 # my ($obj, $spot, $data) = @_;
982 # my $fh = $obj->_fh;
983 # seek( $fh, $spot, SEEK_SET );
984 # print( $fh $data );
991 my ($obj, $size) = @_;
993 my $loc = $obj->_root->{end};
994 $obj->_root->{end} += $size;
1001 my ($obj, $size, $loc) = @_;
1006 seek( $fh, $loc + $obj->_root->{file_offset}, SEEK_SET );
1008 . pack($self->{long_pack}, $size )
1009 . pack($self->{long_pack}, $next_loc )
1018 # This will be added in later, after more refactoring is done. This is an early
1019 # attempt at refactoring on the physical level instead of the virtual level.
1022 my ($obj, $spot, $amount, $unpack) = @_;
1025 seek( $fh, $spot + $obj->_root->{file_offset}, SEEK_SET );
1028 my $bytes_read = read( $fh, $buffer, $amount );
1031 $buffer = unpack( $unpack, $buffer );
1035 return ($buffer, $bytes_read);