1 package DBM::Deep::Engine;
8 use Fcntl qw( :DEFAULT :flock :seek );
11 # * All the local($/,$\); are to protect read() and print() from -l.
12 # * To add to bucket_size, make sure you modify the following:
15 # - add_bucket() - where the buckets are printed
18 # Setup file and tag signatures. These should never change.
20 sub SIG_FILE () { 'DPDB' }
21 sub SIG_HEADER () { 'h' }
22 sub SIG_INTERNAL () { 'i' }
23 sub SIG_HASH () { 'H' }
24 sub SIG_ARRAY () { 'A' }
25 sub SIG_NULL () { 'N' }
26 sub SIG_DATA () { 'D' }
27 sub SIG_INDEX () { 'I' }
28 sub SIG_BLIST () { 'B' }
29 sub SIG_FREE () { 'F' }
42 digest => \&Digest::MD5::md5,
46 # Maximum number of buckets per list before another level of indexing is
47 # done. Increase this value for slightly greater speed, but larger database
48 # files. DO NOT decrease this value below 16, due to risk of recursive
56 if ( defined $args->{pack_size} ) {
57 if ( lc $args->{pack_size} eq 'small' ) {
58 $args->{long_size} = 2;
59 $args->{long_pack} = 'n';
61 elsif ( lc $args->{pack_size} eq 'medium' ) {
62 $args->{long_size} = 4;
63 $args->{long_pack} = 'N';
65 elsif ( lc $args->{pack_size} eq 'large' ) {
66 $args->{long_size} = 8;
67 $args->{long_pack} = 'Q';
70 die "Unknown pack_size value: '$args->{pack_size}'\n";
74 # Grab the parameters we want to use
75 foreach my $param ( keys %$self ) {
76 next unless exists $args->{$param};
77 $self->{$param} = $args->{$param};
80 if ( $self->{max_buckets} < 16 ) {
81 warn "Floor of max_buckets is 16. Setting it to 16 from '$self->{max_buckets}'\n";
82 $self->{max_buckets} = 16;
88 sub _fileobj { return $_[0]{fileobj} }
89 sub _fh { return $_[0]->_fileobj->{fh} }
94 #XXX Does this need to be updated with different hashing algorithms?
95 $self->{index_size} = (2**8) * $self->{long_size};
96 $self->{bucket_size} = $self->{hash_size} + $self->{long_size} * 3;
97 $self->{bucket_list_size} = $self->{max_buckets} * $self->{bucket_size};
102 sub write_file_header {
109 my $loc = $self->_request_space( length( SIG_FILE ) + 21 );
110 seek($fh, $loc + $self->_fileobj->{file_offset}, SEEK_SET);
114 pack('N', 1), # header version
115 pack('N', 12), # header size
116 pack('N', 0), # currently running transaction IDs
117 pack('n', $self->{long_size}),
118 pack('A', $self->{long_pack}),
119 pack('n', $self->{data_size}),
120 pack('A', $self->{data_pack}),
121 pack('n', $self->{max_buckets}),
124 $self->_fileobj->set_transaction_offset( 13 );
129 sub read_file_header {
136 seek($fh, 0 + $self->_fileobj->{file_offset}, SEEK_SET);
138 my $bytes_read = read( $fh, $buffer, length(SIG_FILE) + 9 );
140 return unless $bytes_read;
142 my ($file_signature, $sig_header, $header_version, $size) = unpack(
146 unless ( $file_signature eq SIG_FILE ) {
147 $self->_fileobj->close;
148 $self->_throw_error( "Signature not found -- file is not a Deep DB" );
151 unless ( $sig_header eq SIG_HEADER ) {
152 $self->_fileobj->close;
153 $self->_throw_error( "Old file version found." );
157 $bytes_read += read( $fh, $buffer2, $size );
158 my ($running_transactions, @values) = unpack( 'N n A n A n', $buffer2 );
160 $self->_fileobj->set_transaction_offset( 13 );
162 if ( @values < 5 || grep { !defined } @values ) {
163 $self->_fileobj->close;
164 $self->_throw_error("Corrupted file - bad header");
167 #XXX Add warnings if values weren't set right
168 @{$self}{qw(long_size long_pack data_size data_pack max_buckets)} = @values;
180 #XXX The duplication of calculate_sizes needs to go away
181 unless ( $obj->{base_offset} ) {
182 my $bytes_read = $self->read_file_header;
184 $self->calculate_sizes;
187 # File is empty -- write header and master index
190 $self->write_file_header;
192 $obj->{base_offset} = $self->_request_space( $self->tag_size( $self->{index_size} ) );
195 $obj->_base_offset, $obj->_type,
196 chr(0)x$self->{index_size},
199 # Flush the filehandle
200 my $old_fh = select $fh;
201 my $old_af = $|; $| = 1; $| = $old_af;
205 $obj->{base_offset} = $bytes_read;
208 # Get our type from master index header
210 my $tag = $self->load_tag($obj->_base_offset)
211 or $self->_throw_error("Corrupted file, no master index record");
213 unless ($obj->_type eq $tag->{signature}) {
214 $self->_throw_error("File type mismatch");
219 $self->calculate_sizes;
222 #XXX We have to make sure we don't mess up when autoflush isn't turned on
223 unless ( $self->_fileobj->{inode} ) {
224 my @stats = stat($fh);
225 $self->_fileobj->{inode} = $stats[1];
226 $self->_fileobj->{end} = $stats[7];
237 return SIG_SIZE + $self->{data_size} + $size;
242 # Given offset, signature and content, create tag and write to disk
245 my ($offset, $sig, $content) = @_;
246 my $size = length( $content );
252 if ( defined $offset ) {
253 seek($fh, $offset + $self->_fileobj->{file_offset}, SEEK_SET);
256 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
258 return unless defined $offset;
263 offset => $offset + SIG_SIZE + $self->{data_size},
270 # Given offset, load single tag and return signature, size and data
277 # print join(':',map{$_||''}caller(1)), $/;
281 seek($fh, $offset + $self->_fileobj->{file_offset}, SEEK_SET);
283 #XXX I'm not sure this check will work if autoflush isn't enabled ...
287 read( $fh, $b, SIG_SIZE + $self->{data_size} );
288 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
291 read( $fh, $buffer, $size);
296 offset => $offset + SIG_SIZE + $self->{data_size},
301 sub _get_dbm_object {
306 if ($item->isa( 'DBM::Deep' )) {
313 my $r = Scalar::Util::reftype( $item ) || '';
314 if ( $r eq 'HASH' ) {
317 my $obj = tied(%$item);
318 if ($obj->isa( 'DBM::Deep' )) {
325 elsif ( $r eq 'ARRAY' ) {
328 my $obj = tied(@$item);
329 if ($obj->isa( 'DBM::Deep' )) {
342 my ($value, $key) = @_;
344 my $is_dbm_deep = eval {
345 local $SIG{'__DIE__'};
346 $value->isa( 'DBM::Deep' );
349 my $len = SIG_SIZE + $self->{data_size}
350 + $self->{data_size} + length( $key );
352 if ( $is_dbm_deep && $value->_fileobj eq $self->_fileobj ) {
353 return $len + $self->{long_size};
356 my $r = Scalar::Util::reftype( $value ) || '';
357 if ( $self->_fileobj->{autobless} ) {
358 # This is for the bit saying whether or not this thing is blessed.
362 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
363 if ( defined $value ) {
364 $len += length( $value );
369 $len += $self->{index_size};
371 # if autobless is enabled, must also take into consideration
372 # the class name as it is stored after the key.
373 if ( $self->_fileobj->{autobless} ) {
374 my $c = Scalar::Util::blessed($value);
375 if ( defined $c && !$is_dbm_deep ) {
376 $len += $self->{data_size} + length($c);
385 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
386 # plain (undigested) key and value.
389 my ($tag, $md5, $plain_key, $value, $deleted) = @_;
394 # This verifies that only supported values will be stored.
396 my $r = Scalar::Util::reftype( $value );
399 last if $r eq 'HASH';
400 last if $r eq 'ARRAY';
403 "Storage of variables of type '$r' is not supported."
410 my $root = $self->_fileobj;
413 my $actual_length = $self->_length_needed( $value, $plain_key );
415 #ACID - This is a mutation. Must only find the exact transaction
416 my ($subloc, $offset, $size,$is_deleted) = $self->_find_in_buckets( $tag, $md5, 1 );
419 if ( $self->_fileobj->transaction_id == 0 ) {
420 @transactions = $self->_fileobj->current_transactions;
423 # $self->_release_space( $size, $subloc );
424 # Updating a known md5
425 #XXX This needs updating to use _release_space
429 if ($actual_length <= $size) {
433 $location = $self->_request_space( $actual_length );
436 $tag->{offset} + $offset
437 + $self->{hash_size} + $root->{file_offset},
440 print( $fh pack($self->{long_pack}, $location ) );
441 print( $fh pack($self->{long_pack}, $actual_length ) );
442 print( $fh pack('n n', $root->transaction_id, $deleted ) );
446 elsif ( defined $offset ) {
447 $location = $self->_request_space( $actual_length );
449 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
450 print( $fh $md5 . pack($self->{long_pack}, $location ) );
451 print( $fh pack($self->{long_pack}, $actual_length ) );
452 print( $fh pack('n n', $root->transaction_id, $deleted ) );
454 for ( @transactions ) {
455 my $tag2 = $self->load_tag( $tag->{offset} - SIG_SIZE - $self->{data_size} );
456 $self->_fileobj->{transaction_id} = $_;
457 $self->add_bucket( $tag2, $md5, '', '', 1 );
458 $self->_fileobj->{transaction_id} = 0;
461 # If bucket didn't fit into list, split into a new index level
462 # split_index() will do the _request_space() call
464 $location = $self->split_index( $md5, $tag );
467 $self->write_value( $location, $plain_key, $value );
474 my ($location, $key, $value) = @_;
479 my $root = $self->_fileobj;
481 my $dbm_deep_obj = _get_dbm_object( $value );
482 if ( $dbm_deep_obj && $dbm_deep_obj->_fileobj ne $self->_fileobj ) {
483 $self->_throw_error( "Cannot cross-reference. Use export() instead" );
486 seek($fh, $location + $root->{file_offset}, SEEK_SET);
489 # Write signature based on content type, set content length and write
492 my $r = Scalar::Util::reftype( $value ) || '';
493 if ( $dbm_deep_obj ) {
494 $self->write_tag( undef, SIG_INTERNAL,pack($self->{long_pack}, $dbm_deep_obj->_base_offset) );
496 elsif ($r eq 'HASH') {
497 if ( !$dbm_deep_obj && tied %{$value} ) {
498 $self->_throw_error( "Cannot store something that is tied" );
500 $self->write_tag( undef, SIG_HASH, chr(0)x$self->{index_size} );
502 elsif ($r eq 'ARRAY') {
503 if ( !$dbm_deep_obj && tied @{$value} ) {
504 $self->_throw_error( "Cannot store something that is tied" );
506 $self->write_tag( undef, SIG_ARRAY, chr(0)x$self->{index_size} );
508 elsif (!defined($value)) {
509 $self->write_tag( undef, SIG_NULL, '' );
512 $self->write_tag( undef, SIG_DATA, $value );
516 # Plain key is stored AFTER value, as keys are typically fetched less often.
518 print( $fh pack($self->{data_pack}, length($key)) . $key );
520 # Internal references don't care about autobless
521 return 1 if $dbm_deep_obj;
524 # If value is blessed, preserve class name
526 if ( $root->{autobless} ) {
527 my $c = Scalar::Util::blessed($value);
528 if ( defined $c && !$dbm_deep_obj ) {
530 print( $fh pack($self->{data_pack}, length($c)) . $c );
538 # Tie the passed in reference so that changes to it are reflected in the
539 # datafile. The use of $location as the base_offset will act as the
540 # the linkage between parent and child.
542 # The overall assignment is a hack around the fact that just tying doesn't
543 # store the values. This may not be the wrong thing to do.
547 tie %$value, 'DBM::Deep', {
548 base_offset => $location,
553 elsif ($r eq 'ARRAY') {
555 tie @$value, 'DBM::Deep', {
556 base_offset => $location,
567 my ($md5, $tag) = @_;
572 my $root = $self->_fileobj;
574 my $loc = $self->_request_space(
575 $self->tag_size( $self->{index_size} ),
578 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
579 print( $fh pack($self->{long_pack}, $loc) );
581 my $index_tag = $self->write_tag(
583 chr(0)x$self->{index_size},
586 my $newtag_loc = $self->_request_space(
587 $self->tag_size( $self->{bucket_list_size} ),
590 my $keys = $tag->{content}
591 . $md5 . pack($self->{long_pack}, $newtag_loc)
592 . pack($self->{long_pack}, 0) # size
593 . pack($self->{long_pack}, 0); # transaction ID
597 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
598 my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
600 die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
601 die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
603 my $num = ord(substr($key, $tag->{ch} + 1, 1));
606 seek($fh, $newloc[$num] + $root->{file_offset}, SEEK_SET);
608 read( $fh, $subkeys, $self->{bucket_list_size});
610 # This is looking for the first empty spot
611 my ($subloc, $offset, $size) = $self->_find_in_buckets(
612 { content => $subkeys }, '',
615 seek($fh, $newloc[$num] + $offset + $root->{file_offset}, SEEK_SET);
616 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
621 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
623 my $loc = $self->_request_space(
624 $self->tag_size( $self->{bucket_list_size} ),
627 print( $fh pack($self->{long_pack}, $loc) );
629 my $blist_tag = $self->write_tag(
631 chr(0)x$self->{bucket_list_size},
634 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
635 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
637 $newloc[$num] = $blist_tag->{offset};
640 $self->_release_space(
641 $self->tag_size( $self->{bucket_list_size} ),
642 $tag->{offset} - SIG_SIZE - $self->{data_size},
657 # Found match -- seek to offset and read signature
660 seek($fh, $subloc + $self->_fileobj->{file_offset}, SEEK_SET);
661 read( $fh, $signature, SIG_SIZE);
664 # If value is a hash or array, return new DBM::Deep object with correct offset
666 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
667 my $new_obj = DBM::Deep->new({
669 base_offset => $subloc,
670 fileobj => $self->_fileobj,
673 if ($new_obj->_fileobj->{autobless}) {
675 # Skip over value and plain key to see if object needs
678 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
681 read( $fh, $size, $self->{data_size});
682 $size = unpack($self->{data_pack}, $size);
683 if ($size) { seek($fh, $size, SEEK_CUR); }
686 read( $fh, $bless_bit, 1);
687 if (ord($bless_bit)) {
689 # Yes, object needs to be re-blessed
692 read( $fh, $size, $self->{data_size});
693 $size = unpack($self->{data_pack}, $size);
694 if ($size) { read( $fh, $class_name, $size); }
695 if ($class_name) { $new_obj = bless( $new_obj, $class_name ); }
701 elsif ( $signature eq SIG_INTERNAL ) {
703 read( $fh, $size, $self->{data_size});
704 $size = unpack($self->{data_pack}, $size);
708 read( $fh, $new_loc, $size );
709 $new_loc = unpack( $self->{long_pack}, $new_loc );
711 return $self->read_from_loc( $new_loc );
718 # Otherwise return actual value
720 elsif ( $signature eq SIG_DATA ) {
722 read( $fh, $size, $self->{data_size});
723 $size = unpack($self->{data_pack}, $size);
726 if ($size) { read( $fh, $value, $size); }
731 # Key exists, but content is null
736 sub get_bucket_value {
738 # Fetch single value given tag and MD5 digested key.
741 my ($tag, $md5) = @_;
743 #ACID - This is a read. Can find exact or HEAD
744 my ($subloc, $offset, $size,$is_deleted) = $self->_find_in_buckets( $tag, $md5 );
745 if ( $subloc && !$is_deleted ) {
746 return $self->read_from_loc( $subloc );
753 # Delete single key/value pair given tag and MD5 digested key.
756 my ($tag, $md5) = @_;
760 #ACID - This is a mutation. Must only find the exact transaction
761 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5, 1 );
762 #XXX This needs _release_space()
765 seek($fh, $tag->{offset} + $offset + $self->_fileobj->{file_offset}, SEEK_SET);
766 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
767 print( $fh chr(0) x $self->{bucket_size} );
776 # Check existence of single key given tag and MD5 digested key.
779 my ($tag, $md5) = @_;
781 #ACID - This is a read. Can find exact or HEAD
782 my ($subloc, $offset, $size, $is_deleted) = $self->_find_in_buckets( $tag, $md5 );
783 return ($subloc && !$is_deleted) && 1;
786 sub find_bucket_list {
788 # Locate offset for bucket list, given digested key
791 my ($offset, $md5, $args) = @_;
792 $args = {} unless $args;
797 # Locate offset for bucket list using digest index system
799 my $tag = $self->load_tag( $offset )
800 or $self->_throw_error( "INTERNAL ERROR - Cannot find tag" );
803 while ($tag->{signature} ne SIG_BLIST) {
804 my $num = ord substr($md5, $ch, 1);
806 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
807 $tag = $self->index_lookup( $tag, $num );
810 return if !$args->{create};
812 my $loc = $self->_request_space(
813 $self->tag_size( $self->{bucket_list_size} ),
817 seek($fh, $ref_loc + $self->_fileobj->{file_offset}, SEEK_SET);
818 print( $fh pack($self->{long_pack}, $loc) );
820 $tag = $self->write_tag(
822 chr(0)x$self->{bucket_list_size},
825 $tag->{ref_loc} = $ref_loc;
832 $tag->{ref_loc} = $ref_loc;
840 # Given index tag, lookup single entry in index and return .
843 my ($tag, $index) = @_;
845 my $location = unpack(
849 $index * $self->{long_size},
854 if (!$location) { return; }
856 return $self->load_tag( $location );
861 # Scan index and recursively step into deeper levels, looking for next key.
864 my ($obj, $offset, $ch, $force_return_next) = @_;
868 my $tag = $self->load_tag( $offset );
872 if ($tag->{signature} ne SIG_BLIST) {
873 my $content = $tag->{content};
874 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
876 for (my $idx = $start; $idx < (2**8); $idx++) {
881 $idx * $self->{long_size},
887 my $result = $self->traverse_index(
888 $obj, $subloc, $ch + 1, $force_return_next,
891 if (defined($result)) { return $result; }
895 $obj->{return_next} = 1;
899 my $keys = $tag->{content};
900 if ($force_return_next) { $obj->{return_next} = 1; }
903 # Iterate through buckets, looking for a key match
905 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
906 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
908 # End of bucket list -- return to outer loop
910 $obj->{return_next} = 1;
913 # Located previous key -- return next one found
914 elsif ($key eq $obj->{prev_md5}) {
915 $obj->{return_next} = 1;
918 # Seek to bucket location and skip over signature
919 elsif ($obj->{return_next}) {
920 seek($fh, $subloc + $self->_fileobj->{file_offset}, SEEK_SET);
922 # Skip over value to get to plain key
924 read( $fh, $sig, SIG_SIZE );
927 read( $fh, $size, $self->{data_size});
928 $size = unpack($self->{data_pack}, $size);
929 if ($size) { seek($fh, $size, SEEK_CUR); }
931 # Read in plain key and return as scalar
933 read( $fh, $size, $self->{data_size});
934 $size = unpack($self->{data_pack}, $size);
935 if ($size) { read( $fh, $plain_key, $size); }
941 $obj->{return_next} = 1;
942 } # tag is a bucket list
949 # Locate next key, given digested previous one
954 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
955 $obj->{return_next} = 0;
958 # If the previous key was not specifed, start at the top and
959 # return the first one found.
961 if (!$obj->{prev_md5}) {
962 $obj->{prev_md5} = chr(0) x $self->{hash_size};
963 $obj->{return_next} = 1;
966 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
971 sub _get_key_subloc {
973 my ($keys, $idx) = @_;
975 my ($key, $subloc, $size, $transaction_id, $is_deleted) = unpack(
976 # This is 'a', not 'A'. Please read the pack() documentation for the
977 # difference between the two and why it's important.
978 "a$self->{hash_size} $self->{long_pack}2 n2",
981 ($idx * $self->{bucket_size}),
982 $self->{bucket_size},
986 return ($key, $subloc, $size, $transaction_id, $is_deleted);
989 sub _find_in_buckets {
991 my ($tag, $md5, $exact) = @_;
993 my $trans_id = $self->_fileobj->transaction_id;
998 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
999 my ($key, $subloc, $size, $transaction_id, $is_deleted) = $self->_get_key_subloc(
1000 $tag->{content}, $i,
1003 my @rv = ($subloc, $i * $self->{bucket_size}, $size, $is_deleted);
1005 unless ( $subloc ) {
1006 if ( !$exact && @zero and $trans_id ) {
1007 @rv = ($zero[2], $zero[0] * $self->{bucket_size},$zero[3],$is_deleted);
1012 next BUCKET if $key ne $md5;
1014 # Save off the HEAD in case we need it.
1015 @zero = ($i,$key,$subloc,$size,$transaction_id,$is_deleted) if $transaction_id == 0;
1017 next BUCKET if $transaction_id != $trans_id;
1025 sub _request_space {
1029 my $loc = $self->_fileobj->{end};
1030 $self->_fileobj->{end} += $size;
1035 sub _release_space {
1037 my ($size, $loc) = @_;
1043 my $fh = $self->_fh;
1044 seek( $fh, $loc + $self->_fileobj->{file_offset}, SEEK_SET );
1046 . pack($self->{long_pack}, $size )
1047 . pack($self->{long_pack}, $next_loc )
1054 die "DBM::Deep: $_[1]\n";
1060 # This will be added in later, after more refactoring is done. This is an early
1061 # attempt at refactoring on the physical level instead of the virtual level.
1064 my ($spot, $amount, $unpack) = @_;
1068 my $fh = $self->_fh;
1069 seek( $fh, $spot + $self->_fileobj->{file_offset}, SEEK_SET );
1072 my $bytes_read = read( $fh, $buffer, $amount );
1075 $buffer = unpack( $unpack, $buffer );
1079 return ($buffer, $bytes_read);
1088 my ($spot, $data) = @_;
1092 my $fh = $self->_fh;
1093 seek( $fh, $spot, SEEK_SET );
1099 sub get_file_version {
1104 my $fh = $self->_fh;
1106 seek( $fh, 13 + $self->_fileobj->{file_offset}, SEEK_SET );
1108 my $bytes_read = read( $fh, $buffer, 4 );
1109 unless ( $bytes_read == 4 ) {
1110 $self->_throw_error( "Cannot read file version" );
1113 return unpack( 'N', $buffer );
1116 sub write_file_version {
1118 my ($new_version) = @_;
1122 my $fh = $self->_fh;
1124 seek( $fh, 13 + $self->_fileobj->{file_offset}, SEEK_SET );
1125 print( $fh pack( 'N', $new_version ) );