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} = 'S';
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('S', $self->{long_size}),
118 pack('A', $self->{long_pack}),
119 pack('S', $self->{data_size}),
120 pack('A', $self->{data_pack}),
121 pack('S', $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 S A S A S', $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) = @_;
393 # This verifies that only supported values will be stored.
395 my $r = Scalar::Util::reftype( $value );
398 last if $r eq 'HASH';
399 last if $r eq 'ARRAY';
402 "Storage of variables of type '$r' is not supported."
409 my $root = $self->_fileobj;
412 my $actual_length = $self->_length_needed( $value, $plain_key );
414 #ACID - This is a mutation. Must only find the exact transaction
415 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5, 1 );
417 # $self->_release_space( $size, $subloc );
418 # Updating a known md5
419 #XXX This needs updating to use _release_space
423 if ($actual_length <= $size) {
427 $location = $self->_request_space( $actual_length );
430 $tag->{offset} + $offset
431 + $self->{hash_size} + $root->{file_offset},
434 print( $fh pack($self->{long_pack}, $location ) );
435 print( $fh pack($self->{long_pack}, $actual_length ) );
436 print( $fh pack($self->{long_pack}, $root->transaction_id ) );
440 elsif ( defined $offset ) {
441 $location = $self->_request_space( $actual_length );
443 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
444 print( $fh $md5 . pack($self->{long_pack}, $location ) );
445 print( $fh pack($self->{long_pack}, $actual_length ) );
446 print( $fh pack($self->{long_pack}, $root->transaction_id ) );
448 # If bucket didn't fit into list, split into a new index level
449 # split_index() will do the _request_space() call
451 $location = $self->split_index( $md5, $tag );
454 $self->write_value( $location, $plain_key, $value );
461 my ($location, $key, $value) = @_;
466 my $root = $self->_fileobj;
468 my $dbm_deep_obj = _get_dbm_object( $value );
469 if ( $dbm_deep_obj && $dbm_deep_obj->_fileobj ne $self->_fileobj ) {
470 $self->_throw_error( "Cannot cross-reference. Use export() instead" );
473 seek($fh, $location + $root->{file_offset}, SEEK_SET);
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( undef, 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( undef, 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( undef, SIG_ARRAY, chr(0)x$self->{index_size} );
495 elsif (!defined($value)) {
496 $self->write_tag( undef, SIG_NULL, '' );
499 $self->write_tag( undef, SIG_DATA, $value );
503 # Plain key is stored AFTER value, as keys are typically fetched less often.
505 print( $fh 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 ( $root->{autobless} ) {
514 my $c = Scalar::Util::blessed($value);
515 if ( defined $c && !$dbm_deep_obj ) {
517 print( $fh pack($self->{data_pack}, length($c)) . $c );
525 # Tie the passed in reference so that changes to it are reflected in the
526 # datafile. The use of $location as the base_offset will act as the
527 # the linkage between parent and child.
529 # The overall assignment is a hack around the fact that just tying doesn't
530 # store the values. This may not be the wrong thing to do.
534 tie %$value, 'DBM::Deep', {
535 base_offset => $location,
540 elsif ($r eq 'ARRAY') {
542 tie @$value, 'DBM::Deep', {
543 base_offset => $location,
554 my ($md5, $tag) = @_;
559 my $root = $self->_fileobj;
561 my $loc = $self->_request_space(
562 $self->tag_size( $self->{index_size} ),
565 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
566 print( $fh pack($self->{long_pack}, $loc) );
568 my $index_tag = $self->write_tag(
570 chr(0)x$self->{index_size},
573 my $newtag_loc = $self->_request_space(
574 $self->tag_size( $self->{bucket_list_size} ),
577 my $keys = $tag->{content}
578 . $md5 . pack($self->{long_pack}, $newtag_loc)
579 . pack($self->{long_pack}, 0) # size
580 . pack($self->{long_pack}, 0); # transaction ID
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 seek($fh, $newloc[$num] + $root->{file_offset}, SEEK_SET);
595 read( $fh, $subkeys, $self->{bucket_list_size});
597 # This is looking for the first empty spot
598 my ($subloc, $offset, $size) = $self->_find_in_buckets(
599 { content => $subkeys }, '',
602 seek($fh, $newloc[$num] + $offset + $root->{file_offset}, SEEK_SET);
603 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
608 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
610 my $loc = $self->_request_space(
611 $self->tag_size( $self->{bucket_list_size} ),
614 print( $fh pack($self->{long_pack}, $loc) );
616 my $blist_tag = $self->write_tag(
618 chr(0)x$self->{bucket_list_size},
621 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
622 print( $fh $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},
644 # Found match -- seek to offset and read signature
647 seek($fh, $subloc + $self->_fileobj->{file_offset}, SEEK_SET);
648 read( $fh, $signature, SIG_SIZE);
651 # If value is a hash or array, return new DBM::Deep object with correct offset
653 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
654 my $new_obj = DBM::Deep->new({
656 base_offset => $subloc,
657 fileobj => $self->_fileobj,
660 if ($new_obj->_fileobj->{autobless}) {
662 # Skip over value and plain key to see if object needs
665 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
668 read( $fh, $size, $self->{data_size});
669 $size = unpack($self->{data_pack}, $size);
670 if ($size) { seek($fh, $size, SEEK_CUR); }
673 read( $fh, $bless_bit, 1);
674 if (ord($bless_bit)) {
676 # Yes, object needs to be re-blessed
679 read( $fh, $size, $self->{data_size});
680 $size = unpack($self->{data_pack}, $size);
681 if ($size) { read( $fh, $class_name, $size); }
682 if ($class_name) { $new_obj = bless( $new_obj, $class_name ); }
688 elsif ( $signature eq SIG_INTERNAL ) {
690 read( $fh, $size, $self->{data_size});
691 $size = unpack($self->{data_pack}, $size);
695 read( $fh, $new_loc, $size );
696 $new_loc = unpack( $self->{long_pack}, $new_loc );
698 return $self->read_from_loc( $new_loc );
705 # Otherwise return actual value
707 elsif ( $signature eq SIG_DATA ) {
709 read( $fh, $size, $self->{data_size});
710 $size = unpack($self->{data_pack}, $size);
713 if ($size) { read( $fh, $value, $size); }
718 # Key exists, but content is null
723 sub get_bucket_value {
725 # Fetch single value given tag and MD5 digested key.
728 my ($tag, $md5) = @_;
730 #ACID - This is a read. Can find exact or HEAD
731 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
733 return $self->read_from_loc( $subloc );
740 # Delete single key/value pair given tag and MD5 digested key.
743 my ($tag, $md5) = @_;
747 #ACID - This is a mutation. Must only find the exact transaction
748 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5, 1 );
749 #XXX This needs _release_space()
752 seek($fh, $tag->{offset} + $offset + $self->_fileobj->{file_offset}, SEEK_SET);
753 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
754 print( $fh chr(0) x $self->{bucket_size} );
763 # Check existence of single key given tag and MD5 digested key.
766 my ($tag, $md5) = @_;
768 #ACID - This is a read. Can find exact or HEAD
769 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
773 sub find_bucket_list {
775 # Locate offset for bucket list, given digested key
778 my ($offset, $md5, $args) = @_;
779 $args = {} unless $args;
784 # Locate offset for bucket list using digest index system
786 my $tag = $self->load_tag( $offset )
787 or $self->_throw_error( "INTERNAL ERROR - Cannot find tag" );
790 while ($tag->{signature} ne SIG_BLIST) {
791 my $num = ord substr($md5, $ch, 1);
793 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
794 $tag = $self->index_lookup( $tag, $num );
797 return if !$args->{create};
799 my $loc = $self->_request_space(
800 $self->tag_size( $self->{bucket_list_size} ),
804 seek($fh, $ref_loc + $self->_fileobj->{file_offset}, SEEK_SET);
805 print( $fh pack($self->{long_pack}, $loc) );
807 $tag = $self->write_tag(
809 chr(0)x$self->{bucket_list_size},
812 $tag->{ref_loc} = $ref_loc;
819 $tag->{ref_loc} = $ref_loc;
827 # Given index tag, lookup single entry in index and return .
830 my ($tag, $index) = @_;
832 my $location = unpack(
836 $index * $self->{long_size},
841 if (!$location) { return; }
843 return $self->load_tag( $location );
848 # Scan index and recursively step into deeper levels, looking for next key.
851 my ($obj, $offset, $ch, $force_return_next) = @_;
855 my $tag = $self->load_tag( $offset );
859 if ($tag->{signature} ne SIG_BLIST) {
860 my $content = $tag->{content};
861 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
863 for (my $idx = $start; $idx < (2**8); $idx++) {
868 $idx * $self->{long_size},
874 my $result = $self->traverse_index(
875 $obj, $subloc, $ch + 1, $force_return_next,
878 if (defined($result)) { return $result; }
882 $obj->{return_next} = 1;
886 my $keys = $tag->{content};
887 if ($force_return_next) { $obj->{return_next} = 1; }
890 # Iterate through buckets, looking for a key match
892 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
893 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
895 # End of bucket list -- return to outer loop
897 $obj->{return_next} = 1;
900 # Located previous key -- return next one found
901 elsif ($key eq $obj->{prev_md5}) {
902 $obj->{return_next} = 1;
905 # Seek to bucket location and skip over signature
906 elsif ($obj->{return_next}) {
907 seek($fh, $subloc + $self->_fileobj->{file_offset}, SEEK_SET);
909 # Skip over value to get to plain key
911 read( $fh, $sig, SIG_SIZE );
914 read( $fh, $size, $self->{data_size});
915 $size = unpack($self->{data_pack}, $size);
916 if ($size) { seek($fh, $size, SEEK_CUR); }
918 # Read in plain key and return as scalar
920 read( $fh, $size, $self->{data_size});
921 $size = unpack($self->{data_pack}, $size);
922 if ($size) { read( $fh, $plain_key, $size); }
928 $obj->{return_next} = 1;
929 } # tag is a bucket list
936 # Locate next key, given digested previous one
941 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
942 $obj->{return_next} = 0;
945 # If the previous key was not specifed, start at the top and
946 # return the first one found.
948 if (!$obj->{prev_md5}) {
949 $obj->{prev_md5} = chr(0) x $self->{hash_size};
950 $obj->{return_next} = 1;
953 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
958 sub _get_key_subloc {
960 my ($keys, $idx) = @_;
962 my ($key, $subloc, $size, $transaction) = unpack(
963 # This is 'a', not 'A'. Please read the pack() documentation for the
964 # difference between the two and why it's important.
965 "a$self->{hash_size} $self->{long_pack}3",
968 ($idx * $self->{bucket_size}),
969 $self->{bucket_size},
973 return ($key, $subloc, $size, $transaction);
976 sub _find_in_buckets {
978 my ($tag, $md5, $exact) = @_;
980 my $trans_id = $self->_fileobj->transaction_id;
985 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
986 my ($key, $subloc, $size, $transaction_id) = $self->_get_key_subloc(
990 my @rv = ($subloc, $i * $self->{bucket_size}, $size);
993 if ( !$exact && @zero and $trans_id ) {
994 @rv = ($zero[2], $zero[0] * $self->{bucket_size}, $zero[3]);
999 next BUCKET if $key ne $md5;
1001 # Save off the HEAD in case we need it.
1002 @zero = ($i,$key,$subloc,$size,$transaction_id) if $transaction_id == 0;
1004 next BUCKET if $transaction_id != $trans_id;
1012 sub _request_space {
1016 my $loc = $self->_fileobj->{end};
1017 $self->_fileobj->{end} += $size;
1022 sub _release_space {
1024 my ($size, $loc) = @_;
1030 my $fh = $self->_fh;
1031 seek( $fh, $loc + $self->_fileobj->{file_offset}, SEEK_SET );
1033 . pack($self->{long_pack}, $size )
1034 . pack($self->{long_pack}, $next_loc )
1041 die "DBM::Deep: $_[1]\n";
1047 # This will be added in later, after more refactoring is done. This is an early
1048 # attempt at refactoring on the physical level instead of the virtual level.
1051 my ($spot, $amount, $unpack) = @_;
1055 my $fh = $self->_fh;
1056 seek( $fh, $spot + $self->_fileobj->{file_offset}, SEEK_SET );
1059 my $bytes_read = read( $fh, $buffer, $amount );
1062 $buffer = unpack( $unpack, $buffer );
1066 return ($buffer, $bytes_read);
1075 my ($spot, $data) = @_;
1079 my $fh = $self->_fh;
1080 seek( $fh, $spot, SEEK_SET );
1086 sub get_file_version {
1091 my $fh = $self->_fh;
1093 seek( $fh, 13 + $self->_fileobj->{file_offset}, SEEK_SET );
1095 my $bytes_read = read( $fh, $buffer, 4 );
1096 unless ( $bytes_read == 4 ) {
1097 $self->_throw_error( "Cannot read file version" );
1100 return unpack( 'N', $buffer );
1103 sub write_file_version {
1105 my ($new_version) = @_;
1109 my $fh = $self->_fh;
1111 seek( $fh, 13 + $self->_fileobj->{file_offset}, SEEK_SET );
1112 print( $fh pack( 'N', $new_version ) );