1 package DBM::Deep::Engine;
5 use Fcntl qw( :DEFAULT :flock :seek );
8 # Setup file and tag signatures. These should never change.
10 sub SIG_FILE () { 'DPDB' }
11 sub SIG_INTERNAL () { 'i' }
12 sub SIG_HASH () { 'H' }
13 sub SIG_ARRAY () { 'A' }
14 sub SIG_NULL () { 'N' }
15 sub SIG_DATA () { 'D' }
16 sub SIG_INDEX () { 'I' }
17 sub SIG_BLIST () { 'B' }
18 sub SIG_FREE () { 'F' }
31 digest => \&Digest::MD5::md5,
35 # Maximum number of buckets per list before another level of indexing is
36 # done. Increase this value for slightly greater speed, but larger database
37 # files. DO NOT decrease this value below 16, due to risk of recursive
43 if ( defined $args->{pack_size} ) {
44 if ( lc $args->{pack_size} eq 'small' ) {
45 $args->{long_size} = 2;
46 $args->{long_pack} = 'S';
48 elsif ( lc $args->{pack_size} eq 'medium' ) {
49 $args->{long_size} = 4;
50 $args->{long_pack} = 'N';
52 elsif ( lc $args->{pack_size} eq 'large' ) {
53 $args->{long_size} = 8;
54 $args->{long_pack} = 'Q';
57 die "Unknown pack_size value: '$args->{pack_size}'\n";
61 # Grab the parameters we want to use
62 foreach my $param ( keys %$self ) {
63 next unless exists $args->{$param};
64 $self->{$param} = $args->{$param};
67 if ( $self->{max_buckets} < 16 ) {
68 warn "Floor of max_buckets is 16. Setting it to 16 from '$self->{max_buckets}'\n";
69 $self->{max_buckets} = 16;
72 $self->{index_size} = (2**8) * $self->{long_size};
73 $self->{bucket_size} = $self->{hash_size} + $self->{long_size} * 2;
74 $self->{bucket_list_size} = $self->{max_buckets} * $self->{bucket_size};
79 sub write_file_header {
85 my $loc = $self->_request_space(
86 $obj, length( SIG_FILE ) + $self->{data_size},
88 seek($fh, $loc + $obj->_root->{file_offset}, SEEK_SET);
89 print( $fh SIG_FILE, pack('N', 0) );
94 sub read_file_header {
100 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
102 my $bytes_read = read(
103 $fh, $buffer, length(SIG_FILE) + $self->{data_size},
107 my ($signature, $version) = unpack( 'A4 N', $buffer );
108 unless ($signature eq SIG_FILE) {
109 $self->close_fh( $obj );
110 $obj->_throw_error("Signature not found -- file is not a Deep DB");
121 $self->open( $obj ) if !defined $obj->_fh;
126 unless ( $obj->{base_offset} ) {
127 my $bytes_read = $self->read_file_header( $obj );
130 # File is empty -- write header and master index
133 $self->write_file_header( $obj );
135 $obj->{base_offset} = $self->_request_space(
136 $obj, $self->tag_size( $self->{index_size} ),
140 $obj, $obj->_base_offset, $obj->_type,
141 chr(0)x$self->{index_size},
144 # Flush the filehandle
145 my $old_fh = select $fh;
146 my $old_af = $|; $| = 1; $| = $old_af;
150 $obj->{base_offset} = $bytes_read;
153 # Get our type from master index header
155 my $tag = $self->load_tag($obj, $obj->_base_offset)
156 or $obj->_throw_error("Corrupted file, no master index record");
158 unless ($obj->{type} eq $tag->{signature}) {
159 $obj->_throw_error("File type mismatch");
164 #XXX We have to make sure we don't mess up when autoflush isn't turned on
165 unless ( $obj->_root->{inode} ) {
166 my @stats = stat($obj->_fh);
167 $obj->_root->{inode} = $stats[1];
168 $obj->_root->{end} = $stats[7];
178 # Open a fh to the database, create if nonexistent.
179 # Make sure file signature matches DBM::Deep spec.
184 # Theoretically, adding O_BINARY should remove the need for the binmode
185 # Of course, testing it is going to be ... interesting.
186 my $flags = O_RDWR | O_CREAT | O_BINARY;
189 my $filename = $obj->_root->{file};
190 sysopen( $fh, $filename, $flags )
191 or $obj->_throw_error("Cannot sysopen file '$filename': $!");
192 $obj->_root->{fh} = $fh;
194 # Even though we use O_BINARY, better be safe than sorry.
197 if ($obj->_root->{autoflush}) {
198 my $old = select $fh;
210 if ( my $fh = $obj->_root->{fh} ) {
213 $obj->_root->{fh} = undef;
221 return SIG_SIZE + $self->{data_size} + $size;
226 # Given offset, signature and content, create tag and write to disk
229 my ($obj, $offset, $sig, $content) = @_;
230 my $size = length( $content );
234 if ( defined $offset ) {
235 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
238 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
240 return unless defined $offset;
245 offset => $offset + SIG_SIZE + $self->{data_size},
252 # Given offset, load single tag and return signature, size and data
255 my ($obj, $offset) = @_;
257 # print join(':',map{$_||''}caller(1)), $/;
261 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
263 #XXX I'm not sure this check will work if autoflush isn't enabled ...
267 read( $fh, $b, SIG_SIZE + $self->{data_size} );
268 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
271 read( $fh, $buffer, $size);
276 offset => $offset + SIG_SIZE + $self->{data_size},
281 sub _get_dbm_object {
286 if ($item->isa( 'DBM::Deep' )) {
293 my $r = Scalar::Util::reftype( $item ) || '';
294 if ( $r eq 'HASH' ) {
297 my $obj = tied(%$item);
298 if ($obj->isa( 'DBM::Deep' )) {
305 elsif ( $r eq 'ARRAY' ) {
308 my $obj = tied(@$item);
309 if ($obj->isa( 'DBM::Deep' )) {
322 my ($obj, $value, $key) = @_;
324 my $is_dbm_deep = eval {
325 local $SIG{'__DIE__'};
326 $value->isa( 'DBM::Deep' );
329 my $len = SIG_SIZE + $self->{data_size}
330 + $self->{data_size} + length( $key );
332 if ( $is_dbm_deep && $value->_root eq $obj->_root ) {
333 return $len + $self->{long_size};
336 my $r = Scalar::Util::reftype( $value ) || '';
337 if ( $obj->_root->{autobless} ) {
338 # This is for the bit saying whether or not this thing is blessed.
342 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
343 if ( defined $value ) {
344 $len += length( $value );
349 $len += $self->{index_size};
351 # if autobless is enabled, must also take into consideration
352 # the class name as it is stored after the key.
353 if ( $obj->_root->{autobless} ) {
354 my $c = Scalar::Util::blessed($value);
355 if ( defined $c && !$is_dbm_deep ) {
356 $len += $self->{data_size} + length($c);
365 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
366 # plain (undigested) key and value.
369 my ($obj, $tag, $md5, $plain_key, $value) = @_;
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 $root = $obj->_root;
390 my $actual_length = $self->_length_needed( $obj, $value, $plain_key );
392 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
394 # $self->_release_space( $obj, $size, $subloc );
395 # Updating a known md5
396 #XXX This needs updating to use _release_space
400 if ($actual_length <= $size) {
404 $location = $self->_request_space( $obj, $actual_length );
407 $tag->{offset} + $offset
408 + $self->{hash_size} + $root->{file_offset},
411 print( $fh pack($self->{long_pack}, $location ) );
412 print( $fh pack($self->{long_pack}, $actual_length ) );
416 elsif ( defined $offset ) {
417 $location = $self->_request_space( $obj, $actual_length );
419 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
420 print( $fh $md5 . pack($self->{long_pack}, $location ) );
421 print( $fh pack($self->{long_pack}, $actual_length ) );
423 # If bucket didn't fit into list, split into a new index level
424 # split_index() will do the _request_space() call
426 $location = $self->split_index( $obj, $md5, $tag );
429 $self->write_value( $obj, $location, $plain_key, $value );
436 my ($obj, $location, $key, $value) = @_;
439 my $root = $obj->_root;
441 my $dbm_deep_obj = _get_dbm_object( $value );
442 if ( $dbm_deep_obj && $dbm_deep_obj->_root ne $obj->_root ) {
443 $obj->_throw_error( "Cannot cross-reference. Use export() instead" );
446 seek($fh, $location + $root->{file_offset}, SEEK_SET);
449 # Write signature based on content type, set content length and write
452 my $r = Scalar::Util::reftype( $value ) || '';
453 if ( $dbm_deep_obj ) {
454 $self->write_tag( $obj, undef, SIG_INTERNAL,pack($self->{long_pack}, $dbm_deep_obj->_base_offset) );
456 elsif ($r eq 'HASH') {
457 if ( !$dbm_deep_obj && tied %{$value} ) {
458 $obj->_throw_error( "Cannot store something that is tied" );
460 $self->write_tag( $obj, undef, SIG_HASH, chr(0)x$self->{index_size} );
462 elsif ($r eq 'ARRAY') {
463 if ( !$dbm_deep_obj && tied @{$value} ) {
464 $obj->_throw_error( "Cannot store something that is tied" );
466 $self->write_tag( $obj, undef, SIG_ARRAY, chr(0)x$self->{index_size} );
468 elsif (!defined($value)) {
469 $self->write_tag( $obj, undef, SIG_NULL, '' );
472 $self->write_tag( $obj, undef, SIG_DATA, $value );
476 # Plain key is stored AFTER value, as keys are typically fetched less often.
478 print( $fh pack($self->{data_pack}, length($key)) . $key );
480 # Internal references don't care about autobless
481 return 1 if $dbm_deep_obj;
484 # If value is blessed, preserve class name
486 if ( $root->{autobless} ) {
487 my $c = Scalar::Util::blessed($value);
488 if ( defined $c && !$dbm_deep_obj ) {
490 print( $fh pack($self->{data_pack}, length($c)) . $c );
498 # Tie the passed in reference so that changes to it are reflected in the
499 # datafile. The use of $location as the base_offset will act as the
500 # the linkage between parent and child.
502 # The overall assignment is a hack around the fact that just tying doesn't
503 # store the values. This may not be the wrong thing to do.
507 tie %$value, 'DBM::Deep', {
508 base_offset => $location,
513 elsif ($r eq 'ARRAY') {
515 tie @$value, 'DBM::Deep', {
516 base_offset => $location,
527 my ($obj, $md5, $tag) = @_;
530 my $root = $obj->_root;
532 my $loc = $self->_request_space(
533 $obj, $self->tag_size( $self->{index_size} ),
536 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
537 print( $fh pack($self->{long_pack}, $loc) );
539 my $index_tag = $self->write_tag(
540 $obj, $loc, SIG_INDEX,
541 chr(0)x$self->{index_size},
544 my $newtag_loc = $self->_request_space(
545 $obj, $self->tag_size( $self->{bucket_list_size} ),
548 my $keys = $tag->{content}
549 . $md5 . pack($self->{long_pack}, $newtag_loc)
550 . pack($self->{long_pack}, 0);
554 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
555 my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
557 die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
558 die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
560 my $num = ord(substr($key, $tag->{ch} + 1, 1));
563 seek($fh, $newloc[$num] + $root->{file_offset}, SEEK_SET);
565 read( $fh, $subkeys, $self->{bucket_list_size});
567 # This is looking for the first empty spot
568 my ($subloc, $offset, $size) = $self->_find_in_buckets(
569 { content => $subkeys }, '',
572 seek($fh, $newloc[$num] + $offset + $root->{file_offset}, SEEK_SET);
573 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
578 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
580 my $loc = $self->_request_space(
581 $obj, $self->tag_size( $self->{bucket_list_size} ),
584 print( $fh pack($self->{long_pack}, $loc) );
586 my $blist_tag = $self->write_tag(
587 $obj, $loc, SIG_BLIST,
588 chr(0)x$self->{bucket_list_size},
591 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
592 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
594 $newloc[$num] = $blist_tag->{offset};
597 $self->_release_space(
598 $obj, $self->tag_size( $self->{bucket_list_size} ),
599 $tag->{offset} - SIG_SIZE - $self->{data_size},
607 my ($obj, $subloc) = @_;
612 # Found match -- seek to offset and read signature
615 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
616 read( $fh, $signature, SIG_SIZE);
619 # If value is a hash or array, return new DBM::Deep object with correct offset
621 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
622 my $new_obj = DBM::Deep->new({
624 base_offset => $subloc,
628 if ($new_obj->_root->{autobless}) {
630 # Skip over value and plain key to see if object needs
633 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
636 read( $fh, $size, $self->{data_size});
637 $size = unpack($self->{data_pack}, $size);
638 if ($size) { seek($fh, $size, SEEK_CUR); }
641 read( $fh, $bless_bit, 1);
642 if (ord($bless_bit)) {
644 # Yes, object needs to be re-blessed
647 read( $fh, $size, $self->{data_size});
648 $size = unpack($self->{data_pack}, $size);
649 if ($size) { read( $fh, $class_name, $size); }
650 if ($class_name) { $new_obj = bless( $new_obj, $class_name ); }
656 elsif ( $signature eq SIG_INTERNAL ) {
658 read( $fh, $size, $self->{data_size});
659 $size = unpack($self->{data_pack}, $size);
663 read( $fh, $new_loc, $size );
664 $new_loc = unpack( $self->{long_pack}, $new_loc );
666 return $self->read_from_loc( $obj, $new_loc );
673 # Otherwise return actual value
675 elsif ($signature eq SIG_DATA) {
677 read( $fh, $size, $self->{data_size});
678 $size = unpack($self->{data_pack}, $size);
681 if ($size) { read( $fh, $value, $size); }
686 # Key exists, but content is null
691 sub get_bucket_value {
693 # Fetch single value given tag and MD5 digested key.
696 my ($obj, $tag, $md5) = @_;
698 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
700 return $self->read_from_loc( $obj, $subloc );
707 # Delete single key/value pair given tag and MD5 digested key.
710 my ($obj, $tag, $md5) = @_;
712 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
713 #XXX This needs _release_space()
716 seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
717 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
718 print( $fh chr(0) x $self->{bucket_size} );
727 # Check existence of single key given tag and MD5 digested key.
730 my ($obj, $tag, $md5) = @_;
732 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
736 sub find_bucket_list {
738 # Locate offset for bucket list, given digested key
741 my ($obj, $md5, $args) = @_;
742 $args = {} unless $args;
745 # Locate offset for bucket list using digest index system
747 my $tag = $self->load_tag($obj, $obj->_base_offset)
748 or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
751 while ($tag->{signature} ne SIG_BLIST) {
752 my $num = ord substr($md5, $ch, 1);
754 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
755 $tag = $self->index_lookup( $obj, $tag, $num );
758 return if !$args->{create};
760 my $loc = $self->_request_space(
761 $obj, $self->tag_size( $self->{bucket_list_size} ),
765 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
766 print( $fh pack($self->{long_pack}, $loc) );
768 $tag = $self->write_tag(
769 $obj, $loc, SIG_BLIST,
770 chr(0)x$self->{bucket_list_size},
773 $tag->{ref_loc} = $ref_loc;
780 $tag->{ref_loc} = $ref_loc;
788 # Given index tag, lookup single entry in index and return .
791 my ($obj, $tag, $index) = @_;
793 my $location = unpack(
797 $index * $self->{long_size},
802 if (!$location) { return; }
804 return $self->load_tag( $obj, $location );
809 # Scan index and recursively step into deeper levels, looking for next key.
812 my ($obj, $offset, $ch, $force_return_next) = @_;
814 my $tag = $self->load_tag($obj, $offset );
818 if ($tag->{signature} ne SIG_BLIST) {
819 my $content = $tag->{content};
820 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
822 for (my $idx = $start; $idx < (2**8); $idx++) {
827 $idx * $self->{long_size},
833 my $result = $self->traverse_index(
834 $obj, $subloc, $ch + 1, $force_return_next,
837 if (defined($result)) { return $result; }
841 $obj->{return_next} = 1;
845 my $keys = $tag->{content};
846 if ($force_return_next) { $obj->{return_next} = 1; }
849 # Iterate through buckets, looking for a key match
851 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
852 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
854 # End of bucket list -- return to outer loop
856 $obj->{return_next} = 1;
859 # Located previous key -- return next one found
860 elsif ($key eq $obj->{prev_md5}) {
861 $obj->{return_next} = 1;
864 # Seek to bucket location and skip over signature
865 elsif ($obj->{return_next}) {
866 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
868 # Skip over value to get to plain key
870 read( $fh, $sig, SIG_SIZE );
873 read( $fh, $size, $self->{data_size});
874 $size = unpack($self->{data_pack}, $size);
875 if ($size) { seek($fh, $size, SEEK_CUR); }
877 # Read in plain key and return as scalar
879 read( $fh, $size, $self->{data_size});
880 $size = unpack($self->{data_pack}, $size);
881 if ($size) { read( $fh, $plain_key, $size); }
887 $obj->{return_next} = 1;
888 } # tag is a bucket list
895 # Locate next key, given digested previous one
900 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
901 $obj->{return_next} = 0;
904 # If the previous key was not specifed, start at the top and
905 # return the first one found.
907 if (!$obj->{prev_md5}) {
908 $obj->{prev_md5} = chr(0) x $self->{hash_size};
909 $obj->{return_next} = 1;
912 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
917 sub _get_key_subloc {
919 my ($keys, $idx) = @_;
921 my ($key, $subloc, $size) = unpack(
922 "a$self->{hash_size} $self->{long_pack} $self->{long_pack}",
925 ($idx * $self->{bucket_size}),
926 $self->{bucket_size},
930 return ($key, $subloc, $size);
933 sub _find_in_buckets {
935 my ($tag, $md5) = @_;
938 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
939 my ($key, $subloc, $size) = $self->_get_key_subloc(
943 return ($subloc, $i * $self->{bucket_size}, $size) unless $subloc;
945 next BUCKET if $key ne $md5;
947 return ($subloc, $i * $self->{bucket_size}, $size);
955 # my ($obj, $spot, $data) = @_;
957 # my $fh = $obj->_fh;
958 # seek( $fh, $spot, SEEK_SET );
959 # print( $fh $data );
966 my ($obj, $size) = @_;
968 my $loc = $obj->_root->{end};
969 $obj->_root->{end} += $size;
976 my ($obj, $size, $loc) = @_;
981 seek( $fh, $loc + $obj->_root->{file_offset}, SEEK_SET );
983 . pack($self->{long_pack}, $size )
984 . pack($self->{long_pack}, $next_loc )
993 # This will be added in later, after more refactoring is done. This is an early
994 # attempt at refactoring on the physical level instead of the virtual level.
997 my ($obj, $spot, $amount, $unpack) = @_;
1000 seek( $fh, $spot + $obj->_root->{file_offset}, SEEK_SET );
1003 my $bytes_read = read( $fh, $buffer, $amount );
1006 $buffer = unpack( $unpack, $buffer );
1010 return ($buffer, $bytes_read);