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");
128 if ( grep { !defined } @values ) {
129 die "DBM::Deep: Corrupted file - bad header\n";
131 @{$self}{qw( long_size long_pack data_size data_pack max_buckets )} = @values;
141 $self->open( $obj ) if !defined $obj->_fh;
146 #XXX The duplication of calculate_sizes needs to go away
147 unless ( $obj->{base_offset} ) {
148 my $bytes_read = $self->read_file_header( $obj );
150 $self->calculate_sizes;
153 # File is empty -- write header and master index
156 $self->write_file_header( $obj );
158 $obj->{base_offset} = $self->_request_space(
159 $obj, $self->tag_size( $self->{index_size} ),
163 $obj, $obj->_base_offset, $obj->_type,
164 chr(0)x$self->{index_size},
167 # Flush the filehandle
168 my $old_fh = select $fh;
169 my $old_af = $|; $| = 1; $| = $old_af;
173 $obj->{base_offset} = $bytes_read;
176 # Get our type from master index header
178 my $tag = $self->load_tag($obj, $obj->_base_offset)
179 or $obj->_throw_error("Corrupted file, no master index record");
181 unless ($obj->{type} eq $tag->{signature}) {
182 $obj->_throw_error("File type mismatch");
187 $self->calculate_sizes;
190 #XXX We have to make sure we don't mess up when autoflush isn't turned on
191 unless ( $obj->_root->{inode} ) {
192 my @stats = stat($obj->_fh);
193 $obj->_root->{inode} = $stats[1];
194 $obj->_root->{end} = $stats[7];
204 # Open a fh to the database, create if nonexistent.
205 # Make sure file signature matches DBM::Deep spec.
210 # Theoretically, adding O_BINARY should remove the need for the binmode
211 # Of course, testing it is going to be ... interesting.
212 my $flags = O_RDWR | O_CREAT | O_BINARY;
215 my $filename = $obj->_root->{file};
216 sysopen( $fh, $filename, $flags )
217 or $obj->_throw_error("Cannot sysopen file '$filename': $!");
218 $obj->_root->{fh} = $fh;
220 # Even though we use O_BINARY, better be safe than sorry.
223 if ($obj->_root->{autoflush}) {
224 my $old = select $fh;
236 if ( my $fh = $obj->_root->{fh} ) {
239 $obj->_root->{fh} = undef;
247 return SIG_SIZE + $self->{data_size} + $size;
252 # Given offset, signature and content, create tag and write to disk
255 my ($obj, $offset, $sig, $content) = @_;
256 my $size = length( $content );
260 if ( defined $offset ) {
261 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
264 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
266 return unless defined $offset;
271 offset => $offset + SIG_SIZE + $self->{data_size},
278 # Given offset, load single tag and return signature, size and data
281 my ($obj, $offset) = @_;
283 # print join(':',map{$_||''}caller(1)), $/;
287 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
289 #XXX I'm not sure this check will work if autoflush isn't enabled ...
293 read( $fh, $b, SIG_SIZE + $self->{data_size} );
294 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
297 read( $fh, $buffer, $size);
302 offset => $offset + SIG_SIZE + $self->{data_size},
307 sub _get_dbm_object {
312 if ($item->isa( 'DBM::Deep' )) {
319 my $r = Scalar::Util::reftype( $item ) || '';
320 if ( $r eq 'HASH' ) {
323 my $obj = tied(%$item);
324 if ($obj->isa( 'DBM::Deep' )) {
331 elsif ( $r eq 'ARRAY' ) {
334 my $obj = tied(@$item);
335 if ($obj->isa( 'DBM::Deep' )) {
348 my ($obj, $value, $key) = @_;
350 my $is_dbm_deep = eval {
351 local $SIG{'__DIE__'};
352 $value->isa( 'DBM::Deep' );
355 my $len = SIG_SIZE + $self->{data_size}
356 + $self->{data_size} + length( $key );
358 if ( $is_dbm_deep && $value->_root eq $obj->_root ) {
359 return $len + $self->{long_size};
362 my $r = Scalar::Util::reftype( $value ) || '';
363 if ( $obj->_root->{autobless} ) {
364 # This is for the bit saying whether or not this thing is blessed.
368 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
369 if ( defined $value ) {
370 $len += length( $value );
375 $len += $self->{index_size};
377 # if autobless is enabled, must also take into consideration
378 # the class name as it is stored after the key.
379 if ( $obj->_root->{autobless} ) {
380 my $c = Scalar::Util::blessed($value);
381 if ( defined $c && !$is_dbm_deep ) {
382 $len += $self->{data_size} + length($c);
391 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
392 # plain (undigested) key and value.
395 my ($obj, $tag, $md5, $plain_key, $value) = @_;
397 # This verifies that only supported values will be stored.
399 my $r = Scalar::Util::reftype( $value );
402 last if $r eq 'HASH';
403 last if $r eq 'ARRAY';
406 "Storage of variables of type '$r' is not supported."
413 my $root = $obj->_root;
416 my $actual_length = $self->_length_needed( $obj, $value, $plain_key );
418 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
420 # $self->_release_space( $obj, $size, $subloc );
421 # Updating a known md5
422 #XXX This needs updating to use _release_space
426 if ($actual_length <= $size) {
430 $location = $self->_request_space( $obj, $actual_length );
433 $tag->{offset} + $offset
434 + $self->{hash_size} + $root->{file_offset},
437 print( $fh pack($self->{long_pack}, $location ) );
438 print( $fh pack($self->{long_pack}, $actual_length ) );
442 elsif ( defined $offset ) {
443 $location = $self->_request_space( $obj, $actual_length );
445 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
446 print( $fh $md5 . pack($self->{long_pack}, $location ) );
447 print( $fh pack($self->{long_pack}, $actual_length ) );
449 # If bucket didn't fit into list, split into a new index level
450 # split_index() will do the _request_space() call
452 $location = $self->split_index( $obj, $md5, $tag );
455 $self->write_value( $obj, $location, $plain_key, $value );
462 my ($obj, $location, $key, $value) = @_;
465 my $root = $obj->_root;
467 my $dbm_deep_obj = _get_dbm_object( $value );
468 if ( $dbm_deep_obj && $dbm_deep_obj->_root ne $obj->_root ) {
469 $obj->_throw_error( "Cannot cross-reference. Use export() instead" );
472 seek($fh, $location + $root->{file_offset}, SEEK_SET);
475 # Write signature based on content type, set content length and write
478 my $r = Scalar::Util::reftype( $value ) || '';
479 if ( $dbm_deep_obj ) {
480 $self->write_tag( $obj, undef, SIG_INTERNAL,pack($self->{long_pack}, $dbm_deep_obj->_base_offset) );
482 elsif ($r eq 'HASH') {
483 if ( !$dbm_deep_obj && tied %{$value} ) {
484 $obj->_throw_error( "Cannot store something that is tied" );
486 $self->write_tag( $obj, undef, SIG_HASH, chr(0)x$self->{index_size} );
488 elsif ($r eq 'ARRAY') {
489 if ( !$dbm_deep_obj && tied @{$value} ) {
490 $obj->_throw_error( "Cannot store something that is tied" );
492 $self->write_tag( $obj, undef, SIG_ARRAY, chr(0)x$self->{index_size} );
494 elsif (!defined($value)) {
495 $self->write_tag( $obj, undef, SIG_NULL, '' );
498 $self->write_tag( $obj, undef, SIG_DATA, $value );
502 # Plain key is stored AFTER value, as keys are typically fetched less often.
504 print( $fh pack($self->{data_pack}, length($key)) . $key );
506 # Internal references don't care about autobless
507 return 1 if $dbm_deep_obj;
510 # If value is blessed, preserve class name
512 if ( $root->{autobless} ) {
513 my $c = Scalar::Util::blessed($value);
514 if ( defined $c && !$dbm_deep_obj ) {
516 print( $fh pack($self->{data_pack}, length($c)) . $c );
524 # Tie the passed in reference so that changes to it are reflected in the
525 # datafile. The use of $location as the base_offset will act as the
526 # the linkage between parent and child.
528 # The overall assignment is a hack around the fact that just tying doesn't
529 # store the values. This may not be the wrong thing to do.
533 tie %$value, 'DBM::Deep', {
534 base_offset => $location,
539 elsif ($r eq 'ARRAY') {
541 tie @$value, 'DBM::Deep', {
542 base_offset => $location,
553 my ($obj, $md5, $tag) = @_;
556 my $root = $obj->_root;
558 my $loc = $self->_request_space(
559 $obj, $self->tag_size( $self->{index_size} ),
562 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
563 print( $fh pack($self->{long_pack}, $loc) );
565 my $index_tag = $self->write_tag(
566 $obj, $loc, SIG_INDEX,
567 chr(0)x$self->{index_size},
570 my $newtag_loc = $self->_request_space(
571 $obj, $self->tag_size( $self->{bucket_list_size} ),
574 my $keys = $tag->{content}
575 . $md5 . pack($self->{long_pack}, $newtag_loc)
576 . pack($self->{long_pack}, 0);
580 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
581 my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
583 die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
584 die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
586 my $num = ord(substr($key, $tag->{ch} + 1, 1));
589 seek($fh, $newloc[$num] + $root->{file_offset}, SEEK_SET);
591 read( $fh, $subkeys, $self->{bucket_list_size});
593 # This is looking for the first empty spot
594 my ($subloc, $offset, $size) = $self->_find_in_buckets(
595 { content => $subkeys }, '',
598 seek($fh, $newloc[$num] + $offset + $root->{file_offset}, SEEK_SET);
599 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
604 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
606 my $loc = $self->_request_space(
607 $obj, $self->tag_size( $self->{bucket_list_size} ),
610 print( $fh pack($self->{long_pack}, $loc) );
612 my $blist_tag = $self->write_tag(
613 $obj, $loc, SIG_BLIST,
614 chr(0)x$self->{bucket_list_size},
617 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
618 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
620 $newloc[$num] = $blist_tag->{offset};
623 $self->_release_space(
624 $obj, $self->tag_size( $self->{bucket_list_size} ),
625 $tag->{offset} - SIG_SIZE - $self->{data_size},
633 my ($obj, $subloc) = @_;
638 # Found match -- seek to offset and read signature
641 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
642 read( $fh, $signature, SIG_SIZE);
645 # If value is a hash or array, return new DBM::Deep object with correct offset
647 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
648 my $new_obj = DBM::Deep->new({
650 base_offset => $subloc,
654 if ($new_obj->_root->{autobless}) {
656 # Skip over value and plain key to see if object needs
659 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
662 read( $fh, $size, $self->{data_size});
663 $size = unpack($self->{data_pack}, $size);
664 if ($size) { seek($fh, $size, SEEK_CUR); }
667 read( $fh, $bless_bit, 1);
668 if (ord($bless_bit)) {
670 # Yes, object needs to be re-blessed
673 read( $fh, $size, $self->{data_size});
674 $size = unpack($self->{data_pack}, $size);
675 if ($size) { read( $fh, $class_name, $size); }
676 if ($class_name) { $new_obj = bless( $new_obj, $class_name ); }
682 elsif ( $signature eq SIG_INTERNAL ) {
684 read( $fh, $size, $self->{data_size});
685 $size = unpack($self->{data_pack}, $size);
689 read( $fh, $new_loc, $size );
690 $new_loc = unpack( $self->{long_pack}, $new_loc );
692 return $self->read_from_loc( $obj, $new_loc );
699 # Otherwise return actual value
701 elsif ($signature eq SIG_DATA) {
703 read( $fh, $size, $self->{data_size});
704 $size = unpack($self->{data_pack}, $size);
707 if ($size) { read( $fh, $value, $size); }
712 # Key exists, but content is null
717 sub get_bucket_value {
719 # Fetch single value given tag and MD5 digested key.
722 my ($obj, $tag, $md5) = @_;
724 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
726 return $self->read_from_loc( $obj, $subloc );
733 # Delete single key/value pair given tag and MD5 digested key.
736 my ($obj, $tag, $md5) = @_;
738 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
739 #XXX This needs _release_space()
742 seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
743 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
744 print( $fh chr(0) x $self->{bucket_size} );
753 # Check existence of single key given tag and MD5 digested key.
756 my ($obj, $tag, $md5) = @_;
758 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
762 sub find_bucket_list {
764 # Locate offset for bucket list, given digested key
767 my ($obj, $md5, $args) = @_;
768 $args = {} unless $args;
771 # Locate offset for bucket list using digest index system
773 my $tag = $self->load_tag($obj, $obj->_base_offset)
774 or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
777 while ($tag->{signature} ne SIG_BLIST) {
778 my $num = ord substr($md5, $ch, 1);
780 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
781 $tag = $self->index_lookup( $obj, $tag, $num );
784 return if !$args->{create};
786 my $loc = $self->_request_space(
787 $obj, $self->tag_size( $self->{bucket_list_size} ),
791 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
792 print( $fh pack($self->{long_pack}, $loc) );
794 $tag = $self->write_tag(
795 $obj, $loc, SIG_BLIST,
796 chr(0)x$self->{bucket_list_size},
799 $tag->{ref_loc} = $ref_loc;
806 $tag->{ref_loc} = $ref_loc;
814 # Given index tag, lookup single entry in index and return .
817 my ($obj, $tag, $index) = @_;
819 my $location = unpack(
823 $index * $self->{long_size},
828 if (!$location) { return; }
830 return $self->load_tag( $obj, $location );
835 # Scan index and recursively step into deeper levels, looking for next key.
838 my ($obj, $offset, $ch, $force_return_next) = @_;
840 my $tag = $self->load_tag($obj, $offset );
844 if ($tag->{signature} ne SIG_BLIST) {
845 my $content = $tag->{content};
846 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
848 for (my $idx = $start; $idx < (2**8); $idx++) {
853 $idx * $self->{long_size},
859 my $result = $self->traverse_index(
860 $obj, $subloc, $ch + 1, $force_return_next,
863 if (defined($result)) { return $result; }
867 $obj->{return_next} = 1;
871 my $keys = $tag->{content};
872 if ($force_return_next) { $obj->{return_next} = 1; }
875 # Iterate through buckets, looking for a key match
877 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
878 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
880 # End of bucket list -- return to outer loop
882 $obj->{return_next} = 1;
885 # Located previous key -- return next one found
886 elsif ($key eq $obj->{prev_md5}) {
887 $obj->{return_next} = 1;
890 # Seek to bucket location and skip over signature
891 elsif ($obj->{return_next}) {
892 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
894 # Skip over value to get to plain key
896 read( $fh, $sig, SIG_SIZE );
899 read( $fh, $size, $self->{data_size});
900 $size = unpack($self->{data_pack}, $size);
901 if ($size) { seek($fh, $size, SEEK_CUR); }
903 # Read in plain key and return as scalar
905 read( $fh, $size, $self->{data_size});
906 $size = unpack($self->{data_pack}, $size);
907 if ($size) { read( $fh, $plain_key, $size); }
913 $obj->{return_next} = 1;
914 } # tag is a bucket list
921 # Locate next key, given digested previous one
926 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
927 $obj->{return_next} = 0;
930 # If the previous key was not specifed, start at the top and
931 # return the first one found.
933 if (!$obj->{prev_md5}) {
934 $obj->{prev_md5} = chr(0) x $self->{hash_size};
935 $obj->{return_next} = 1;
938 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
943 sub _get_key_subloc {
945 my ($keys, $idx) = @_;
947 my ($key, $subloc, $size) = unpack(
948 "a$self->{hash_size} $self->{long_pack} $self->{long_pack}",
951 ($idx * $self->{bucket_size}),
952 $self->{bucket_size},
956 return ($key, $subloc, $size);
959 sub _find_in_buckets {
961 my ($tag, $md5) = @_;
964 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
965 my ($key, $subloc, $size) = $self->_get_key_subloc(
969 return ($subloc, $i * $self->{bucket_size}, $size) unless $subloc;
971 next BUCKET if $key ne $md5;
973 return ($subloc, $i * $self->{bucket_size}, $size);
981 # my ($obj, $spot, $data) = @_;
983 # my $fh = $obj->_fh;
984 # seek( $fh, $spot, SEEK_SET );
985 # print( $fh $data );
992 my ($obj, $size) = @_;
994 my $loc = $obj->_root->{end};
995 $obj->_root->{end} += $size;
1000 sub _release_space {
1002 my ($obj, $size, $loc) = @_;
1007 seek( $fh, $loc + $obj->_root->{file_offset}, SEEK_SET );
1009 . pack($self->{long_pack}, $size )
1010 . pack($self->{long_pack}, $next_loc )
1019 # This will be added in later, after more refactoring is done. This is an early
1020 # attempt at refactoring on the physical level instead of the virtual level.
1023 my ($obj, $spot, $amount, $unpack) = @_;
1026 seek( $fh, $spot + $obj->_root->{file_offset}, SEEK_SET );
1029 my $bytes_read = read( $fh, $buffer, $amount );
1032 $buffer = unpack( $unpack, $buffer );
1036 return ($buffer, $bytes_read);