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), # file version
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 ($file_version, @values) = unpack( 'N S A S A S', $buffer2 );
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;
171 #XXX The duplication of calculate_sizes needs to go away
172 unless ( $obj->{base_offset} ) {
173 my $bytes_read = $self->read_file_header;
175 $self->calculate_sizes;
178 # File is empty -- write header and master index
181 $self->write_file_header;
183 $obj->{base_offset} = $self->_request_space( $self->tag_size( $self->{index_size} ) );
186 $obj->_base_offset, $obj->_type,
187 chr(0)x$self->{index_size},
190 # Flush the filehandle
191 my $old_fh = select $fh;
192 my $old_af = $|; $| = 1; $| = $old_af;
196 $obj->{base_offset} = $bytes_read;
199 # Get our type from master index header
201 my $tag = $self->load_tag($obj->_base_offset)
202 or $self->_throw_error("Corrupted file, no master index record");
204 unless ($obj->_type eq $tag->{signature}) {
205 $self->_throw_error("File type mismatch");
210 $self->calculate_sizes;
213 #XXX We have to make sure we don't mess up when autoflush isn't turned on
214 unless ( $self->_fileobj->{inode} ) {
215 my @stats = stat($fh);
216 $self->_fileobj->{inode} = $stats[1];
217 $self->_fileobj->{end} = $stats[7];
228 return SIG_SIZE + $self->{data_size} + $size;
233 # Given offset, signature and content, create tag and write to disk
236 my ($offset, $sig, $content) = @_;
237 my $size = length( $content );
243 if ( defined $offset ) {
244 seek($fh, $offset + $self->_fileobj->{file_offset}, SEEK_SET);
247 print( $fh $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
268 # print join(':',map{$_||''}caller(1)), $/;
272 seek($fh, $offset + $self->_fileobj->{file_offset}, SEEK_SET);
274 #XXX I'm not sure this check will work if autoflush isn't enabled ...
278 read( $fh, $b, SIG_SIZE + $self->{data_size} );
279 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
282 read( $fh, $buffer, $size);
287 offset => $offset + SIG_SIZE + $self->{data_size},
292 sub _get_dbm_object {
297 if ($item->isa( 'DBM::Deep' )) {
304 my $r = Scalar::Util::reftype( $item ) || '';
305 if ( $r eq 'HASH' ) {
308 my $obj = tied(%$item);
309 if ($obj->isa( 'DBM::Deep' )) {
316 elsif ( $r eq 'ARRAY' ) {
319 my $obj = tied(@$item);
320 if ($obj->isa( 'DBM::Deep' )) {
333 my ($value, $key) = @_;
335 my $is_dbm_deep = eval {
336 local $SIG{'__DIE__'};
337 $value->isa( 'DBM::Deep' );
340 my $len = SIG_SIZE + $self->{data_size}
341 + $self->{data_size} + length( $key );
343 if ( $is_dbm_deep && $value->_fileobj eq $self->_fileobj ) {
344 return $len + $self->{long_size};
347 my $r = Scalar::Util::reftype( $value ) || '';
348 if ( $self->_fileobj->{autobless} ) {
349 # This is for the bit saying whether or not this thing is blessed.
353 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
354 if ( defined $value ) {
355 $len += length( $value );
360 $len += $self->{index_size};
362 # if autobless is enabled, must also take into consideration
363 # the class name as it is stored after the key.
364 if ( $self->_fileobj->{autobless} ) {
365 my $c = Scalar::Util::blessed($value);
366 if ( defined $c && !$is_dbm_deep ) {
367 $len += $self->{data_size} + length($c);
376 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
377 # plain (undigested) key and value.
380 my ($tag, $md5, $plain_key, $value) = @_;
384 # This verifies that only supported values will be stored.
386 my $r = Scalar::Util::reftype( $value );
389 last if $r eq 'HASH';
390 last if $r eq 'ARRAY';
393 "Storage of variables of type '$r' is not supported."
400 my $root = $self->_fileobj;
403 my $actual_length = $self->_length_needed( $value, $plain_key );
405 #ACID - This is a mutation. Must only find the exact transaction
406 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5, 1 );
408 # $self->_release_space( $size, $subloc );
409 # Updating a known md5
410 #XXX This needs updating to use _release_space
414 if ($actual_length <= $size) {
418 $location = $self->_request_space( $actual_length );
421 $tag->{offset} + $offset
422 + $self->{hash_size} + $root->{file_offset},
425 print( $fh pack($self->{long_pack}, $location ) );
426 print( $fh pack($self->{long_pack}, $actual_length ) );
427 print( $fh pack($self->{long_pack}, $root->transaction_id ) );
431 elsif ( defined $offset ) {
432 $location = $self->_request_space( $actual_length );
434 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
435 print( $fh $md5 . pack($self->{long_pack}, $location ) );
436 print( $fh pack($self->{long_pack}, $actual_length ) );
437 print( $fh pack($self->{long_pack}, $root->transaction_id ) );
439 # If bucket didn't fit into list, split into a new index level
440 # split_index() will do the _request_space() call
442 $location = $self->split_index( $md5, $tag );
445 $self->write_value( $location, $plain_key, $value );
452 my ($location, $key, $value) = @_;
457 my $root = $self->_fileobj;
459 my $dbm_deep_obj = _get_dbm_object( $value );
460 if ( $dbm_deep_obj && $dbm_deep_obj->_fileobj ne $self->_fileobj ) {
461 $self->_throw_error( "Cannot cross-reference. Use export() instead" );
464 seek($fh, $location + $root->{file_offset}, SEEK_SET);
467 # Write signature based on content type, set content length and write
470 my $r = Scalar::Util::reftype( $value ) || '';
471 if ( $dbm_deep_obj ) {
472 $self->write_tag( undef, SIG_INTERNAL,pack($self->{long_pack}, $dbm_deep_obj->_base_offset) );
474 elsif ($r eq 'HASH') {
475 if ( !$dbm_deep_obj && tied %{$value} ) {
476 $self->_throw_error( "Cannot store something that is tied" );
478 $self->write_tag( undef, SIG_HASH, chr(0)x$self->{index_size} );
480 elsif ($r eq 'ARRAY') {
481 if ( !$dbm_deep_obj && tied @{$value} ) {
482 $self->_throw_error( "Cannot store something that is tied" );
484 $self->write_tag( undef, SIG_ARRAY, chr(0)x$self->{index_size} );
486 elsif (!defined($value)) {
487 $self->write_tag( undef, SIG_NULL, '' );
490 $self->write_tag( undef, SIG_DATA, $value );
494 # Plain key is stored AFTER value, as keys are typically fetched less often.
496 print( $fh pack($self->{data_pack}, length($key)) . $key );
498 # Internal references don't care about autobless
499 return 1 if $dbm_deep_obj;
502 # If value is blessed, preserve class name
504 if ( $root->{autobless} ) {
505 my $c = Scalar::Util::blessed($value);
506 if ( defined $c && !$dbm_deep_obj ) {
508 print( $fh pack($self->{data_pack}, length($c)) . $c );
516 # Tie the passed in reference so that changes to it are reflected in the
517 # datafile. The use of $location as the base_offset will act as the
518 # the linkage between parent and child.
520 # The overall assignment is a hack around the fact that just tying doesn't
521 # store the values. This may not be the wrong thing to do.
525 tie %$value, 'DBM::Deep', {
526 base_offset => $location,
531 elsif ($r eq 'ARRAY') {
533 tie @$value, 'DBM::Deep', {
534 base_offset => $location,
545 my ($md5, $tag) = @_;
550 my $root = $self->_fileobj;
552 my $loc = $self->_request_space(
553 $self->tag_size( $self->{index_size} ),
556 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
557 print( $fh pack($self->{long_pack}, $loc) );
559 my $index_tag = $self->write_tag(
561 chr(0)x$self->{index_size},
564 my $newtag_loc = $self->_request_space(
565 $self->tag_size( $self->{bucket_list_size} ),
568 my $keys = $tag->{content}
569 . $md5 . pack($self->{long_pack}, $newtag_loc)
570 . pack($self->{long_pack}, 0) # size
571 . pack($self->{long_pack}, 0); # transaction #
575 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
576 my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
578 die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
579 die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
581 my $num = ord(substr($key, $tag->{ch} + 1, 1));
584 seek($fh, $newloc[$num] + $root->{file_offset}, SEEK_SET);
586 read( $fh, $subkeys, $self->{bucket_list_size});
588 # This is looking for the first empty spot
589 my ($subloc, $offset, $size) = $self->_find_in_buckets(
590 { content => $subkeys }, '',
593 seek($fh, $newloc[$num] + $offset + $root->{file_offset}, SEEK_SET);
594 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
599 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
601 my $loc = $self->_request_space(
602 $self->tag_size( $self->{bucket_list_size} ),
605 print( $fh pack($self->{long_pack}, $loc) );
607 my $blist_tag = $self->write_tag(
609 chr(0)x$self->{bucket_list_size},
612 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
613 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
615 $newloc[$num] = $blist_tag->{offset};
618 $self->_release_space(
619 $self->tag_size( $self->{bucket_list_size} ),
620 $tag->{offset} - SIG_SIZE - $self->{data_size},
635 # Found match -- seek to offset and read signature
638 seek($fh, $subloc + $self->_fileobj->{file_offset}, SEEK_SET);
639 read( $fh, $signature, SIG_SIZE);
642 # If value is a hash or array, return new DBM::Deep object with correct offset
644 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
645 my $new_obj = DBM::Deep->new({
647 base_offset => $subloc,
648 fileobj => $self->_fileobj,
651 if ($new_obj->_fileobj->{autobless}) {
653 # Skip over value and plain key to see if object needs
656 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
659 read( $fh, $size, $self->{data_size});
660 $size = unpack($self->{data_pack}, $size);
661 if ($size) { seek($fh, $size, SEEK_CUR); }
664 read( $fh, $bless_bit, 1);
665 if (ord($bless_bit)) {
667 # Yes, object needs to be re-blessed
670 read( $fh, $size, $self->{data_size});
671 $size = unpack($self->{data_pack}, $size);
672 if ($size) { read( $fh, $class_name, $size); }
673 if ($class_name) { $new_obj = bless( $new_obj, $class_name ); }
679 elsif ( $signature eq SIG_INTERNAL ) {
681 read( $fh, $size, $self->{data_size});
682 $size = unpack($self->{data_pack}, $size);
686 read( $fh, $new_loc, $size );
687 $new_loc = unpack( $self->{long_pack}, $new_loc );
689 return $self->read_from_loc( $new_loc );
696 # Otherwise return actual value
698 elsif ( $signature eq SIG_DATA ) {
700 read( $fh, $size, $self->{data_size});
701 $size = unpack($self->{data_pack}, $size);
704 if ($size) { read( $fh, $value, $size); }
709 # Key exists, but content is null
714 sub get_bucket_value {
716 # Fetch single value given tag and MD5 digested key.
719 my ($tag, $md5) = @_;
721 #ACID - This is a read. Can find exact or HEAD
722 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
724 return $self->read_from_loc( $subloc );
731 # Delete single key/value pair given tag and MD5 digested key.
734 my ($tag, $md5) = @_;
738 #ACID - This is a mutation. Must only find the exact transaction
739 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5, 1 );
740 #XXX This needs _release_space()
743 seek($fh, $tag->{offset} + $offset + $self->_fileobj->{file_offset}, SEEK_SET);
744 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
745 print( $fh chr(0) x $self->{bucket_size} );
754 # Check existence of single key given tag and MD5 digested key.
757 my ($tag, $md5) = @_;
759 #ACID - This is a read. Can find exact or HEAD
760 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
764 sub find_bucket_list {
766 # Locate offset for bucket list, given digested key
769 my ($offset, $md5, $args) = @_;
770 $args = {} unless $args;
775 # Locate offset for bucket list using digest index system
777 my $tag = $self->load_tag( $offset )
778 or $self->_throw_error( "INTERNAL ERROR - Cannot find tag" );
781 while ($tag->{signature} ne SIG_BLIST) {
782 my $num = ord substr($md5, $ch, 1);
784 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
785 $tag = $self->index_lookup( $tag, $num );
788 return if !$args->{create};
790 my $loc = $self->_request_space(
791 $self->tag_size( $self->{bucket_list_size} ),
795 seek($fh, $ref_loc + $self->_fileobj->{file_offset}, SEEK_SET);
796 print( $fh pack($self->{long_pack}, $loc) );
798 $tag = $self->write_tag(
800 chr(0)x$self->{bucket_list_size},
803 $tag->{ref_loc} = $ref_loc;
810 $tag->{ref_loc} = $ref_loc;
818 # Given index tag, lookup single entry in index and return .
821 my ($tag, $index) = @_;
823 my $location = unpack(
827 $index * $self->{long_size},
832 if (!$location) { return; }
834 return $self->load_tag( $location );
839 # Scan index and recursively step into deeper levels, looking for next key.
842 my ($obj, $offset, $ch, $force_return_next) = @_;
846 my $tag = $self->load_tag( $offset );
850 if ($tag->{signature} ne SIG_BLIST) {
851 my $content = $tag->{content};
852 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
854 for (my $idx = $start; $idx < (2**8); $idx++) {
859 $idx * $self->{long_size},
865 my $result = $self->traverse_index(
866 $obj, $subloc, $ch + 1, $force_return_next,
869 if (defined($result)) { return $result; }
873 $obj->{return_next} = 1;
877 my $keys = $tag->{content};
878 if ($force_return_next) { $obj->{return_next} = 1; }
881 # Iterate through buckets, looking for a key match
883 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
884 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
886 # End of bucket list -- return to outer loop
888 $obj->{return_next} = 1;
891 # Located previous key -- return next one found
892 elsif ($key eq $obj->{prev_md5}) {
893 $obj->{return_next} = 1;
896 # Seek to bucket location and skip over signature
897 elsif ($obj->{return_next}) {
898 seek($fh, $subloc + $self->_fileobj->{file_offset}, SEEK_SET);
900 # Skip over value to get to plain key
902 read( $fh, $sig, SIG_SIZE );
905 read( $fh, $size, $self->{data_size});
906 $size = unpack($self->{data_pack}, $size);
907 if ($size) { seek($fh, $size, SEEK_CUR); }
909 # Read in plain key and return as scalar
911 read( $fh, $size, $self->{data_size});
912 $size = unpack($self->{data_pack}, $size);
913 if ($size) { read( $fh, $plain_key, $size); }
919 $obj->{return_next} = 1;
920 } # tag is a bucket list
927 # Locate next key, given digested previous one
932 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
933 $obj->{return_next} = 0;
936 # If the previous key was not specifed, start at the top and
937 # return the first one found.
939 if (!$obj->{prev_md5}) {
940 $obj->{prev_md5} = chr(0) x $self->{hash_size};
941 $obj->{return_next} = 1;
944 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
949 sub _get_key_subloc {
951 my ($keys, $idx) = @_;
953 my ($key, $subloc, $size, $transaction) = unpack(
954 # This is 'a', not 'A'. Please read the pack() documentation for the
955 # difference between the two and why it's important.
956 "a$self->{hash_size} $self->{long_pack} $self->{long_pack} $self->{long_pack}",
959 ($idx * $self->{bucket_size}),
960 $self->{bucket_size},
964 return ($key, $subloc, $size, $transaction);
967 sub _find_in_buckets {
969 my ($tag, $md5, $exact) = @_;
971 my $trans_id = $self->_fileobj->transaction_id;
976 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
977 my ($key, $subloc, $size, $transaction_id) = $self->_get_key_subloc(
981 my @rv = ($subloc, $i * $self->{bucket_size}, $size);
984 return @zero if !$exact && @zero and $trans_id;
988 next BUCKET if $key ne $md5;
990 # Save off the HEAD in case we need it.
991 @zero = @rv if $transaction_id == 0;
993 next BUCKET if $transaction_id != $trans_id;
1001 sub _request_space {
1005 my $loc = $self->_fileobj->{end};
1006 $self->_fileobj->{end} += $size;
1011 sub _release_space {
1013 my ($size, $loc) = @_;
1019 my $fh = $self->_fh;
1020 seek( $fh, $loc + $self->_fileobj->{file_offset}, SEEK_SET );
1022 . pack($self->{long_pack}, $size )
1023 . pack($self->{long_pack}, $next_loc )
1030 die "DBM::Deep: $_[1]\n";
1036 # This will be added in later, after more refactoring is done. This is an early
1037 # attempt at refactoring on the physical level instead of the virtual level.
1040 my ($spot, $amount, $unpack) = @_;
1044 my $fh = $self->_fh;
1045 seek( $fh, $spot + $self->_fileobj->{file_offset}, SEEK_SET );
1048 my $bytes_read = read( $fh, $buffer, $amount );
1051 $buffer = unpack( $unpack, $buffer );
1055 return ($buffer, $bytes_read);
1064 my ($spot, $data) = @_;
1068 my $fh = $self->_fh;
1069 seek( $fh, $spot, SEEK_SET );
1075 sub get_file_version {
1080 my $fh = $self->_fh;
1082 seek( $fh, 13 + $self->_fileobj->{file_offset}, SEEK_SET );
1084 my $bytes_read = read( $fh, $buffer, 4 );
1085 unless ( $bytes_read == 4 ) {
1086 $self->_throw_error( "Cannot read file version" );
1089 return unpack( 'N', $buffer );
1092 sub write_file_version {
1094 my ($new_version) = @_;
1098 my $fh = $self->_fh;
1100 seek( $fh, 13 + $self->_fileobj->{file_offset}, SEEK_SET );
1101 print( $fh pack( 'N', $new_version ) );