1 package DBM::Deep::Engine;
8 use Fcntl qw( :DEFAULT :flock :seek );
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 #XXX Does this need to be updated with different hashing algorithms?
96 $self->{index_size} = (2**8) * $self->{long_size};
97 $self->{bucket_size} = $self->{hash_size} + $self->{long_size} * 3;
98 $self->{bucket_list_size} = $self->{max_buckets} * $self->{bucket_size};
103 sub write_file_header {
106 my $loc = $self->_fileobj->request_space( length( SIG_FILE ) + 21 );
108 $self->_fileobj->print_at( $loc,
111 pack('N', 1), # header version
112 pack('N', 12), # header size
113 pack('N', 0), # currently running transaction IDs
114 pack('n', $self->{long_size}),
115 pack('A', $self->{long_pack}),
116 pack('n', $self->{data_size}),
117 pack('A', $self->{data_pack}),
118 pack('n', $self->{max_buckets}),
121 $self->_fileobj->set_transaction_offset( 13 );
126 sub read_file_header {
129 my $buffer = $self->_fileobj->read_at( 0, length(SIG_FILE) + 9 );
130 return unless length($buffer);
132 my ($file_signature, $sig_header, $header_version, $size) = unpack(
136 unless ( $file_signature eq SIG_FILE ) {
137 $self->_fileobj->close;
138 $self->_throw_error( "Signature not found -- file is not a Deep DB" );
141 unless ( $sig_header eq SIG_HEADER ) {
142 $self->_fileobj->close;
143 $self->_throw_error( "Old file version found." );
146 my $buffer2 = $self->_fileobj->read_at( undef, $size );
147 my ($running_transactions, @values) = unpack( 'N n A n A n', $buffer2 );
149 $self->_fileobj->set_transaction_offset( 13 );
151 if ( @values < 5 || grep { !defined } @values ) {
152 $self->_fileobj->close;
153 $self->_throw_error("Corrupted file - bad header");
156 #XXX Add warnings if values weren't set right
157 @{$self}{qw(long_size long_pack data_size data_pack max_buckets)} = @values;
159 return length($buffer) + length($buffer2);
166 # Need to remove use of $fh here
167 my $fh = $self->_fileobj->{fh};
170 #XXX The duplication of calculate_sizes needs to go away
171 unless ( $obj->{base_offset} ) {
172 my $bytes_read = $self->read_file_header;
174 $self->calculate_sizes;
177 # File is empty -- write header and master index
180 $self->_fileobj->audit( "# Database created on" );
182 $self->write_file_header;
184 $obj->{base_offset} = $self->_fileobj->request_space( $self->tag_size( $self->{index_size} ) );
187 $obj->_base_offset, $obj->_type,
188 chr(0)x$self->{index_size},
191 # Flush the filehandle
192 my $old_fh = select $fh;
193 my $old_af = $|; $| = 1; $| = $old_af;
197 $obj->{base_offset} = $bytes_read;
200 # Get our type from master index header
202 my $tag = $self->load_tag($obj->_base_offset);
205 $self->_throw_error("Corrupted file, no master index record");
208 unless ($obj->_type eq $tag->{signature}) {
210 $self->_throw_error("File type mismatch");
215 $self->calculate_sizes;
218 #XXX We have to make sure we don't mess up when autoflush isn't turned on
219 $self->_fileobj->set_inode;
229 return SIG_SIZE + $self->{data_size} + $size;
234 # Given offset, signature and content, create tag and write to disk
237 my ($offset, $sig, $content) = @_;
238 my $size = length( $content );
240 $self->_fileobj->print_at(
242 $sig, pack($self->{data_pack}, $size), $content,
245 return unless defined $offset;
250 offset => $offset + SIG_SIZE + $self->{data_size},
257 # Given offset, load single tag and return signature, size and data
262 my $fileobj = $self->_fileobj;
264 my $s = SIG_SIZE + $self->{data_size};
265 my $b = $fileobj->read_at( $offset, $s );
266 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
268 my $buffer = $fileobj->read_at( undef, $size );
273 offset => $offset + SIG_SIZE + $self->{data_size},
278 sub _get_dbm_object {
283 if ($item->isa( 'DBM::Deep' )) {
290 my $r = Scalar::Util::reftype( $item ) || '';
291 if ( $r eq 'HASH' ) {
294 my $obj = tied(%$item);
295 if ($obj->isa( 'DBM::Deep' )) {
302 elsif ( $r eq 'ARRAY' ) {
305 my $obj = tied(@$item);
306 if ($obj->isa( 'DBM::Deep' )) {
319 my ($value, $key) = @_;
321 my $is_dbm_deep = eval {
322 local $SIG{'__DIE__'};
323 $value->isa( 'DBM::Deep' );
326 my $len = SIG_SIZE + $self->{data_size}
327 + $self->{data_size} + length( $key );
329 if ( $is_dbm_deep && $value->_fileobj eq $self->_fileobj ) {
330 return $len + $self->{long_size};
333 my $r = Scalar::Util::reftype( $value ) || '';
334 if ( $self->_fileobj->{autobless} ) {
335 # This is for the bit saying whether or not this thing is blessed.
339 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
340 if ( defined $value ) {
341 $len += length( $value );
346 $len += $self->{index_size};
348 # if autobless is enabled, must also take into consideration
349 # the class name as it is stored after the key.
350 if ( $self->_fileobj->{autobless} ) {
351 my $c = Scalar::Util::blessed($value);
352 if ( defined $c && !$is_dbm_deep ) {
353 $len += $self->{data_size} + length($c);
362 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
363 # plain (undigested) key and value.
366 my ($tag, $md5, $plain_key, $value, $deleted, $orig_key) = @_;
371 # This verifies that only supported values will be stored.
373 my $r = Scalar::Util::reftype( $value );
376 last if $r eq 'HASH';
377 last if $r eq 'ARRAY';
380 "Storage of variables of type '$r' is not supported."
387 my $fileobj = $self->_fileobj;
389 my $actual_length = $self->_length_needed( $value, $plain_key );
391 #ACID - This is a mutation. Must only find the exact transaction
392 my ($subloc, $offset, $size,$is_deleted) = $self->_find_in_buckets( $tag, $md5, 1 );
395 if ( $fileobj->transaction_id == 0 ) {
396 @transactions = $fileobj->current_transactions;
399 # $self->_release_space( $size, $subloc );
400 # Updating a known md5
401 #XXX This needs updating to use _release_space
405 if ($actual_length <= $size) {
409 $location = $fileobj->request_space( $actual_length );
411 $fileobj->print_at( $tag->{offset} + $offset + $self->{hash_size},
412 pack($self->{long_pack}, $location ),
413 pack($self->{long_pack}, $actual_length ),
414 pack('n n', $fileobj->transaction_id, $deleted ),
419 elsif ( defined $offset ) {
420 $location = $fileobj->request_space( $actual_length );
422 $fileobj->print_at( $tag->{offset} + $offset,
424 pack($self->{long_pack}, $location ),
425 pack($self->{long_pack}, $actual_length ),
426 pack('n n', $fileobj->transaction_id, $deleted ),
429 for ( @transactions ) {
430 my $tag2 = $self->load_tag( $tag->{offset} - SIG_SIZE - $self->{data_size} );
431 $fileobj->{transaction_id} = $_;
432 $self->add_bucket( $tag2, $md5, '', '', 1, $orig_key );
433 $fileobj->{transaction_id} = 0;
436 # If bucket didn't fit into list, split into a new index level
437 # split_index() will do the _fileobj->request_space() call
439 $location = $self->split_index( $md5, $tag );
442 $self->write_value( $location, $plain_key, $value, $orig_key );
449 my ($location, $key, $value, $orig_key) = @_;
451 my $fileobj = $self->_fileobj;
453 my $dbm_deep_obj = _get_dbm_object( $value );
454 if ( $dbm_deep_obj && $dbm_deep_obj->_fileobj ne $fileobj ) {
455 $self->_throw_error( "Cannot cross-reference. Use export() instead" );
459 # Write signature based on content type, set content length and write
462 my $r = Scalar::Util::reftype( $value ) || '';
463 if ( $dbm_deep_obj ) {
464 $self->write_tag( $location, SIG_INTERNAL,pack($self->{long_pack}, $dbm_deep_obj->_base_offset) );
466 elsif ($r eq 'HASH') {
467 if ( !$dbm_deep_obj && tied %{$value} ) {
468 $self->_throw_error( "Cannot store something that is tied" );
470 $self->write_tag( $location, SIG_HASH, chr(0)x$self->{index_size} );
472 elsif ($r eq 'ARRAY') {
473 if ( !$dbm_deep_obj && tied @{$value} ) {
474 $self->_throw_error( "Cannot store something that is tied" );
476 $self->write_tag( $location, SIG_ARRAY, chr(0)x$self->{index_size} );
478 elsif (!defined($value)) {
479 $self->write_tag( $location, SIG_NULL, '' );
482 $self->write_tag( $location, SIG_DATA, $value );
486 # Plain key is stored AFTER value, as keys are typically fetched less often.
488 $fileobj->print_at( undef, pack($self->{data_pack}, length($key)) . $key );
490 # Internal references don't care about autobless
491 return 1 if $dbm_deep_obj;
494 # If value is blessed, preserve class name
496 if ( $fileobj->{autobless} ) {
497 my $c = Scalar::Util::blessed($value);
498 if ( defined $c && !$dbm_deep_obj ) {
499 $fileobj->print_at( undef, chr(1), pack($self->{data_pack}, length($c)) . $c );
502 $fileobj->print_at( undef, chr(0) );
507 # Tie the passed in reference so that changes to it are reflected in the
508 # datafile. The use of $location as the base_offset will act as the
509 # the linkage between parent and child.
511 # The overall assignment is a hack around the fact that just tying doesn't
512 # store the values. This may not be the wrong thing to do.
516 tie %$value, 'DBM::Deep', {
517 base_offset => $location,
519 parent => $self->{obj},
520 parent_key => $orig_key,
524 elsif ($r eq 'ARRAY') {
526 tie @$value, 'DBM::Deep', {
527 base_offset => $location,
529 parent => $self->{obj},
530 parent_key => $orig_key,
540 my ($md5, $tag) = @_;
542 my $fileobj = $self->_fileobj;
544 my $loc = $fileobj->request_space(
545 $self->tag_size( $self->{index_size} ),
548 $fileobj->print_at( $tag->{ref_loc}, pack($self->{long_pack}, $loc) );
550 my $index_tag = $self->write_tag(
552 chr(0)x$self->{index_size},
555 my $newtag_loc = $fileobj->request_space(
556 $self->tag_size( $self->{bucket_list_size} ),
559 my $keys = $tag->{content}
560 . $md5 . pack($self->{long_pack}, $newtag_loc)
561 . pack($self->{long_pack}, 0) # size
562 . pack($self->{long_pack}, 0); # transaction ID
566 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
567 my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
569 die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
570 die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
572 my $num = ord(substr($key, $tag->{ch} + 1, 1));
575 my $subkeys = $fileobj->read_at( $newloc[$num], $self->{bucket_list_size} );
577 # This is looking for the first empty spot
578 my ($subloc, $offset, $size) = $self->_find_in_buckets(
579 { content => $subkeys }, '',
582 $fileobj->print_at( $newloc[$num] + $offset, $key . pack($self->{long_pack}, $old_subloc) );
587 my $loc = $fileobj->request_space(
588 $self->tag_size( $self->{bucket_list_size} ),
592 $index_tag->{offset} + ($num * $self->{long_size}),
593 pack($self->{long_pack}, $loc),
596 my $blist_tag = $self->write_tag(
598 chr(0)x$self->{bucket_list_size},
601 $fileobj->print_at( $blist_tag->{offset}, $key . pack($self->{long_pack}, $old_subloc) );
603 $newloc[$num] = $blist_tag->{offset};
606 $self->_release_space(
607 $self->tag_size( $self->{bucket_list_size} ),
608 $tag->{offset} - SIG_SIZE - $self->{data_size},
616 my ($subloc, $orig_key) = @_;
618 my $fileobj = $self->_fileobj;
621 # Found match -- seek to offset and read signature
623 my $signature = $fileobj->read_at( $subloc, SIG_SIZE );
626 # If value is a hash or array, return new DBM::Deep object with correct offset
628 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
629 my $new_obj = DBM::Deep->new({
631 base_offset => $subloc,
632 fileobj => $self->_fileobj,
633 parent => $self->{obj},
634 parent_key => $orig_key,
637 if ($new_obj->_fileobj->{autobless}) {
639 # Skip over value and plain key to see if object needs
642 $fileobj->increment_pointer( $self->{data_size} + $self->{index_size} );
644 my $size = $fileobj->read_at( undef, $self->{data_size} );
645 $size = unpack($self->{data_pack}, $size);
646 if ($size) { $fileobj->increment_pointer( $size ); }
648 my $bless_bit = $fileobj->read_at( undef, 1 );
649 if (ord($bless_bit)) {
651 # Yes, object needs to be re-blessed
653 my $size = $fileobj->read_at( undef, $self->{data_size} );
654 $size = unpack($self->{data_pack}, $size);
657 if ($size) { $class_name = $fileobj->read_at( undef, $size ); }
658 if (defined $class_name) { $new_obj = bless( $new_obj, $class_name ); }
664 elsif ( $signature eq SIG_INTERNAL ) {
665 my $size = $fileobj->read_at( undef, $self->{data_size} );
666 $size = unpack($self->{data_pack}, $size);
669 my $new_loc = $fileobj->read_at( undef, $size );
670 $new_loc = unpack( $self->{long_pack}, $new_loc );
671 return $self->read_from_loc( $new_loc, $orig_key );
678 # Otherwise return actual value
680 elsif ( $signature eq SIG_DATA ) {
681 my $size = $fileobj->read_at( undef, $self->{data_size} );
682 $size = unpack($self->{data_pack}, $size);
685 if ($size) { $value = $fileobj->read_at( undef, $size ); }
690 # Key exists, but content is null
695 sub get_bucket_value {
697 # Fetch single value given tag and MD5 digested key.
700 my ($tag, $md5, $orig_key) = @_;
702 #ACID - This is a read. Can find exact or HEAD
703 my ($subloc, $offset, $size,$is_deleted) = $self->_find_in_buckets( $tag, $md5 );
704 if ( $subloc && !$is_deleted ) {
705 return $self->read_from_loc( $subloc, $orig_key );
712 # Delete single key/value pair given tag and MD5 digested key.
715 my ($tag, $md5, $orig_key) = @_;
717 #ACID - This is a mutation. Must only find the exact transaction
718 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5, 1 );
719 #XXX This needs _release_space() for the value and anything below
721 $self->_fileobj->print_at(
722 $tag->{offset} + $offset,
723 substr($tag->{content}, $offset + $self->{bucket_size} ),
724 chr(0) x $self->{bucket_size},
734 # Check existence of single key given tag and MD5 digested key.
737 my ($tag, $md5) = @_;
739 #ACID - This is a read. Can find exact or HEAD
740 my ($subloc, $offset, $size, $is_deleted) = $self->_find_in_buckets( $tag, $md5 );
741 return ($subloc && !$is_deleted) && 1;
744 sub find_bucket_list {
746 # Locate offset for bucket list, given digested key
749 my ($offset, $md5, $args) = @_;
750 $args = {} unless $args;
755 # Locate offset for bucket list using digest index system
757 my $tag = $self->load_tag( $offset )
758 or $self->_throw_error( "INTERNAL ERROR - Cannot find tag" );
761 while ($tag->{signature} ne SIG_BLIST) {
762 my $num = ord substr($md5, $ch, 1);
764 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
765 $tag = $self->index_lookup( $tag, $num );
768 return if !$args->{create};
770 my $loc = $self->_fileobj->request_space(
771 $self->tag_size( $self->{bucket_list_size} ),
774 $self->_fileobj->print_at( $ref_loc, pack($self->{long_pack}, $loc) );
776 $tag = $self->write_tag(
778 chr(0)x$self->{bucket_list_size},
781 $tag->{ref_loc} = $ref_loc;
788 $tag->{ref_loc} = $ref_loc;
796 # Given index tag, lookup single entry in index and return .
799 my ($tag, $index) = @_;
801 my $location = unpack(
805 $index * $self->{long_size},
810 if (!$location) { return; }
812 return $self->load_tag( $location );
817 # Scan index and recursively step into deeper levels, looking for next key.
820 my ($obj, $offset, $ch, $force_return_next) = @_;
822 my $tag = $self->load_tag( $offset );
824 if ($tag->{signature} ne SIG_BLIST) {
825 my $content = $tag->{content};
826 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
828 for (my $idx = $start; $idx < (2**8); $idx++) {
833 $idx * $self->{long_size},
839 my $result = $self->traverse_index(
840 $obj, $subloc, $ch + 1, $force_return_next,
843 if (defined($result)) { return $result; }
847 $obj->{return_next} = 1;
851 my $keys = $tag->{content};
852 if ($force_return_next) { $obj->{return_next} = 1; }
855 # Iterate through buckets, looking for a key match
857 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
858 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
860 # End of bucket list -- return to outer loop
862 $obj->{return_next} = 1;
865 # Located previous key -- return next one found
866 elsif ($key eq $obj->{prev_md5}) {
867 $obj->{return_next} = 1;
870 # Seek to bucket location and skip over signature
871 elsif ($obj->{return_next}) {
872 my $fileobj = $self->_fileobj;
874 # Skip over value to get to plain key
875 my $sig = $fileobj->read_at( $subloc, SIG_SIZE );
877 my $size = $fileobj->read_at( undef, $self->{data_size} );
878 $size = unpack($self->{data_pack}, $size);
879 if ($size) { $fileobj->increment_pointer( $size ); }
881 # Read in plain key and return as scalar
882 $size = $fileobj->read_at( undef, $self->{data_size} );
883 $size = unpack($self->{data_pack}, $size);
885 if ($size) { $plain_key = $fileobj->read_at( undef, $size); }
891 $obj->{return_next} = 1;
892 } # tag is a bucket list
899 # Locate next key, given digested previous one
904 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
905 $obj->{return_next} = 0;
908 # If the previous key was not specifed, start at the top and
909 # return the first one found.
911 if (!$obj->{prev_md5}) {
912 $obj->{prev_md5} = chr(0) x $self->{hash_size};
913 $obj->{return_next} = 1;
916 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
921 sub _get_key_subloc {
923 my ($keys, $idx) = @_;
925 my ($key, $subloc, $size, $transaction_id, $is_deleted) = unpack(
926 # This is 'a', not 'A'. Please read the pack() documentation for the
927 # difference between the two and why it's important.
928 "a$self->{hash_size} $self->{long_pack}2 n2",
931 ($idx * $self->{bucket_size}),
932 $self->{bucket_size},
936 return ($key, $subloc, $size, $transaction_id, $is_deleted);
939 sub _find_in_buckets {
941 my ($tag, $md5, $exact) = @_;
943 my $trans_id = $self->_fileobj->transaction_id;
948 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
949 my ($key, $subloc, $size, $transaction_id, $is_deleted) = $self->_get_key_subloc(
953 my @rv = ($subloc, $i * $self->{bucket_size}, $size, $is_deleted);
956 if ( !$exact && @zero and $trans_id ) {
957 @rv = ($zero[2], $zero[0] * $self->{bucket_size},$zero[3],$is_deleted);
962 next BUCKET if $key ne $md5;
964 # Save off the HEAD in case we need it.
965 @zero = ($i,$key,$subloc,$size,$transaction_id,$is_deleted) if $transaction_id == 0;
967 next BUCKET if $transaction_id != $trans_id;
977 my ($size, $loc) = @_;
981 $self->_fileobj->print_at( $loc,
983 pack($self->{long_pack}, $size ),
984 pack($self->{long_pack}, $next_loc ),
991 die "DBM::Deep: $_[1]\n";