1 package DBM::Deep::Engine;
8 use Fcntl qw( :DEFAULT :flock );
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
57 if ( defined $args->{pack_size} ) {
58 if ( lc $args->{pack_size} eq 'small' ) {
59 $args->{long_size} = 2;
60 $args->{long_pack} = 'n';
62 elsif ( lc $args->{pack_size} eq 'medium' ) {
63 $args->{long_size} = 4;
64 $args->{long_pack} = 'N';
66 elsif ( lc $args->{pack_size} eq 'large' ) {
67 $args->{long_size} = 8;
68 $args->{long_pack} = 'Q';
71 die "Unknown pack_size value: '$args->{pack_size}'\n";
75 # Grab the parameters we want to use
76 foreach my $param ( keys %$self ) {
77 next unless exists $args->{$param};
78 $self->{$param} = $args->{$param};
80 Scalar::Util::weaken( $self->{obj} ) if $self->{obj};
82 if ( $self->{max_buckets} < 16 ) {
83 warn "Floor of max_buckets is 16. Setting it to 16 from '$self->{max_buckets}'\n";
84 $self->{max_buckets} = 16;
90 sub _fileobj { return $_[0]{fileobj} }
95 # The 2**8 here indicates the number of different characters in the
96 # current hashing algorithm
97 #XXX Does this need to be updated with different hashing algorithms?
98 $self->{index_size} = (2**8) * $self->{long_size};
99 $self->{bucket_size} = $self->{hash_size} + $self->{long_size} * 3;
100 $self->{bucket_list_size} = $self->{max_buckets} * $self->{bucket_size};
105 sub write_file_header {
108 my $loc = $self->_fileobj->request_space( length( SIG_FILE ) + 21 );
110 $self->_fileobj->print_at( $loc,
113 pack('N', 1), # header version
114 pack('N', 12), # header size
115 pack('N', 0), # currently running transaction IDs
116 pack('n', $self->{long_size}),
117 pack('A', $self->{long_pack}),
118 pack('n', $self->{data_size}),
119 pack('A', $self->{data_pack}),
120 pack('n', $self->{max_buckets}),
123 $self->_fileobj->set_transaction_offset( 13 );
128 sub read_file_header {
131 my $buffer = $self->_fileobj->read_at( 0, length(SIG_FILE) + 9 );
132 return unless length($buffer);
134 my ($file_signature, $sig_header, $header_version, $size) = unpack(
138 unless ( $file_signature eq SIG_FILE ) {
139 $self->_fileobj->close;
140 $self->_throw_error( "Signature not found -- file is not a Deep DB" );
143 unless ( $sig_header eq SIG_HEADER ) {
144 $self->_fileobj->close;
145 $self->_throw_error( "Old file version found." );
148 my $buffer2 = $self->_fileobj->read_at( undef, $size );
149 my ($running_transactions, @values) = unpack( 'N n A n A n', $buffer2 );
151 $self->_fileobj->set_transaction_offset( 13 );
153 if ( @values < 5 || grep { !defined } @values ) {
154 $self->_fileobj->close;
155 $self->_throw_error("Corrupted file - bad header");
158 #XXX Add warnings if values weren't set right
159 @{$self}{qw(long_size long_pack data_size data_pack max_buckets)} = @values;
161 return length($buffer) + length($buffer2);
168 # Need to remove use of $fh here
169 my $fh = $self->_fileobj->{fh};
172 #XXX The duplication of calculate_sizes needs to go away
173 unless ( $obj->{base_offset} ) {
174 my $bytes_read = $self->read_file_header;
176 $self->calculate_sizes;
179 # File is empty -- write header and master index
182 $self->_fileobj->audit( "# Database created on" );
184 $self->write_file_header;
186 $obj->{base_offset} = $self->_fileobj->request_space(
187 $self->tag_size( $self->{index_size} ),
191 $obj->_base_offset, $obj->_type,
192 chr(0)x$self->{index_size},
195 # Flush the filehandle
196 my $old_fh = select $fh;
197 my $old_af = $|; $| = 1; $| = $old_af;
201 $obj->{base_offset} = $bytes_read;
204 # Get our type from master index header
206 my $tag = $self->load_tag($obj->_base_offset);
209 $self->_throw_error("Corrupted file, no master index record");
212 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 $self->_fileobj->set_inode;
233 return SIG_SIZE + $self->{data_size} + $size;
238 # Given offset, signature and content, create tag and write to disk
241 my ($offset, $sig, $content) = @_;
242 my $size = length( $content );
244 $self->_fileobj->print_at(
246 $sig, pack($self->{data_pack}, $size), $content,
249 return unless defined $offset;
254 offset => $offset + SIG_SIZE + $self->{data_size},
261 # Given offset, load single tag and return signature, size and data
266 my $fileobj = $self->_fileobj;
268 my $s = SIG_SIZE + $self->{data_size};
269 my $b = $fileobj->read_at( $offset, $s );
270 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
272 my $buffer = $fileobj->read_at( undef, $size );
277 offset => $offset + SIG_SIZE + $self->{data_size},
282 sub _get_dbm_object {
287 if ($item->isa( 'DBM::Deep' )) {
294 my $r = Scalar::Util::reftype( $item ) || '';
295 if ( $r eq 'HASH' ) {
298 my $obj = tied(%$item);
299 if ($obj->isa( 'DBM::Deep' )) {
306 elsif ( $r eq 'ARRAY' ) {
309 my $obj = tied(@$item);
310 if ($obj->isa( 'DBM::Deep' )) {
323 my ($value, $key) = @_;
325 my $is_dbm_deep = eval {
326 local $SIG{'__DIE__'};
327 $value->isa( 'DBM::Deep' );
331 + $self->{data_size} # size for value
332 + $self->{data_size} # size for key
333 + length( $key ); # length of key
335 if ( $is_dbm_deep && $value->_fileobj eq $self->_fileobj ) {
336 # long_size is for the internal reference
337 return $len + $self->{long_size};
340 if ( $self->_fileobj->{autobless} ) {
341 # This is for the bit saying whether or not this thing is blessed.
345 my $r = Scalar::Util::reftype( $value ) || '';
346 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
347 if ( defined $value ) {
348 $len += length( $value );
353 $len += $self->{index_size};
355 # if autobless is enabled, must also take into consideration
356 # the class name as it is stored after the key.
357 if ( $self->_fileobj->{autobless} ) {
358 my $c = Scalar::Util::blessed($value);
359 if ( defined $c && !$is_dbm_deep ) {
360 $len += $self->{data_size} + length($c);
369 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
370 # plain (undigested) key and value.
373 my ($tag, $md5, $plain_key, $value, $deleted, $orig_key) = @_;
378 # This verifies that only supported values will be stored.
380 my $r = Scalar::Util::reftype( $value );
383 last if $r eq 'HASH';
384 last if $r eq 'ARRAY';
387 "Storage of variables of type '$r' is not supported."
394 my $fileobj = $self->_fileobj;
396 my $actual_length = $self->_length_needed( $value, $plain_key );
398 #ACID - This is a mutation. Must only find the exact transaction
399 my ($subloc, $offset, $size,$is_deleted) = $self->_find_in_buckets( $tag, $md5, 1 );
402 if ( $fileobj->transaction_id == 0 ) {
403 @transactions = $fileobj->current_transactions;
406 # $self->_release_space( $size, $subloc );
407 # Updating a known md5
408 #XXX This needs updating to use _release_space
412 if ($actual_length <= $size) {
416 $location = $fileobj->request_space( $actual_length );
418 $fileobj->print_at( $tag->{offset} + $offset + $self->{hash_size},
419 pack($self->{long_pack}, $location ),
420 pack($self->{long_pack}, $actual_length ),
421 pack('n n', $fileobj->transaction_id, $deleted ),
425 my $old_value = $self->read_from_loc( $subloc, $orig_key );
426 for ( @transactions ) {
427 my $tag2 = $self->load_tag( $tag->{offset} - SIG_SIZE - $self->{data_size} );
428 $fileobj->{transaction_id} = $_;
429 $self->add_bucket( $tag2, $md5, $orig_key, $old_value, undef, $orig_key );
430 $fileobj->{transaction_id} = 0;
432 $tag = $self->load_tag( $tag->{offset} - SIG_SIZE - $self->{data_size} );
435 elsif ( defined $offset ) {
436 $location = $fileobj->request_space( $actual_length );
438 $fileobj->print_at( $tag->{offset} + $offset,
440 pack($self->{long_pack}, $location ),
441 pack($self->{long_pack}, $actual_length ),
442 pack('n n', $fileobj->transaction_id, $deleted ),
445 for ( @transactions ) {
446 my $tag2 = $self->load_tag( $tag->{offset} - SIG_SIZE - $self->{data_size} );
447 $fileobj->{transaction_id} = $_;
448 $self->add_bucket( $tag2, $md5, '', '', 1, $orig_key );
449 $fileobj->{transaction_id} = 0;
451 $tag = $self->load_tag( $tag->{offset} - SIG_SIZE - $self->{data_size} );
453 # If bucket didn't fit into list, split into a new index level
454 # split_index() will do the _fileobj->request_space() call
456 $location = $self->split_index( $md5, $tag );
459 $self->write_value( $location, $plain_key, $value, $orig_key );
466 my ($location, $key, $value, $orig_key) = @_;
468 my $fileobj = $self->_fileobj;
470 my $dbm_deep_obj = _get_dbm_object( $value );
471 if ( $dbm_deep_obj && $dbm_deep_obj->_fileobj ne $fileobj ) {
472 $self->_throw_error( "Cannot cross-reference. Use export() instead" );
476 # Write signature based on content type, set content length and write
479 my $r = Scalar::Util::reftype( $value ) || '';
480 if ( $dbm_deep_obj ) {
481 $self->write_tag( $location, SIG_INTERNAL,pack($self->{long_pack}, $dbm_deep_obj->_base_offset) );
483 elsif ($r eq 'HASH') {
484 if ( !$dbm_deep_obj && tied %{$value} ) {
485 $self->_throw_error( "Cannot store something that is tied" );
487 $self->write_tag( $location, SIG_HASH, chr(0)x$self->{index_size} );
489 elsif ($r eq 'ARRAY') {
490 if ( !$dbm_deep_obj && tied @{$value} ) {
491 $self->_throw_error( "Cannot store something that is tied" );
493 $self->write_tag( $location, SIG_ARRAY, chr(0)x$self->{index_size} );
495 elsif (!defined($value)) {
496 $self->write_tag( $location, SIG_NULL, '' );
499 $self->write_tag( $location, SIG_DATA, $value );
503 # Plain key is stored AFTER value, as keys are typically fetched less often.
505 $fileobj->print_at( undef, pack($self->{data_pack}, length($key)) . $key );
507 # Internal references don't care about autobless
508 return 1 if $dbm_deep_obj;
511 # If value is blessed, preserve class name
513 if ( $fileobj->{autobless} ) {
514 if ( defined( my $c = Scalar::Util::blessed($value) ) ) {
515 $fileobj->print_at( undef, chr(1), pack($self->{data_pack}, length($c)) . $c );
518 $fileobj->print_at( undef, chr(0) );
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,
535 parent => $self->{obj},
536 parent_key => $orig_key,
540 elsif ($r eq 'ARRAY') {
542 tie @$value, 'DBM::Deep', {
543 base_offset => $location,
545 parent => $self->{obj},
546 parent_key => $orig_key,
556 my ($md5, $tag) = @_;
558 my $fileobj = $self->_fileobj;
560 my $loc = $fileobj->request_space(
561 $self->tag_size( $self->{index_size} ),
564 $fileobj->print_at( $tag->{ref_loc}, pack($self->{long_pack}, $loc) );
566 my $index_tag = $self->write_tag(
568 chr(0)x$self->{index_size},
571 my $newtag_loc = $fileobj->request_space(
572 $self->tag_size( $self->{bucket_list_size} ),
575 my $keys = $tag->{content}
576 . $md5 . pack($self->{long_pack}, $newtag_loc)
577 . pack($self->{long_pack}, 0) # size
578 . pack($self->{long_pack}, 0); # transaction ID
582 # The <= here is deliberate - we have max_buckets+1 keys to iterate
583 # through, unlike every other loop that uses max_buckets as a stop.
584 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
585 my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
587 die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
588 die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
590 my $num = ord(substr($key, $tag->{ch} + 1, 1));
593 my $subkeys = $fileobj->read_at( $newloc[$num], $self->{bucket_list_size} );
595 # This is looking for the first empty spot
596 my ($subloc, $offset, $size) = $self->_find_in_buckets(
597 { content => $subkeys }, '',
601 $newloc[$num] + $offset,
602 $key, pack($self->{long_pack}, $old_subloc),
608 my $loc = $fileobj->request_space(
609 $self->tag_size( $self->{bucket_list_size} ),
613 $index_tag->{offset} + ($num * $self->{long_size}),
614 pack($self->{long_pack}, $loc),
617 my $blist_tag = $self->write_tag(
619 chr(0)x$self->{bucket_list_size},
622 $fileobj->print_at( $blist_tag->{offset}, $key . pack($self->{long_pack}, $old_subloc) );
624 $newloc[$num] = $blist_tag->{offset};
627 $self->_release_space(
628 $self->tag_size( $self->{bucket_list_size} ),
629 $tag->{offset} - SIG_SIZE - $self->{data_size},
637 my ($subloc, $orig_key) = @_;
639 my $fileobj = $self->_fileobj;
641 my $signature = $fileobj->read_at( $subloc, 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,
650 fileobj => $self->_fileobj,
651 parent => $self->{obj},
652 parent_key => $orig_key,
655 if ($new_obj->_fileobj->{autobless}) {
657 # Skip over value and plain key to see if object needs
660 $fileobj->increment_pointer( $self->{data_size} + $self->{index_size} );
662 my $size = $fileobj->read_at( undef, $self->{data_size} );
663 $size = unpack($self->{data_pack}, $size);
664 if ($size) { $fileobj->increment_pointer( $size ); }
666 my $bless_bit = $fileobj->read_at( undef, 1 );
667 if (ord($bless_bit)) {
669 # Yes, object needs to be re-blessed
671 my $size = $fileobj->read_at( undef, $self->{data_size} );
672 $size = unpack($self->{data_pack}, $size);
675 if ($size) { $class_name = $fileobj->read_at( undef, $size ); }
676 if (defined $class_name) { $new_obj = bless( $new_obj, $class_name ); }
682 elsif ( $signature eq SIG_INTERNAL ) {
683 my $size = $fileobj->read_at( undef, $self->{data_size} );
684 $size = unpack($self->{data_pack}, $size);
687 my $new_loc = $fileobj->read_at( undef, $size );
688 $new_loc = unpack( $self->{long_pack}, $new_loc );
689 return $self->read_from_loc( $new_loc, $orig_key );
696 # Otherwise return actual value
698 elsif ( $signature eq SIG_DATA ) {
699 my $size = $fileobj->read_at( undef, $self->{data_size} );
700 $size = unpack($self->{data_pack}, $size);
703 if ($size) { $value = $fileobj->read_at( undef, $size ); }
708 # Key exists, but content is null
713 sub get_bucket_value {
715 # Fetch single value given tag and MD5 digested key.
718 my ($tag, $md5, $orig_key) = @_;
720 #ACID - This is a read. Can find exact or HEAD
721 my ($subloc, $offset, $size, $is_deleted) = $self->_find_in_buckets( $tag, $md5 );
724 #XXX Need to use real key
725 # $self->add_bucket( $tag, $md5, $orig_key, undef, undef, $orig_key );
728 elsif ( !$is_deleted ) {
729 return $self->read_from_loc( $subloc, $orig_key );
737 # Delete single key/value pair given tag and MD5 digested key.
740 my ($tag, $md5, $orig_key) = @_;
742 #ACID - Although this is a mutation, we must find any transaction.
743 # This is because we need to mark something as deleted that is in the HEAD.
744 my ($subloc, $offset, $size,$is_deleted) = $self->_find_in_buckets( $tag, $md5 );
748 my $fileobj = $self->_fileobj;
751 if ( $fileobj->transaction_id == 0 ) {
752 @transactions = $fileobj->current_transactions;
755 if ( $fileobj->transaction_id == 0 ) {
756 my $value = $self->read_from_loc( $subloc, $orig_key );
758 for (@transactions) {
759 $fileobj->{transaction_id} = $_;
760 #XXX Need to use real key
761 $self->add_bucket( $tag, $md5, $orig_key, $value, undef, $orig_key );
762 $fileobj->{transaction_id} = 0;
764 $tag = $self->load_tag( $tag->{offset} - SIG_SIZE - $self->{data_size} );
766 #XXX This needs _release_space() for the value and anything below
768 $tag->{offset} + $offset,
769 substr( $tag->{content}, $offset + $self->{bucket_size} ),
770 chr(0) x $self->{bucket_size},
774 $self->add_bucket( $tag, $md5, '', '', 1, $orig_key );
782 # Check existence of single key given tag and MD5 digested key.
785 my ($tag, $md5) = @_;
787 #ACID - This is a read. Can find exact or HEAD
788 my ($subloc, $offset, $size, $is_deleted) = $self->_find_in_buckets( $tag, $md5 );
789 return ($subloc && !$is_deleted) && 1;
792 sub find_bucket_list {
794 # Locate offset for bucket list, given digested key
797 my ($offset, $md5, $args) = @_;
798 $args = {} unless $args;
803 # Locate offset for bucket list using digest index system
805 my $tag = $self->load_tag( $offset )
806 or $self->_throw_error( "INTERNAL ERROR - Cannot find tag" );
809 while ($tag->{signature} ne SIG_BLIST) {
810 my $num = ord substr($md5, $ch, 1);
812 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
813 $tag = $self->index_lookup( $tag, $num );
816 return if !$args->{create};
818 my $loc = $self->_fileobj->request_space(
819 $self->tag_size( $self->{bucket_list_size} ),
822 $self->_fileobj->print_at( $ref_loc, pack($self->{long_pack}, $loc) );
824 $tag = $self->write_tag(
826 chr(0)x$self->{bucket_list_size},
829 $tag->{ref_loc} = $ref_loc;
836 $tag->{ref_loc} = $ref_loc;
844 # Given index tag, lookup single entry in index and return .
847 my ($tag, $index) = @_;
849 my $location = unpack(
853 $index * $self->{long_size},
858 if (!$location) { return; }
860 return $self->load_tag( $location );
865 # Scan index and recursively step into deeper levels, looking for next key.
868 my ($obj, $offset, $ch, $force_return_next) = @_;
870 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;
897 # This is the bucket list
899 my $keys = $tag->{content};
900 if ($force_return_next) { $obj->{return_next} = 1; }
903 # Iterate through buckets, looking for a key match
905 my $transaction_id = $self->_fileobj->transaction_id;
906 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
907 my ($key, $subloc, $size, $trans_id, $is_deleted) = $self->_get_key_subloc( $keys, $i );
910 #XXX Need to find all the copies of this key to find out if $transaction_id has it
911 #XXX marked as deleted, in use, or what.
912 next if $trans_id && $trans_id != $transaction_id;
914 # End of bucket list -- return to outer loop
916 $obj->{return_next} = 1;
919 # Located previous key -- return next one found
920 elsif ($key eq $obj->{prev_md5}) {
921 $obj->{return_next} = 1;
924 # Seek to bucket location and skip over signature
925 elsif ($obj->{return_next}) {
926 my $fileobj = $self->_fileobj;
928 # Skip over value to get to plain key
929 my $sig = $fileobj->read_at( $subloc, SIG_SIZE );
931 my $size = $fileobj->read_at( undef, $self->{data_size} );
932 $size = unpack($self->{data_pack}, $size);
933 if ($size) { $fileobj->increment_pointer( $size ); }
935 # Read in plain key and return as scalar
936 $size = $fileobj->read_at( undef, $self->{data_size} );
937 $size = unpack($self->{data_pack}, $size);
939 if ($size) { $plain_key = $fileobj->read_at( undef, $size); }
945 $obj->{return_next} = 1;
953 # Locate next key, given digested previous one
958 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
959 $obj->{return_next} = 0;
962 # If the previous key was not specifed, start at the top and
963 # return the first one found.
965 if (!$obj->{prev_md5}) {
966 $obj->{prev_md5} = chr(0) x $self->{hash_size};
967 $obj->{return_next} = 1;
970 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
975 sub _get_key_subloc {
977 my ($keys, $idx) = @_;
979 my ($key, $subloc, $size, $transaction_id, $is_deleted) = unpack(
980 # This is 'a', not 'A'. Please read the pack() documentation for the
981 # difference between the two and why it's important.
982 "a$self->{hash_size} $self->{long_pack}2 n2",
985 ($idx * $self->{bucket_size}),
986 $self->{bucket_size},
990 return ($key, $subloc, $size, $transaction_id, $is_deleted);
993 sub _find_in_buckets {
995 my ($tag, $md5, $exact) = @_;
998 my $trans_id = $self->_fileobj->transaction_id;
1003 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
1004 my ($key, $subloc, $size, $transaction_id, $is_deleted) = $self->_get_key_subloc(
1005 $tag->{content}, $i,
1008 my @rv = ($subloc, $i * $self->{bucket_size}, $size, $is_deleted);
1010 unless ( $subloc ) {
1011 if ( !$exact && @zero && $trans_id ) {
1012 @rv = ($zero[2], $zero[0] * $self->{bucket_size},$zero[3],$is_deleted);
1017 next BUCKET if $key ne $md5;
1019 # Save off the HEAD in case we need it.
1020 @zero = ($i,$key,$subloc,$size,$transaction_id,$is_deleted) if $transaction_id == 0;
1022 next BUCKET if $transaction_id != $trans_id;
1030 sub _release_space {
1032 my ($size, $loc) = @_;
1036 $self->_fileobj->print_at( $loc,
1038 pack($self->{long_pack}, $size ),
1039 pack($self->{long_pack}, $next_loc ),
1046 die "DBM::Deep: $_[1]\n";