1 package DBM::Deep::Engine;
8 use Fcntl qw( :DEFAULT :flock :seek );
11 # * All the local($/,$\); are to protect read() and print() from -l.
14 # Setup file and tag signatures. These should never change.
16 sub SIG_FILE () { 'DPDB' }
17 sub SIG_HEADER () { 'h' }
18 sub SIG_INTERNAL () { 'i' }
19 sub SIG_HASH () { 'H' }
20 sub SIG_ARRAY () { 'A' }
21 sub SIG_NULL () { 'N' }
22 sub SIG_DATA () { 'D' }
23 sub SIG_INDEX () { 'I' }
24 sub SIG_BLIST () { 'B' }
25 sub SIG_FREE () { 'F' }
38 digest => \&Digest::MD5::md5,
42 # Maximum number of buckets per list before another level of indexing is
43 # done. Increase this value for slightly greater speed, but larger database
44 # files. DO NOT decrease this value below 16, due to risk of recursive
52 if ( defined $args->{pack_size} ) {
53 if ( lc $args->{pack_size} eq 'small' ) {
54 $args->{long_size} = 2;
55 $args->{long_pack} = 'S';
57 elsif ( lc $args->{pack_size} eq 'medium' ) {
58 $args->{long_size} = 4;
59 $args->{long_pack} = 'N';
61 elsif ( lc $args->{pack_size} eq 'large' ) {
62 $args->{long_size} = 8;
63 $args->{long_pack} = 'Q';
66 die "Unknown pack_size value: '$args->{pack_size}'\n";
70 # Grab the parameters we want to use
71 foreach my $param ( keys %$self ) {
72 next unless exists $args->{$param};
73 $self->{$param} = $args->{$param};
76 if ( $self->{max_buckets} < 16 ) {
77 warn "Floor of max_buckets is 16. Setting it to 16 from '$self->{max_buckets}'\n";
78 $self->{max_buckets} = 16;
84 sub _fileobj { return $_[0]{fileobj} }
85 sub _fh { return $_[0]->_fileobj->{fh} }
90 #XXX Does this need to be updated with different hashing algorithms?
91 $self->{index_size} = (2**8) * $self->{long_size};
92 $self->{bucket_size} = $self->{hash_size} + $self->{long_size} * 3;
93 $self->{bucket_list_size} = $self->{max_buckets} * $self->{bucket_size};
98 sub write_file_header {
105 my $loc = $self->_request_space( length( SIG_FILE ) + 21 );
106 seek($fh, $loc + $self->_fileobj->{file_offset}, SEEK_SET);
110 pack('N', 1), # header version
111 pack('N', 12), # header size
112 pack('N', 0), # currently running transaction IDs
113 pack('S', $self->{long_size}),
114 pack('A', $self->{long_pack}),
115 pack('S', $self->{data_size}),
116 pack('A', $self->{data_pack}),
117 pack('S', $self->{max_buckets}),
123 sub read_file_header {
130 seek($fh, 0 + $self->_fileobj->{file_offset}, SEEK_SET);
132 my $bytes_read = read( $fh, $buffer, length(SIG_FILE) + 9 );
134 return unless $bytes_read;
136 my ($file_signature, $sig_header, $header_version, $size) = unpack(
140 unless ( $file_signature eq SIG_FILE ) {
141 $self->_fileobj->close;
142 $self->_throw_error( "Signature not found -- file is not a Deep DB" );
145 unless ( $sig_header eq SIG_HEADER ) {
146 $self->_fileobj->close;
147 $self->_throw_error( "Old file version found." );
151 $bytes_read += read( $fh, $buffer2, $size );
152 my ($running_transactions, @values) = unpack( 'N S A S A S', $buffer2 );
154 $self->_fileobj->set_transaction_offset( 13 );
156 if ( @values < 5 || grep { !defined } @values ) {
157 $self->_fileobj->close;
158 $self->_throw_error("Corrupted file - bad header");
161 #XXX Add warnings if values weren't set right
162 @{$self}{qw(long_size long_pack data_size data_pack max_buckets)} = @values;
174 #XXX The duplication of calculate_sizes needs to go away
175 unless ( $obj->{base_offset} ) {
176 my $bytes_read = $self->read_file_header;
178 $self->calculate_sizes;
181 # File is empty -- write header and master index
184 $self->write_file_header;
186 $obj->{base_offset} = $self->_request_space( $self->tag_size( $self->{index_size} ) );
189 $obj->_base_offset, $obj->_type,
190 chr(0)x$self->{index_size},
193 # Flush the filehandle
194 my $old_fh = select $fh;
195 my $old_af = $|; $| = 1; $| = $old_af;
199 $obj->{base_offset} = $bytes_read;
202 # Get our type from master index header
204 my $tag = $self->load_tag($obj->_base_offset)
205 or $self->_throw_error("Corrupted file, no master index record");
207 unless ($obj->_type eq $tag->{signature}) {
208 $self->_throw_error("File type mismatch");
213 $self->calculate_sizes;
216 #XXX We have to make sure we don't mess up when autoflush isn't turned on
217 unless ( $self->_fileobj->{inode} ) {
218 my @stats = stat($fh);
219 $self->_fileobj->{inode} = $stats[1];
220 $self->_fileobj->{end} = $stats[7];
231 return SIG_SIZE + $self->{data_size} + $size;
236 # Given offset, signature and content, create tag and write to disk
239 my ($offset, $sig, $content) = @_;
240 my $size = length( $content );
246 if ( defined $offset ) {
247 seek($fh, $offset + $self->_fileobj->{file_offset}, SEEK_SET);
250 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
252 return unless defined $offset;
257 offset => $offset + SIG_SIZE + $self->{data_size},
264 # Given offset, load single tag and return signature, size and data
271 # print join(':',map{$_||''}caller(1)), $/;
275 seek($fh, $offset + $self->_fileobj->{file_offset}, SEEK_SET);
277 #XXX I'm not sure this check will work if autoflush isn't enabled ...
281 read( $fh, $b, SIG_SIZE + $self->{data_size} );
282 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
285 read( $fh, $buffer, $size);
290 offset => $offset + SIG_SIZE + $self->{data_size},
295 sub _get_dbm_object {
300 if ($item->isa( 'DBM::Deep' )) {
307 my $r = Scalar::Util::reftype( $item ) || '';
308 if ( $r eq 'HASH' ) {
311 my $obj = tied(%$item);
312 if ($obj->isa( 'DBM::Deep' )) {
319 elsif ( $r eq 'ARRAY' ) {
322 my $obj = tied(@$item);
323 if ($obj->isa( 'DBM::Deep' )) {
336 my ($value, $key) = @_;
338 my $is_dbm_deep = eval {
339 local $SIG{'__DIE__'};
340 $value->isa( 'DBM::Deep' );
343 my $len = SIG_SIZE + $self->{data_size}
344 + $self->{data_size} + length( $key );
346 if ( $is_dbm_deep && $value->_fileobj eq $self->_fileobj ) {
347 return $len + $self->{long_size};
350 my $r = Scalar::Util::reftype( $value ) || '';
351 if ( $self->_fileobj->{autobless} ) {
352 # This is for the bit saying whether or not this thing is blessed.
356 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
357 if ( defined $value ) {
358 $len += length( $value );
363 $len += $self->{index_size};
365 # if autobless is enabled, must also take into consideration
366 # the class name as it is stored after the key.
367 if ( $self->_fileobj->{autobless} ) {
368 my $c = Scalar::Util::blessed($value);
369 if ( defined $c && !$is_dbm_deep ) {
370 $len += $self->{data_size} + length($c);
379 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
380 # plain (undigested) key and value.
383 my ($tag, $md5, $plain_key, $value) = @_;
387 # This verifies that only supported values will be stored.
389 my $r = Scalar::Util::reftype( $value );
392 last if $r eq 'HASH';
393 last if $r eq 'ARRAY';
396 "Storage of variables of type '$r' is not supported."
403 my $root = $self->_fileobj;
406 my $actual_length = $self->_length_needed( $value, $plain_key );
408 #ACID - This is a mutation. Must only find the exact transaction
409 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5, 1 );
411 # $self->_release_space( $size, $subloc );
412 # Updating a known md5
413 #XXX This needs updating to use _release_space
417 if ($actual_length <= $size) {
421 $location = $self->_request_space( $actual_length );
424 $tag->{offset} + $offset
425 + $self->{hash_size} + $root->{file_offset},
428 print( $fh pack($self->{long_pack}, $location ) );
429 print( $fh pack($self->{long_pack}, $actual_length ) );
430 print( $fh pack($self->{long_pack}, $root->transaction_id ) );
434 elsif ( defined $offset ) {
435 $location = $self->_request_space( $actual_length );
437 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
438 print( $fh $md5 . pack($self->{long_pack}, $location ) );
439 print( $fh pack($self->{long_pack}, $actual_length ) );
440 print( $fh pack($self->{long_pack}, $root->transaction_id ) );
442 # If bucket didn't fit into list, split into a new index level
443 # split_index() will do the _request_space() call
445 $location = $self->split_index( $md5, $tag );
448 $self->write_value( $location, $plain_key, $value );
455 my ($location, $key, $value) = @_;
460 my $root = $self->_fileobj;
462 my $dbm_deep_obj = _get_dbm_object( $value );
463 if ( $dbm_deep_obj && $dbm_deep_obj->_fileobj ne $self->_fileobj ) {
464 $self->_throw_error( "Cannot cross-reference. Use export() instead" );
467 seek($fh, $location + $root->{file_offset}, SEEK_SET);
470 # Write signature based on content type, set content length and write
473 my $r = Scalar::Util::reftype( $value ) || '';
474 if ( $dbm_deep_obj ) {
475 $self->write_tag( undef, SIG_INTERNAL,pack($self->{long_pack}, $dbm_deep_obj->_base_offset) );
477 elsif ($r eq 'HASH') {
478 if ( !$dbm_deep_obj && tied %{$value} ) {
479 $self->_throw_error( "Cannot store something that is tied" );
481 $self->write_tag( undef, SIG_HASH, chr(0)x$self->{index_size} );
483 elsif ($r eq 'ARRAY') {
484 if ( !$dbm_deep_obj && tied @{$value} ) {
485 $self->_throw_error( "Cannot store something that is tied" );
487 $self->write_tag( undef, SIG_ARRAY, chr(0)x$self->{index_size} );
489 elsif (!defined($value)) {
490 $self->write_tag( undef, SIG_NULL, '' );
493 $self->write_tag( undef, SIG_DATA, $value );
497 # Plain key is stored AFTER value, as keys are typically fetched less often.
499 print( $fh pack($self->{data_pack}, length($key)) . $key );
501 # Internal references don't care about autobless
502 return 1 if $dbm_deep_obj;
505 # If value is blessed, preserve class name
507 if ( $root->{autobless} ) {
508 my $c = Scalar::Util::blessed($value);
509 if ( defined $c && !$dbm_deep_obj ) {
511 print( $fh pack($self->{data_pack}, length($c)) . $c );
519 # Tie the passed in reference so that changes to it are reflected in the
520 # datafile. The use of $location as the base_offset will act as the
521 # the linkage between parent and child.
523 # The overall assignment is a hack around the fact that just tying doesn't
524 # store the values. This may not be the wrong thing to do.
528 tie %$value, 'DBM::Deep', {
529 base_offset => $location,
534 elsif ($r eq 'ARRAY') {
536 tie @$value, 'DBM::Deep', {
537 base_offset => $location,
548 my ($md5, $tag) = @_;
553 my $root = $self->_fileobj;
555 my $loc = $self->_request_space(
556 $self->tag_size( $self->{index_size} ),
559 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
560 print( $fh pack($self->{long_pack}, $loc) );
562 my $index_tag = $self->write_tag(
564 chr(0)x$self->{index_size},
567 my $newtag_loc = $self->_request_space(
568 $self->tag_size( $self->{bucket_list_size} ),
571 my $keys = $tag->{content}
572 . $md5 . pack($self->{long_pack}, $newtag_loc)
573 . pack($self->{long_pack}, 0) # size
574 . pack($self->{long_pack}, 0); # transaction #
578 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
579 my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
581 die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
582 die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
584 my $num = ord(substr($key, $tag->{ch} + 1, 1));
587 seek($fh, $newloc[$num] + $root->{file_offset}, SEEK_SET);
589 read( $fh, $subkeys, $self->{bucket_list_size});
591 # This is looking for the first empty spot
592 my ($subloc, $offset, $size) = $self->_find_in_buckets(
593 { content => $subkeys }, '',
596 seek($fh, $newloc[$num] + $offset + $root->{file_offset}, SEEK_SET);
597 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
602 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
604 my $loc = $self->_request_space(
605 $self->tag_size( $self->{bucket_list_size} ),
608 print( $fh pack($self->{long_pack}, $loc) );
610 my $blist_tag = $self->write_tag(
612 chr(0)x$self->{bucket_list_size},
615 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
616 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
618 $newloc[$num] = $blist_tag->{offset};
621 $self->_release_space(
622 $self->tag_size( $self->{bucket_list_size} ),
623 $tag->{offset} - SIG_SIZE - $self->{data_size},
638 # Found match -- seek to offset and read signature
641 seek($fh, $subloc + $self->_fileobj->{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,
651 fileobj => $self->_fileobj,
654 if ($new_obj->_fileobj->{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( $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 ($tag, $md5) = @_;
724 #ACID - This is a read. Can find exact or HEAD
725 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
727 return $self->read_from_loc( $subloc );
734 # Delete single key/value pair given tag and MD5 digested key.
737 my ($tag, $md5) = @_;
741 #ACID - This is a mutation. Must only find the exact transaction
742 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5, 1 );
743 #XXX This needs _release_space()
746 seek($fh, $tag->{offset} + $offset + $self->_fileobj->{file_offset}, SEEK_SET);
747 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
748 print( $fh chr(0) x $self->{bucket_size} );
757 # Check existence of single key given tag and MD5 digested key.
760 my ($tag, $md5) = @_;
762 #ACID - This is a read. Can find exact or HEAD
763 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
767 sub find_bucket_list {
769 # Locate offset for bucket list, given digested key
772 my ($offset, $md5, $args) = @_;
773 $args = {} unless $args;
778 # Locate offset for bucket list using digest index system
780 my $tag = $self->load_tag( $offset )
781 or $self->_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( $tag, $num );
791 return if !$args->{create};
793 my $loc = $self->_request_space(
794 $self->tag_size( $self->{bucket_list_size} ),
798 seek($fh, $ref_loc + $self->_fileobj->{file_offset}, SEEK_SET);
799 print( $fh pack($self->{long_pack}, $loc) );
801 $tag = $self->write_tag(
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 ($tag, $index) = @_;
826 my $location = unpack(
830 $index * $self->{long_size},
835 if (!$location) { return; }
837 return $self->load_tag( $location );
842 # Scan index and recursively step into deeper levels, looking for next key.
845 my ($obj, $offset, $ch, $force_return_next) = @_;
849 my $tag = $self->load_tag( $offset );
853 if ($tag->{signature} ne SIG_BLIST) {
854 my $content = $tag->{content};
855 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
857 for (my $idx = $start; $idx < (2**8); $idx++) {
862 $idx * $self->{long_size},
868 my $result = $self->traverse_index(
869 $obj, $subloc, $ch + 1, $force_return_next,
872 if (defined($result)) { return $result; }
876 $obj->{return_next} = 1;
880 my $keys = $tag->{content};
881 if ($force_return_next) { $obj->{return_next} = 1; }
884 # Iterate through buckets, looking for a key match
886 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
887 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
889 # End of bucket list -- return to outer loop
891 $obj->{return_next} = 1;
894 # Located previous key -- return next one found
895 elsif ($key eq $obj->{prev_md5}) {
896 $obj->{return_next} = 1;
899 # Seek to bucket location and skip over signature
900 elsif ($obj->{return_next}) {
901 seek($fh, $subloc + $self->_fileobj->{file_offset}, SEEK_SET);
903 # Skip over value to get to plain key
905 read( $fh, $sig, SIG_SIZE );
908 read( $fh, $size, $self->{data_size});
909 $size = unpack($self->{data_pack}, $size);
910 if ($size) { seek($fh, $size, SEEK_CUR); }
912 # Read in plain key and return as scalar
914 read( $fh, $size, $self->{data_size});
915 $size = unpack($self->{data_pack}, $size);
916 if ($size) { read( $fh, $plain_key, $size); }
922 $obj->{return_next} = 1;
923 } # tag is a bucket list
930 # Locate next key, given digested previous one
935 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
936 $obj->{return_next} = 0;
939 # If the previous key was not specifed, start at the top and
940 # return the first one found.
942 if (!$obj->{prev_md5}) {
943 $obj->{prev_md5} = chr(0) x $self->{hash_size};
944 $obj->{return_next} = 1;
947 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
952 sub _get_key_subloc {
954 my ($keys, $idx) = @_;
956 my ($key, $subloc, $size, $transaction) = unpack(
957 # This is 'a', not 'A'. Please read the pack() documentation for the
958 # difference between the two and why it's important.
959 "a$self->{hash_size} $self->{long_pack} $self->{long_pack} $self->{long_pack}",
962 ($idx * $self->{bucket_size}),
963 $self->{bucket_size},
967 return ($key, $subloc, $size, $transaction);
970 sub _find_in_buckets {
972 my ($tag, $md5, $exact) = @_;
974 my $trans_id = $self->_fileobj->transaction_id;
979 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
980 my ($key, $subloc, $size, $transaction_id) = $self->_get_key_subloc(
984 my @rv = ($subloc, $i * $self->{bucket_size}, $size);
987 return @zero if !$exact && @zero and $trans_id;
991 next BUCKET if $key ne $md5;
993 # Save off the HEAD in case we need it.
994 @zero = @rv if $transaction_id == 0;
996 next BUCKET if $transaction_id != $trans_id;
1004 sub _request_space {
1008 my $loc = $self->_fileobj->{end};
1009 $self->_fileobj->{end} += $size;
1014 sub _release_space {
1016 my ($size, $loc) = @_;
1022 my $fh = $self->_fh;
1023 seek( $fh, $loc + $self->_fileobj->{file_offset}, SEEK_SET );
1025 . pack($self->{long_pack}, $size )
1026 . pack($self->{long_pack}, $next_loc )
1033 die "DBM::Deep: $_[1]\n";
1039 # This will be added in later, after more refactoring is done. This is an early
1040 # attempt at refactoring on the physical level instead of the virtual level.
1043 my ($spot, $amount, $unpack) = @_;
1047 my $fh = $self->_fh;
1048 seek( $fh, $spot + $self->_fileobj->{file_offset}, SEEK_SET );
1051 my $bytes_read = read( $fh, $buffer, $amount );
1054 $buffer = unpack( $unpack, $buffer );
1058 return ($buffer, $bytes_read);
1067 my ($spot, $data) = @_;
1071 my $fh = $self->_fh;
1072 seek( $fh, $spot, SEEK_SET );
1078 sub get_file_version {
1083 my $fh = $self->_fh;
1085 seek( $fh, 13 + $self->_fileobj->{file_offset}, SEEK_SET );
1087 my $bytes_read = read( $fh, $buffer, 4 );
1088 unless ( $bytes_read == 4 ) {
1089 $self->_throw_error( "Cannot read file version" );
1092 return unpack( 'N', $buffer );
1095 sub write_file_version {
1097 my ($new_version) = @_;
1101 my $fh = $self->_fh;
1103 seek( $fh, 13 + $self->_fileobj->{file_offset}, SEEK_SET );
1104 print( $fh pack( 'N', $new_version ) );