1 package DBM::Deep::Engine;
8 use Fcntl qw( :DEFAULT :flock :seek );
12 # * All the local($/,$\); are to protect read() and print() from -l.
13 # * To add to bucket_size, make sure you modify the following:
16 # - add_bucket() - where the buckets are printed
19 # Setup file and tag signatures. These should never change.
21 sub SIG_FILE () { 'DPDB' }
22 sub SIG_HEADER () { 'h' }
23 sub SIG_INTERNAL () { 'i' }
24 sub SIG_HASH () { 'H' }
25 sub SIG_ARRAY () { 'A' }
26 sub SIG_NULL () { 'N' }
27 sub SIG_DATA () { 'D' }
28 sub SIG_INDEX () { 'I' }
29 sub SIG_BLIST () { 'B' }
30 sub SIG_FREE () { 'F' }
43 digest => \&Digest::MD5::md5,
47 # Maximum number of buckets per list before another level of indexing is
48 # done. Increase this value for slightly greater speed, but larger database
49 # files. DO NOT decrease this value below 16, due to risk of recursive
58 if ( defined $args->{pack_size} ) {
59 if ( lc $args->{pack_size} eq 'small' ) {
60 $args->{long_size} = 2;
61 $args->{long_pack} = 'n';
63 elsif ( lc $args->{pack_size} eq 'medium' ) {
64 $args->{long_size} = 4;
65 $args->{long_pack} = 'N';
67 elsif ( lc $args->{pack_size} eq 'large' ) {
68 $args->{long_size} = 8;
69 $args->{long_pack} = 'Q';
72 die "Unknown pack_size value: '$args->{pack_size}'\n";
76 # Grab the parameters we want to use
77 foreach my $param ( keys %$self ) {
78 next unless exists $args->{$param};
79 $self->{$param} = $args->{$param};
81 Scalar::Util::weaken( $self->{obj} ) if $self->{obj};
83 if ( $self->{max_buckets} < 16 ) {
84 warn "Floor of max_buckets is 16. Setting it to 16 from '$self->{max_buckets}'\n";
85 $self->{max_buckets} = 16;
91 sub _fileobj { return $_[0]{fileobj} }
92 sub _fh { return $_[0]->_fileobj->{fh} }
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 {
135 seek($fh, 0 + $self->_fileobj->{file_offset}, SEEK_SET);
137 my $bytes_read = read( $fh, $buffer, length(SIG_FILE) + 9 );
139 return unless $bytes_read;
141 my ($file_signature, $sig_header, $header_version, $size) = unpack(
145 unless ( $file_signature eq SIG_FILE ) {
146 $self->_fileobj->close;
147 $self->_throw_error( "Signature not found -- file is not a Deep DB" );
150 unless ( $sig_header eq SIG_HEADER ) {
151 $self->_fileobj->close;
152 $self->_throw_error( "Old file version found." );
156 $bytes_read += read( $fh, $buffer2, $size );
157 my ($running_transactions, @values) = unpack( 'N n A n A n', $buffer2 );
159 $self->_fileobj->set_transaction_offset( 13 );
161 if ( @values < 5 || grep { !defined } @values ) {
162 $self->_fileobj->close;
163 $self->_throw_error("Corrupted file - bad header");
166 #XXX Add warnings if values weren't set right
167 @{$self}{qw(long_size long_pack data_size data_pack max_buckets)} = @values;
181 #XXX The duplication of calculate_sizes needs to go away
182 unless ( $obj->{base_offset} ) {
183 my $bytes_read = $self->read_file_header;
185 $self->calculate_sizes;
188 # File is empty -- write header and master index
191 $self->_fileobj->audit( "# Database created on" );
193 $self->write_file_header;
195 $obj->{base_offset} = $self->_fileobj->request_space( $self->tag_size( $self->{index_size} ) );
198 $obj->_base_offset, $obj->_type,
199 chr(0)x$self->{index_size},
202 # Flush the filehandle
203 my $old_fh = select $fh;
204 my $old_af = $|; $| = 1; $| = $old_af;
208 $obj->{base_offset} = $bytes_read;
211 # Get our type from master index header
213 my $tag = $self->load_tag($obj->_base_offset);
216 $self->_throw_error("Corrupted file, no master index record");
219 unless ($obj->_type eq $tag->{signature}) {
221 $self->_throw_error("File type mismatch");
226 $self->calculate_sizes;
229 #XXX We have to make sure we don't mess up when autoflush isn't turned on
230 unless ( $self->_fileobj->{inode} ) {
231 my @stats = stat($fh);
232 $self->_fileobj->{inode} = $stats[1];
233 $self->_fileobj->{end} = $stats[7];
244 return SIG_SIZE + $self->{data_size} + $size;
249 # Given offset, signature and content, create tag and write to disk
252 my ($offset, $sig, $content) = @_;
253 my $size = length( $content );
259 if ( defined $offset ) {
260 seek($fh, $offset + $self->_fileobj->{file_offset}, SEEK_SET);
263 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
265 return unless defined $offset;
270 offset => $offset + SIG_SIZE + $self->{data_size},
277 # Given offset, load single tag and return signature, size and data
286 seek($fh, $offset + $self->_fileobj->{file_offset}, SEEK_SET);
288 #XXX I'm not sure this check will work if autoflush isn't enabled ...
292 read( $fh, $b, SIG_SIZE + $self->{data_size} );
293 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
296 read( $fh, $buffer, $size);
301 offset => $offset + SIG_SIZE + $self->{data_size},
306 sub _get_dbm_object {
311 if ($item->isa( 'DBM::Deep' )) {
318 my $r = Scalar::Util::reftype( $item ) || '';
319 if ( $r eq 'HASH' ) {
322 my $obj = tied(%$item);
323 if ($obj->isa( 'DBM::Deep' )) {
330 elsif ( $r eq 'ARRAY' ) {
333 my $obj = tied(@$item);
334 if ($obj->isa( 'DBM::Deep' )) {
347 my ($value, $key) = @_;
349 my $is_dbm_deep = eval {
350 local $SIG{'__DIE__'};
351 $value->isa( 'DBM::Deep' );
354 my $len = SIG_SIZE + $self->{data_size}
355 + $self->{data_size} + length( $key );
357 if ( $is_dbm_deep && $value->_fileobj eq $self->_fileobj ) {
358 return $len + $self->{long_size};
361 my $r = Scalar::Util::reftype( $value ) || '';
362 if ( $self->_fileobj->{autobless} ) {
363 # This is for the bit saying whether or not this thing is blessed.
367 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
368 if ( defined $value ) {
369 $len += length( $value );
374 $len += $self->{index_size};
376 # if autobless is enabled, must also take into consideration
377 # the class name as it is stored after the key.
378 if ( $self->_fileobj->{autobless} ) {
379 my $c = Scalar::Util::blessed($value);
380 if ( defined $c && !$is_dbm_deep ) {
381 $len += $self->{data_size} + length($c);
390 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
391 # plain (undigested) key and value.
394 my ($tag, $md5, $plain_key, $value, $deleted, $orig_key) = @_;
399 # This verifies that only supported values will be stored.
401 my $r = Scalar::Util::reftype( $value );
404 last if $r eq 'HASH';
405 last if $r eq 'ARRAY';
408 "Storage of variables of type '$r' is not supported."
415 my $fileobj = $self->_fileobj;
417 my $actual_length = $self->_length_needed( $value, $plain_key );
419 #ACID - This is a mutation. Must only find the exact transaction
420 my ($subloc, $offset, $size,$is_deleted) = $self->_find_in_buckets( $tag, $md5, 1 );
423 if ( $fileobj->transaction_id == 0 ) {
424 @transactions = $fileobj->current_transactions;
427 # $self->_release_space( $size, $subloc );
428 # Updating a known md5
429 #XXX This needs updating to use _release_space
433 if ($actual_length <= $size) {
437 $location = $fileobj->request_space( $actual_length );
439 $fileobj->print_at( $tag->{offset} + $offset + $self->{hash_size},
440 pack($self->{long_pack}, $location ),
441 pack($self->{long_pack}, $actual_length ),
442 pack('n n', $fileobj->transaction_id, $deleted ),
447 elsif ( defined $offset ) {
448 $location = $fileobj->request_space( $actual_length );
450 $fileobj->print_at( $tag->{offset} + $offset,
452 pack($self->{long_pack}, $location ),
453 pack($self->{long_pack}, $actual_length ),
454 pack('n n', $fileobj->transaction_id, $deleted ),
457 for ( @transactions ) {
458 my $tag2 = $self->load_tag( $tag->{offset} - SIG_SIZE - $self->{data_size} );
459 $fileobj->{transaction_id} = $_;
460 $self->add_bucket( $tag2, $md5, '', '', 1, $orig_key );
461 $fileobj->{transaction_id} = 0;
464 # If bucket didn't fit into list, split into a new index level
465 # split_index() will do the _fileobj->request_space() call
467 $location = $self->split_index( $md5, $tag );
470 $self->write_value( $location, $plain_key, $value, $orig_key );
477 my ($location, $key, $value, $orig_key) = @_;
482 my $root = $self->_fileobj;
484 my $dbm_deep_obj = _get_dbm_object( $value );
485 if ( $dbm_deep_obj && $dbm_deep_obj->_fileobj ne $self->_fileobj ) {
486 $self->_throw_error( "Cannot cross-reference. Use export() instead" );
489 seek($fh, $location + $root->{file_offset}, SEEK_SET);
492 # Write signature based on content type, set content length and write
495 my $r = Scalar::Util::reftype( $value ) || '';
496 if ( $dbm_deep_obj ) {
497 $self->write_tag( undef, SIG_INTERNAL,pack($self->{long_pack}, $dbm_deep_obj->_base_offset) );
499 elsif ($r eq 'HASH') {
500 if ( !$dbm_deep_obj && tied %{$value} ) {
501 $self->_throw_error( "Cannot store something that is tied" );
503 $self->write_tag( undef, SIG_HASH, chr(0)x$self->{index_size} );
505 elsif ($r eq 'ARRAY') {
506 if ( !$dbm_deep_obj && tied @{$value} ) {
507 $self->_throw_error( "Cannot store something that is tied" );
509 $self->write_tag( undef, SIG_ARRAY, chr(0)x$self->{index_size} );
511 elsif (!defined($value)) {
512 $self->write_tag( undef, SIG_NULL, '' );
515 $self->write_tag( undef, SIG_DATA, $value );
519 # Plain key is stored AFTER value, as keys are typically fetched less often.
521 print( $fh pack($self->{data_pack}, length($key)) . $key );
523 # Internal references don't care about autobless
524 return 1 if $dbm_deep_obj;
527 # If value is blessed, preserve class name
529 if ( $root->{autobless} ) {
530 my $c = Scalar::Util::blessed($value);
531 if ( defined $c && !$dbm_deep_obj ) {
533 print( $fh pack($self->{data_pack}, length($c)) . $c );
541 # Tie the passed in reference so that changes to it are reflected in the
542 # datafile. The use of $location as the base_offset will act as the
543 # the linkage between parent and child.
545 # The overall assignment is a hack around the fact that just tying doesn't
546 # store the values. This may not be the wrong thing to do.
550 tie %$value, 'DBM::Deep', {
551 base_offset => $location,
553 parent => $self->{obj},
554 parent_key => $orig_key,
558 elsif ($r eq 'ARRAY') {
560 tie @$value, 'DBM::Deep', {
561 base_offset => $location,
563 parent => $self->{obj},
564 parent_key => $orig_key,
574 my ($md5, $tag) = @_;
576 my $fileobj = $self->_fileobj;
578 my $loc = $fileobj->request_space(
579 $self->tag_size( $self->{index_size} ),
582 $fileobj->print_at( $tag->{ref_loc}, pack($self->{long_pack}, $loc) );
584 my $index_tag = $self->write_tag(
586 chr(0)x$self->{index_size},
589 my $newtag_loc = $fileobj->request_space(
590 $self->tag_size( $self->{bucket_list_size} ),
593 my $keys = $tag->{content}
594 . $md5 . pack($self->{long_pack}, $newtag_loc)
595 . pack($self->{long_pack}, 0) # size
596 . pack($self->{long_pack}, 0); # transaction ID
600 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
601 my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
603 die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
604 die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
606 my $num = ord(substr($key, $tag->{ch} + 1, 1));
613 seek($fh, $newloc[$num] + $fileobj->{file_offset}, SEEK_SET);
615 read( $fh, $subkeys, $self->{bucket_list_size});
617 # This is looking for the first empty spot
618 my ($subloc, $offset, $size) = $self->_find_in_buckets(
619 { content => $subkeys }, '',
622 $fileobj->print_at( $newloc[$num] + $offset, $key . pack($self->{long_pack}, $old_subloc) );
627 my $loc = $fileobj->request_space(
628 $self->tag_size( $self->{bucket_list_size} ),
632 $index_tag->{offset} + ($num * $self->{long_size}),
633 pack($self->{long_pack}, $loc),
636 my $blist_tag = $self->write_tag(
638 chr(0)x$self->{bucket_list_size},
641 $fileobj->print_at( $blist_tag->{offset}, $key . pack($self->{long_pack}, $old_subloc) );
643 $newloc[$num] = $blist_tag->{offset};
646 $self->_release_space(
647 $self->tag_size( $self->{bucket_list_size} ),
648 $tag->{offset} - SIG_SIZE - $self->{data_size},
656 my ($subloc, $orig_key) = @_;
663 # Found match -- seek to offset and read signature
666 seek($fh, $subloc + $self->_fileobj->{file_offset}, SEEK_SET);
667 read( $fh, $signature, SIG_SIZE);
670 # If value is a hash or array, return new DBM::Deep object with correct offset
672 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
673 my $new_obj = DBM::Deep->new({
675 base_offset => $subloc,
676 fileobj => $self->_fileobj,
677 parent => $self->{obj},
678 parent_key => $orig_key,
681 if ($new_obj->_fileobj->{autobless}) {
683 # Skip over value and plain key to see if object needs
686 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
689 read( $fh, $size, $self->{data_size});
690 $size = unpack($self->{data_pack}, $size);
691 if ($size) { seek($fh, $size, SEEK_CUR); }
694 read( $fh, $bless_bit, 1);
695 if (ord($bless_bit)) {
697 # Yes, object needs to be re-blessed
700 read( $fh, $size, $self->{data_size});
701 $size = unpack($self->{data_pack}, $size);
702 if ($size) { read( $fh, $class_name, $size); }
703 if ($class_name) { $new_obj = bless( $new_obj, $class_name ); }
709 elsif ( $signature eq SIG_INTERNAL ) {
711 read( $fh, $size, $self->{data_size});
712 $size = unpack($self->{data_pack}, $size);
716 read( $fh, $new_loc, $size );
717 $new_loc = unpack( $self->{long_pack}, $new_loc );
719 return $self->read_from_loc( $new_loc, $orig_key );
726 # Otherwise return actual value
728 elsif ( $signature eq SIG_DATA ) {
730 read( $fh, $size, $self->{data_size});
731 $size = unpack($self->{data_pack}, $size);
734 if ($size) { read( $fh, $value, $size); }
739 # Key exists, but content is null
744 sub get_bucket_value {
746 # Fetch single value given tag and MD5 digested key.
749 my ($tag, $md5, $orig_key) = @_;
751 #ACID - This is a read. Can find exact or HEAD
752 my ($subloc, $offset, $size,$is_deleted) = $self->_find_in_buckets( $tag, $md5 );
753 if ( $subloc && !$is_deleted ) {
754 return $self->read_from_loc( $subloc, $orig_key );
761 # Delete single key/value pair given tag and MD5 digested key.
764 my ($tag, $md5, $orig_key) = @_;
766 #ACID - This is a mutation. Must only find the exact transaction
767 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5, 1 );
768 #XXX This needs _release_space() for the value and anything below
770 $self->_fileobj->print_at(
771 $tag->{offset} + $offset,
772 substr($tag->{content}, $offset + $self->{bucket_size} ),
773 chr(0) x $self->{bucket_size},
783 # Check existence of single key given tag and MD5 digested key.
786 my ($tag, $md5) = @_;
788 #ACID - This is a read. Can find exact or HEAD
789 my ($subloc, $offset, $size, $is_deleted) = $self->_find_in_buckets( $tag, $md5 );
790 return ($subloc && !$is_deleted) && 1;
793 sub find_bucket_list {
795 # Locate offset for bucket list, given digested key
798 my ($offset, $md5, $args) = @_;
799 $args = {} unless $args;
804 # Locate offset for bucket list using digest index system
806 my $tag = $self->load_tag( $offset )
807 or $self->_throw_error( "INTERNAL ERROR - Cannot find tag" );
810 while ($tag->{signature} ne SIG_BLIST) {
811 my $num = ord substr($md5, $ch, 1);
813 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
814 $tag = $self->index_lookup( $tag, $num );
817 return if !$args->{create};
819 my $loc = $self->_fileobj->request_space(
820 $self->tag_size( $self->{bucket_list_size} ),
823 $self->_fileobj->print_at( $ref_loc, pack($self->{long_pack}, $loc) );
825 $tag = $self->write_tag(
827 chr(0)x$self->{bucket_list_size},
830 $tag->{ref_loc} = $ref_loc;
837 $tag->{ref_loc} = $ref_loc;
845 # Given index tag, lookup single entry in index and return .
848 my ($tag, $index) = @_;
850 my $location = unpack(
854 $index * $self->{long_size},
859 if (!$location) { return; }
861 return $self->load_tag( $location );
866 # Scan index and recursively step into deeper levels, looking for next key.
869 my ($obj, $offset, $ch, $force_return_next) = @_;
873 my $tag = $self->load_tag( $offset );
877 if ($tag->{signature} ne SIG_BLIST) {
878 my $content = $tag->{content};
879 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
881 for (my $idx = $start; $idx < (2**8); $idx++) {
886 $idx * $self->{long_size},
892 my $result = $self->traverse_index(
893 $obj, $subloc, $ch + 1, $force_return_next,
896 if (defined($result)) { return $result; }
900 $obj->{return_next} = 1;
904 my $keys = $tag->{content};
905 if ($force_return_next) { $obj->{return_next} = 1; }
908 # Iterate through buckets, looking for a key match
910 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
911 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
913 # End of bucket list -- return to outer loop
915 $obj->{return_next} = 1;
918 # Located previous key -- return next one found
919 elsif ($key eq $obj->{prev_md5}) {
920 $obj->{return_next} = 1;
923 # Seek to bucket location and skip over signature
924 elsif ($obj->{return_next}) {
925 seek($fh, $subloc + $self->_fileobj->{file_offset}, SEEK_SET);
927 # Skip over value to get to plain key
929 read( $fh, $sig, SIG_SIZE );
932 read( $fh, $size, $self->{data_size});
933 $size = unpack($self->{data_pack}, $size);
934 if ($size) { seek($fh, $size, SEEK_CUR); }
936 # Read in plain key and return as scalar
938 read( $fh, $size, $self->{data_size});
939 $size = unpack($self->{data_pack}, $size);
940 if ($size) { read( $fh, $plain_key, $size); }
946 $obj->{return_next} = 1;
947 } # tag is a bucket list
954 # Locate next key, given digested previous one
959 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
960 $obj->{return_next} = 0;
963 # If the previous key was not specifed, start at the top and
964 # return the first one found.
966 if (!$obj->{prev_md5}) {
967 $obj->{prev_md5} = chr(0) x $self->{hash_size};
968 $obj->{return_next} = 1;
971 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
976 sub _get_key_subloc {
978 my ($keys, $idx) = @_;
980 my ($key, $subloc, $size, $transaction_id, $is_deleted) = unpack(
981 # This is 'a', not 'A'. Please read the pack() documentation for the
982 # difference between the two and why it's important.
983 "a$self->{hash_size} $self->{long_pack}2 n2",
986 ($idx * $self->{bucket_size}),
987 $self->{bucket_size},
991 return ($key, $subloc, $size, $transaction_id, $is_deleted);
994 sub _find_in_buckets {
996 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 and $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";
1052 # This will be added in later, after more refactoring is done. This is an early
1053 # attempt at refactoring on the physical level instead of the virtual level.
1056 my ($spot, $amount, $unpack) = @_;
1060 my $fh = $self->_fh;
1061 seek( $fh, $spot + $self->_fileobj->{file_offset}, SEEK_SET );
1064 my $bytes_read = read( $fh, $buffer, $amount );
1067 $buffer = unpack( $unpack, $buffer );
1071 return ($buffer, $bytes_read);
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 ) );