1 package DBM::Deep::Engine;
8 use Fcntl qw( :DEFAULT :flock :seek );
11 # Setup file and tag signatures. These should never change.
13 sub SIG_FILE () { 'DPDB' }
14 sub SIG_HEADER () { 'h' }
15 sub SIG_INTERNAL () { 'i' }
16 sub SIG_HASH () { 'H' }
17 sub SIG_ARRAY () { 'A' }
18 sub SIG_NULL () { 'N' }
19 sub SIG_DATA () { 'D' }
20 sub SIG_INDEX () { 'I' }
21 sub SIG_BLIST () { 'B' }
22 sub SIG_FREE () { 'F' }
35 digest => \&Digest::MD5::md5,
39 # Maximum number of buckets per list before another level of indexing is
40 # done. Increase this value for slightly greater speed, but larger database
41 # files. DO NOT decrease this value below 16, due to risk of recursive
49 if ( defined $args->{pack_size} ) {
50 if ( lc $args->{pack_size} eq 'small' ) {
51 $args->{long_size} = 2;
52 $args->{long_pack} = 'S';
54 elsif ( lc $args->{pack_size} eq 'medium' ) {
55 $args->{long_size} = 4;
56 $args->{long_pack} = 'N';
58 elsif ( lc $args->{pack_size} eq 'large' ) {
59 $args->{long_size} = 8;
60 $args->{long_pack} = 'Q';
63 die "Unknown pack_size value: '$args->{pack_size}'\n";
67 # Grab the parameters we want to use
68 foreach my $param ( keys %$self ) {
69 next unless exists $args->{$param};
70 $self->{$param} = $args->{$param};
73 if ( $self->{max_buckets} < 16 ) {
74 warn "Floor of max_buckets is 16. Setting it to 16 from '$self->{max_buckets}'\n";
75 $self->{max_buckets} = 16;
81 sub _fileobj { return $_[0]{fileobj} }
82 sub _fh { return $_[0]->_fileobj->{fh} }
87 $self->{index_size} = (2**8) * $self->{long_size};
88 $self->{bucket_size} = $self->{hash_size} + $self->{long_size} * 2;
89 $self->{bucket_list_size} = $self->{max_buckets} * $self->{bucket_size};
94 sub write_file_header {
100 my $loc = $self->_request_space(
101 undef, length( SIG_FILE ) + 21,
103 seek($fh, $loc + $self->_fileobj->{file_offset}, SEEK_SET);
107 pack('N', 1), # header version
108 pack('N', 12), # header size
109 pack('N', 0), # file version
110 pack('S', $self->{long_size}),
111 pack('A', $self->{long_pack}),
112 pack('S', $self->{data_size}),
113 pack('A', $self->{data_pack}),
114 pack('S', $self->{max_buckets}),
120 sub read_file_header {
126 seek($fh, 0 + $obj->_fileobj->{file_offset}, SEEK_SET);
128 my $bytes_read = read( $fh, $buffer, length(SIG_FILE) + 9 );
130 return unless $bytes_read;
132 my ($file_signature, $sig_header, $header_version, $size) = unpack(
136 unless ( $file_signature eq SIG_FILE ) {
137 $self->{fileobj}->close;
138 $obj->_throw_error( "Signature not found -- file is not a Deep DB" );
141 unless ( $sig_header eq SIG_HEADER ) {
142 $self->{fileobj}->close;
143 $obj->_throw_error( "Old file version found." );
147 $bytes_read += read( $fh, $buffer2, $size );
148 my ($file_version, @values) = unpack( 'N S A S A S', $buffer2 );
149 if ( @values < 5 || grep { !defined } @values ) {
150 $self->{fileobj}->close;
151 $obj->_throw_error("Corrupted file - bad header");
154 #XXX Add warnings if values weren't set right
155 @{$self}{qw(long_size long_pack data_size data_pack max_buckets)} = @values;
160 sub get_file_version {
166 seek( $fh, 13 + $obj->_fileobj->{file_offset}, SEEK_SET );
168 my $bytes_read = read( $fh, $buffer, 4 );
169 unless ( $bytes_read == 4 ) {
170 $obj->_throw_error( "Cannot read file version" );
173 return unpack( 'N', $buffer );
176 sub write_file_version {
178 my ($obj, $new_version) = @_;
182 seek( $fh, 13 + $obj->_fileobj->{file_offset}, SEEK_SET );
183 print( $fh pack( 'N', $new_version ) );
195 #XXX The duplication of calculate_sizes needs to go away
196 unless ( $obj->{base_offset} ) {
197 my $bytes_read = $self->read_file_header( $obj );
199 $self->calculate_sizes;
202 # File is empty -- write header and master index
205 $self->write_file_header( $obj );
207 $obj->{base_offset} = $self->_request_space(
208 $obj, $self->tag_size( $self->{index_size} ),
212 $obj, $obj->_base_offset, $obj->_type,
213 chr(0)x$self->{index_size},
216 # Flush the filehandle
217 my $old_fh = select $fh;
218 my $old_af = $|; $| = 1; $| = $old_af;
222 $obj->{base_offset} = $bytes_read;
225 # Get our type from master index header
227 my $tag = $self->load_tag($obj, $obj->_base_offset)
228 or $obj->_throw_error("Corrupted file, no master index record");
230 unless ($obj->{type} eq $tag->{signature}) {
231 $obj->_throw_error("File type mismatch");
236 $self->calculate_sizes;
239 #XXX We have to make sure we don't mess up when autoflush isn't turned on
240 unless ( $obj->_fileobj->{inode} ) {
241 my @stats = stat($obj->_fh);
242 $obj->_fileobj->{inode} = $stats[1];
243 $obj->_fileobj->{end} = $stats[7];
254 return SIG_SIZE + $self->{data_size} + $size;
259 # Given offset, signature and content, create tag and write to disk
262 my ($obj, $offset, $sig, $content) = @_;
263 my $size = length( $content );
267 if ( defined $offset ) {
268 seek($fh, $offset + $obj->_fileobj->{file_offset}, SEEK_SET);
271 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
273 return unless defined $offset;
278 offset => $offset + SIG_SIZE + $self->{data_size},
285 # Given offset, load single tag and return signature, size and data
288 my ($obj, $offset) = @_;
290 # print join(':',map{$_||''}caller(1)), $/;
294 seek($fh, $offset + $obj->_fileobj->{file_offset}, SEEK_SET);
296 #XXX I'm not sure this check will work if autoflush isn't enabled ...
300 read( $fh, $b, SIG_SIZE + $self->{data_size} );
301 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
304 read( $fh, $buffer, $size);
309 offset => $offset + SIG_SIZE + $self->{data_size},
314 sub _get_dbm_object {
319 if ($item->isa( 'DBM::Deep' )) {
326 my $r = Scalar::Util::reftype( $item ) || '';
327 if ( $r eq 'HASH' ) {
330 my $obj = tied(%$item);
331 if ($obj->isa( 'DBM::Deep' )) {
338 elsif ( $r eq 'ARRAY' ) {
341 my $obj = tied(@$item);
342 if ($obj->isa( 'DBM::Deep' )) {
355 my ($obj, $value, $key) = @_;
357 my $is_dbm_deep = eval {
358 local $SIG{'__DIE__'};
359 $value->isa( 'DBM::Deep' );
362 my $len = SIG_SIZE + $self->{data_size}
363 + $self->{data_size} + length( $key );
365 if ( $is_dbm_deep && $value->_fileobj eq $obj->_fileobj ) {
366 return $len + $self->{long_size};
369 my $r = Scalar::Util::reftype( $value ) || '';
370 if ( $obj->_fileobj->{autobless} ) {
371 # This is for the bit saying whether or not this thing is blessed.
375 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
376 if ( defined $value ) {
377 $len += length( $value );
382 $len += $self->{index_size};
384 # if autobless is enabled, must also take into consideration
385 # the class name as it is stored after the key.
386 if ( $obj->_fileobj->{autobless} ) {
387 my $c = Scalar::Util::blessed($value);
388 if ( defined $c && !$is_dbm_deep ) {
389 $len += $self->{data_size} + length($c);
398 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
399 # plain (undigested) key and value.
402 my ($obj, $tag, $md5, $plain_key, $value) = @_;
404 # This verifies that only supported values will be stored.
406 my $r = Scalar::Util::reftype( $value );
409 last if $r eq 'HASH';
410 last if $r eq 'ARRAY';
413 "Storage of variables of type '$r' is not supported."
420 my $root = $obj->_fileobj;
423 my $actual_length = $self->_length_needed( $obj, $value, $plain_key );
425 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
427 # $self->_release_space( $obj, $size, $subloc );
428 # Updating a known md5
429 #XXX This needs updating to use _release_space
433 if ($actual_length <= $size) {
437 $location = $self->_request_space( $obj, $actual_length );
440 $tag->{offset} + $offset
441 + $self->{hash_size} + $root->{file_offset},
444 print( $fh pack($self->{long_pack}, $location ) );
445 print( $fh pack($self->{long_pack}, $actual_length ) );
449 elsif ( defined $offset ) {
450 $location = $self->_request_space( $obj, $actual_length );
452 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
453 print( $fh $md5 . pack($self->{long_pack}, $location ) );
454 print( $fh pack($self->{long_pack}, $actual_length ) );
456 # If bucket didn't fit into list, split into a new index level
457 # split_index() will do the _request_space() call
459 $location = $self->split_index( $obj, $md5, $tag );
462 $self->write_value( $obj, $location, $plain_key, $value );
469 my ($obj, $location, $key, $value) = @_;
472 my $root = $obj->_fileobj;
474 my $dbm_deep_obj = _get_dbm_object( $value );
475 if ( $dbm_deep_obj && $dbm_deep_obj->_fileobj ne $obj->_fileobj ) {
476 $obj->_throw_error( "Cannot cross-reference. Use export() instead" );
479 seek($fh, $location + $root->{file_offset}, SEEK_SET);
482 # Write signature based on content type, set content length and write
485 my $r = Scalar::Util::reftype( $value ) || '';
486 if ( $dbm_deep_obj ) {
487 $self->write_tag( $obj, undef, SIG_INTERNAL,pack($self->{long_pack}, $dbm_deep_obj->_base_offset) );
489 elsif ($r eq 'HASH') {
490 if ( !$dbm_deep_obj && tied %{$value} ) {
491 $obj->_throw_error( "Cannot store something that is tied" );
493 $self->write_tag( $obj, undef, SIG_HASH, chr(0)x$self->{index_size} );
495 elsif ($r eq 'ARRAY') {
496 if ( !$dbm_deep_obj && tied @{$value} ) {
497 $obj->_throw_error( "Cannot store something that is tied" );
499 $self->write_tag( $obj, undef, SIG_ARRAY, chr(0)x$self->{index_size} );
501 elsif (!defined($value)) {
502 $self->write_tag( $obj, undef, SIG_NULL, '' );
505 $self->write_tag( $obj, undef, SIG_DATA, $value );
509 # Plain key is stored AFTER value, as keys are typically fetched less often.
511 print( $fh pack($self->{data_pack}, length($key)) . $key );
513 # Internal references don't care about autobless
514 return 1 if $dbm_deep_obj;
517 # If value is blessed, preserve class name
519 if ( $root->{autobless} ) {
520 my $c = Scalar::Util::blessed($value);
521 if ( defined $c && !$dbm_deep_obj ) {
523 print( $fh pack($self->{data_pack}, length($c)) . $c );
531 # Tie the passed in reference so that changes to it are reflected in the
532 # datafile. The use of $location as the base_offset will act as the
533 # the linkage between parent and child.
535 # The overall assignment is a hack around the fact that just tying doesn't
536 # store the values. This may not be the wrong thing to do.
540 tie %$value, 'DBM::Deep', {
541 base_offset => $location,
546 elsif ($r eq 'ARRAY') {
548 tie @$value, 'DBM::Deep', {
549 base_offset => $location,
560 my ($obj, $md5, $tag) = @_;
563 my $root = $obj->_fileobj;
565 my $loc = $self->_request_space(
566 $obj, $self->tag_size( $self->{index_size} ),
569 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
570 print( $fh pack($self->{long_pack}, $loc) );
572 my $index_tag = $self->write_tag(
573 $obj, $loc, SIG_INDEX,
574 chr(0)x$self->{index_size},
577 my $newtag_loc = $self->_request_space(
578 $obj, $self->tag_size( $self->{bucket_list_size} ),
581 my $keys = $tag->{content}
582 . $md5 . pack($self->{long_pack}, $newtag_loc)
583 . pack($self->{long_pack}, 0);
587 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
588 my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
590 die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
591 die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
593 my $num = ord(substr($key, $tag->{ch} + 1, 1));
596 seek($fh, $newloc[$num] + $root->{file_offset}, SEEK_SET);
598 read( $fh, $subkeys, $self->{bucket_list_size});
600 # This is looking for the first empty spot
601 my ($subloc, $offset, $size) = $self->_find_in_buckets(
602 { content => $subkeys }, '',
605 seek($fh, $newloc[$num] + $offset + $root->{file_offset}, SEEK_SET);
606 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
611 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
613 my $loc = $self->_request_space(
614 $obj, $self->tag_size( $self->{bucket_list_size} ),
617 print( $fh pack($self->{long_pack}, $loc) );
619 my $blist_tag = $self->write_tag(
620 $obj, $loc, SIG_BLIST,
621 chr(0)x$self->{bucket_list_size},
624 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
625 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
627 $newloc[$num] = $blist_tag->{offset};
630 $self->_release_space(
631 $obj, $self->tag_size( $self->{bucket_list_size} ),
632 $tag->{offset} - SIG_SIZE - $self->{data_size},
640 my ($obj, $subloc) = @_;
645 # Found match -- seek to offset and read signature
648 seek($fh, $subloc + $obj->_fileobj->{file_offset}, SEEK_SET);
649 read( $fh, $signature, SIG_SIZE);
652 # If value is a hash or array, return new DBM::Deep object with correct offset
654 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
655 my $new_obj = DBM::Deep->new({
657 base_offset => $subloc,
658 fileobj => $obj->_fileobj,
661 if ($new_obj->_fileobj->{autobless}) {
663 # Skip over value and plain key to see if object needs
666 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
669 read( $fh, $size, $self->{data_size});
670 $size = unpack($self->{data_pack}, $size);
671 if ($size) { seek($fh, $size, SEEK_CUR); }
674 read( $fh, $bless_bit, 1);
675 if (ord($bless_bit)) {
677 # Yes, object needs to be re-blessed
680 read( $fh, $size, $self->{data_size});
681 $size = unpack($self->{data_pack}, $size);
682 if ($size) { read( $fh, $class_name, $size); }
683 if ($class_name) { $new_obj = bless( $new_obj, $class_name ); }
689 elsif ( $signature eq SIG_INTERNAL ) {
691 read( $fh, $size, $self->{data_size});
692 $size = unpack($self->{data_pack}, $size);
696 read( $fh, $new_loc, $size );
697 $new_loc = unpack( $self->{long_pack}, $new_loc );
699 return $self->read_from_loc( $obj, $new_loc );
706 # Otherwise return actual value
708 elsif ( $signature eq SIG_DATA ) {
710 read( $fh, $size, $self->{data_size});
711 $size = unpack($self->{data_pack}, $size);
714 if ($size) { read( $fh, $value, $size); }
719 # Key exists, but content is null
724 sub get_bucket_value {
726 # Fetch single value given tag and MD5 digested key.
729 my ($obj, $tag, $md5) = @_;
731 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
733 return $self->read_from_loc( $obj, $subloc );
740 # Delete single key/value pair given tag and MD5 digested key.
743 my ($obj, $tag, $md5) = @_;
745 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
746 #XXX This needs _release_space()
749 seek($fh, $tag->{offset} + $offset + $obj->_fileobj->{file_offset}, SEEK_SET);
750 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
751 print( $fh chr(0) x $self->{bucket_size} );
760 # Check existence of single key given tag and MD5 digested key.
763 my ($obj, $tag, $md5) = @_;
765 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
769 sub find_bucket_list {
771 # Locate offset for bucket list, given digested key
774 my ($obj, $md5, $args) = @_;
775 $args = {} unless $args;
778 # Locate offset for bucket list using digest index system
780 my $tag = $self->load_tag($obj, $obj->_base_offset)
781 or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
784 while ($tag->{signature} ne SIG_BLIST) {
785 my $num = ord substr($md5, $ch, 1);
787 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
788 $tag = $self->index_lookup( $obj, $tag, $num );
791 return if !$args->{create};
793 my $loc = $self->_request_space(
794 $obj, $self->tag_size( $self->{bucket_list_size} ),
798 seek($fh, $ref_loc + $obj->_fileobj->{file_offset}, SEEK_SET);
799 print( $fh pack($self->{long_pack}, $loc) );
801 $tag = $self->write_tag(
802 $obj, $loc, SIG_BLIST,
803 chr(0)x$self->{bucket_list_size},
806 $tag->{ref_loc} = $ref_loc;
813 $tag->{ref_loc} = $ref_loc;
821 # Given index tag, lookup single entry in index and return .
824 my ($obj, $tag, $index) = @_;
826 my $location = unpack(
830 $index * $self->{long_size},
835 if (!$location) { return; }
837 return $self->load_tag( $obj, $location );
842 # Scan index and recursively step into deeper levels, looking for next key.
845 my ($obj, $offset, $ch, $force_return_next) = @_;
847 my $tag = $self->load_tag($obj, $offset );
851 if ($tag->{signature} ne SIG_BLIST) {
852 my $content = $tag->{content};
853 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
855 for (my $idx = $start; $idx < (2**8); $idx++) {
860 $idx * $self->{long_size},
866 my $result = $self->traverse_index(
867 $obj, $subloc, $ch + 1, $force_return_next,
870 if (defined($result)) { return $result; }
874 $obj->{return_next} = 1;
878 my $keys = $tag->{content};
879 if ($force_return_next) { $obj->{return_next} = 1; }
882 # Iterate through buckets, looking for a key match
884 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
885 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
887 # End of bucket list -- return to outer loop
889 $obj->{return_next} = 1;
892 # Located previous key -- return next one found
893 elsif ($key eq $obj->{prev_md5}) {
894 $obj->{return_next} = 1;
897 # Seek to bucket location and skip over signature
898 elsif ($obj->{return_next}) {
899 seek($fh, $subloc + $obj->_fileobj->{file_offset}, SEEK_SET);
901 # Skip over value to get to plain key
903 read( $fh, $sig, SIG_SIZE );
906 read( $fh, $size, $self->{data_size});
907 $size = unpack($self->{data_pack}, $size);
908 if ($size) { seek($fh, $size, SEEK_CUR); }
910 # Read in plain key and return as scalar
912 read( $fh, $size, $self->{data_size});
913 $size = unpack($self->{data_pack}, $size);
914 if ($size) { read( $fh, $plain_key, $size); }
920 $obj->{return_next} = 1;
921 } # tag is a bucket list
928 # Locate next key, given digested previous one
933 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
934 $obj->{return_next} = 0;
937 # If the previous key was not specifed, start at the top and
938 # return the first one found.
940 if (!$obj->{prev_md5}) {
941 $obj->{prev_md5} = chr(0) x $self->{hash_size};
942 $obj->{return_next} = 1;
945 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
950 sub _get_key_subloc {
952 my ($keys, $idx) = @_;
954 my ($key, $subloc, $size) = unpack(
955 "a$self->{hash_size} $self->{long_pack} $self->{long_pack}",
958 ($idx * $self->{bucket_size}),
959 $self->{bucket_size},
963 return ($key, $subloc, $size);
966 sub _find_in_buckets {
968 my ($tag, $md5) = @_;
971 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
972 my ($key, $subloc, $size) = $self->_get_key_subloc(
976 return ($subloc, $i * $self->{bucket_size}, $size) unless $subloc;
978 next BUCKET if $key ne $md5;
980 return ($subloc, $i * $self->{bucket_size}, $size);
988 # my ($obj, $spot, $data) = @_;
990 # my $fh = $obj->_fh;
991 # seek( $fh, $spot, SEEK_SET );
992 # print( $fh $data );
999 my ($obj, $size) = @_;
1001 my $loc = $self->_fileobj->{end};
1002 $self->_fileobj->{end} += $size;
1007 sub _release_space {
1009 my ($obj, $size, $loc) = @_;
1014 seek( $fh, $loc + $obj->_fileobj->{file_offset}, SEEK_SET );
1016 . pack($self->{long_pack}, $size )
1017 . pack($self->{long_pack}, $next_loc )
1026 # This will be added in later, after more refactoring is done. This is an early
1027 # attempt at refactoring on the physical level instead of the virtual level.
1030 my ($obj, $spot, $amount, $unpack) = @_;
1033 seek( $fh, $spot + $obj->_fileobj->{file_offset}, SEEK_SET );
1036 my $bytes_read = read( $fh, $buffer, $amount );
1039 $buffer = unpack( $unpack, $buffer );
1043 return ($buffer, $bytes_read);