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' }
23 # Precalculate index, bucket and bucket list sizes
27 $self->{index_size} = (2**8) * $self->{long_size};
28 $self->{bucket_size} = $self->{hash_size} + $self->{long_size} * 2;
29 $self->{bucket_list_size} = $self->{max_buckets} * $self->{bucket_size};
36 # Set pack/unpack modes (see file header for more)
39 my ($long_s, $long_p, $data_s, $data_p) = @_;
42 # Set to 4 and 'N' for 32-bit offset tags (default). Theoretical limit of 4
44 # (Perl must be compiled with largefile support for files > 2 GB)
46 # Set to 8 and 'Q' for 64-bit offsets. Theoretical limit of 16 XB per file.
47 # (Perl must be compiled with largefile and 64-bit long support)
49 $self->{long_size} = $long_s ? $long_s : 4;
50 $self->{long_pack} = $long_p ? $long_p : 'N';
53 # Set to 4 and 'N' for 32-bit data length prefixes. Limit of 4 GB for each
54 # key/value. Upgrading this is possible (see above) but probably not
55 # necessary. If you need more than 4 GB for a single key or value, this
56 # module is really not for you :-)
58 $self->{data_size} = $data_s ? $data_s : 4;
59 $self->{data_pack} = $data_p ? $data_p : 'N';
61 return $self->precalc_sizes();
66 # Set key digest function (default is MD5)
69 my ($digest_func, $hash_size) = @_;
71 $self->{digest} = $digest_func ? $digest_func : \&Digest::MD5::md5;
72 $self->{hash_size} = $hash_size ? $hash_size : 16;
74 return $self->precalc_sizes();
87 digest => \&Digest::MD5::md5,
91 # Maximum number of buckets per list before another level of indexing is
93 # Increase this value for slightly greater speed, but larger database
94 # files. DO NOT decrease this value below 16, due to risk of recursive
100 # Grab the parameters we want to use
101 foreach my $param ( keys %$self ) {
102 next unless exists $args->{$param};
103 $self->{$param} = $args->{$param};
106 $self->precalc_sizes;
111 sub write_file_header {
117 my $loc = $self->_request_space(
118 $obj, length( SIG_FILE ) + $self->{data_size},
120 seek($fh, $loc + $obj->_root->{file_offset}, SEEK_SET);
121 print( $fh SIG_FILE, pack('N', 0) );
126 sub read_file_header {
132 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
134 my $bytes_read = read(
135 $fh, $buffer, length(SIG_FILE) + $self->{data_size},
139 my ($signature, $version) = unpack( 'A4 N', $buffer );
140 unless ($signature eq SIG_FILE) {
141 $self->close_fh( $obj );
142 $obj->_throw_error("Signature not found -- file is not a Deep DB");
153 $self->open( $obj ) if !defined $obj->_fh;
158 unless ( $obj->{base_offset} ) {
159 my $bytes_read = $self->read_file_header( $obj );
162 # File is empty -- write header and master index
165 $self->write_file_header( $obj );
167 $obj->{base_offset} = $self->_request_space(
168 $obj, $self->tag_size( $self->{index_size} ),
172 $obj, $obj->_base_offset, $obj->_type,
173 chr(0)x$self->{index_size},
176 # Flush the filehandle
177 my $old_fh = select $fh;
178 my $old_af = $|; $| = 1; $| = $old_af;
182 $obj->{base_offset} = $bytes_read;
185 # Get our type from master index header
187 my $tag = $self->load_tag($obj, $obj->_base_offset)
188 or $obj->_throw_error("Corrupted file, no master index record");
190 unless ($obj->{type} eq $tag->{signature}) {
191 $obj->_throw_error("File type mismatch");
196 #XXX We have to make sure we don't mess up when autoflush isn't turned on
197 unless ( $obj->_root->{inode} ) {
198 my @stats = stat($obj->_fh);
199 $obj->_root->{inode} = $stats[1];
200 $obj->_root->{end} = $stats[7];
210 # Open a fh to the database, create if nonexistent.
211 # Make sure file signature matches DBM::Deep spec.
216 # Theoretically, adding O_BINARY should remove the need for the binmode
217 # Of course, testing it is going to be ... interesting.
218 my $flags = O_RDWR | O_CREAT | O_BINARY;
221 my $filename = $obj->_root->{file};
222 sysopen( $fh, $filename, $flags )
223 or $obj->_throw_error("Cannot sysopen file '$filename': $!");
224 $obj->_root->{fh} = $fh;
226 # Even though we use O_BINARY, better be safe than sorry.
229 if ($obj->_root->{autoflush}) {
230 my $old = select $fh;
242 if ( my $fh = $obj->_root->{fh} ) {
245 $obj->_root->{fh} = undef;
253 return SIG_SIZE + $self->{data_size} + $size;
258 # Given offset, signature and content, create tag and write to disk
261 my ($obj, $offset, $sig, $content) = @_;
262 my $size = length( $content );
266 if ( defined $offset ) {
267 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
270 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
272 return unless defined $offset;
277 offset => $offset + SIG_SIZE + $self->{data_size},
284 # Given offset, load single tag and return signature, size and data
287 my ($obj, $offset) = @_;
289 # print join(':',map{$_||''}caller(1)), $/;
293 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
295 #XXX I'm not sure this check will work if autoflush isn't enabled ...
299 read( $fh, $b, SIG_SIZE + $self->{data_size} );
300 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
303 read( $fh, $buffer, $size);
308 offset => $offset + SIG_SIZE + $self->{data_size},
313 sub _get_dbm_object {
318 if ($item->isa( 'DBM::Deep' )) {
325 my $r = Scalar::Util::reftype( $item ) || '';
326 if ( $r eq 'HASH' ) {
329 my $obj = tied(%$item);
330 if ($obj->isa( 'DBM::Deep' )) {
337 elsif ( $r eq 'ARRAY' ) {
340 my $obj = tied(@$item);
341 if ($obj->isa( 'DBM::Deep' )) {
354 my ($obj, $value, $key) = @_;
356 my $is_dbm_deep = eval {
357 local $SIG{'__DIE__'};
358 $value->isa( 'DBM::Deep' );
361 my $len = SIG_SIZE + $self->{data_size}
362 + $self->{data_size} + length( $key );
364 if ( $is_dbm_deep && $value->_root eq $obj->_root ) {
365 return $len + $self->{long_size};
368 my $r = Scalar::Util::reftype( $value ) || '';
369 if ( $obj->_root->{autobless} ) {
370 # This is for the bit saying whether or not this thing is blessed.
374 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
375 if ( defined $value ) {
376 $len += length( $value );
381 $len += $self->{index_size};
383 # if autobless is enabled, must also take into consideration
384 # the class name as it is stored after the key.
385 if ( $obj->_root->{autobless} ) {
386 my $c = Scalar::Util::blessed($value);
387 if ( defined $c && !$is_dbm_deep ) {
388 $len += $self->{data_size} + length($c);
397 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
398 # plain (undigested) key and value.
401 my ($obj, $tag, $md5, $plain_key, $value) = @_;
403 # This verifies that only supported values will be stored.
405 my $r = Scalar::Util::reftype( $value );
408 last if $r eq 'HASH';
409 last if $r eq 'ARRAY';
412 "Storage of variables of type '$r' is not supported."
419 my $root = $obj->_root;
422 my $actual_length = $self->_length_needed( $obj, $value, $plain_key );
424 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
426 # $self->_release_space( $obj, $size, $subloc );
427 # Updating a known md5
428 #XXX This needs updating to use _release_space
432 if ($actual_length <= $size) {
436 $location = $self->_request_space( $obj, $actual_length );
439 $tag->{offset} + $offset
440 + $self->{hash_size} + $root->{file_offset},
443 print( $fh pack($self->{long_pack}, $location ) );
444 print( $fh pack($self->{long_pack}, $actual_length ) );
448 elsif ( defined $offset ) {
449 $location = $self->_request_space( $obj, $actual_length );
451 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
452 print( $fh $md5 . pack($self->{long_pack}, $location ) );
453 print( $fh pack($self->{long_pack}, $actual_length ) );
455 # If bucket didn't fit into list, split into a new index level
456 # split_index() will do the _request_space() call
458 $location = $self->split_index( $obj, $md5, $tag );
461 $self->write_value( $obj, $location, $plain_key, $value );
468 my ($obj, $location, $key, $value) = @_;
471 my $root = $obj->_root;
473 my $dbm_deep_obj = _get_dbm_object( $value );
474 if ( $dbm_deep_obj && $dbm_deep_obj->_root ne $obj->_root ) {
475 $obj->_throw_error( "Cannot cross-reference. Use export() instead" );
478 seek($fh, $location + $root->{file_offset}, SEEK_SET);
481 # Write signature based on content type, set content length and write
484 my $r = Scalar::Util::reftype( $value ) || '';
485 if ( $dbm_deep_obj ) {
486 $self->write_tag( $obj, undef, SIG_INTERNAL,pack($self->{long_pack}, $dbm_deep_obj->_base_offset) );
488 elsif ($r eq 'HASH') {
489 if ( !$dbm_deep_obj && tied %{$value} ) {
490 $obj->_throw_error( "Cannot store something that is tied" );
492 $self->write_tag( $obj, undef, SIG_HASH, chr(0)x$self->{index_size} );
494 elsif ($r eq 'ARRAY') {
495 if ( !$dbm_deep_obj && tied @{$value} ) {
496 $obj->_throw_error( "Cannot store something that is tied" );
498 $self->write_tag( $obj, undef, SIG_ARRAY, chr(0)x$self->{index_size} );
500 elsif (!defined($value)) {
501 $self->write_tag( $obj, undef, SIG_NULL, '' );
504 $self->write_tag( $obj, undef, SIG_DATA, $value );
508 # Plain key is stored AFTER value, as keys are typically fetched less often.
510 print( $fh pack($self->{data_pack}, length($key)) . $key );
512 # Internal references don't care about autobless
513 return 1 if $dbm_deep_obj;
516 # If value is blessed, preserve class name
518 if ( $root->{autobless} ) {
519 my $c = Scalar::Util::blessed($value);
520 if ( defined $c && !$dbm_deep_obj ) {
522 print( $fh pack($self->{data_pack}, length($c)) . $c );
530 # Tie the passed in reference so that changes to it are reflected in the
531 # datafile. The use of $location as the base_offset will act as the
532 # the linkage between parent and child.
534 # The overall assignment is a hack around the fact that just tying doesn't
535 # store the values. This may not be the wrong thing to do.
539 tie %$value, 'DBM::Deep', {
540 base_offset => $location,
545 elsif ($r eq 'ARRAY') {
547 tie @$value, 'DBM::Deep', {
548 base_offset => $location,
559 my ($obj, $md5, $tag) = @_;
562 my $root = $obj->_root;
564 my $loc = $self->_request_space(
565 $obj, $self->tag_size( $self->{index_size} ),
568 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
569 print( $fh pack($self->{long_pack}, $loc) );
571 my $index_tag = $self->write_tag(
572 $obj, $loc, SIG_INDEX,
573 chr(0)x$self->{index_size},
576 my $newtag_loc = $self->_request_space(
577 $obj, $self->tag_size( $self->{bucket_list_size} ),
580 my $keys = $tag->{content}
581 . $md5 . pack($self->{long_pack}, $newtag_loc)
582 . pack($self->{long_pack}, 0);
586 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
587 my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
589 die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
590 die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
592 my $num = ord(substr($key, $tag->{ch} + 1, 1));
595 seek($fh, $newloc[$num] + $root->{file_offset}, SEEK_SET);
597 read( $fh, $subkeys, $self->{bucket_list_size});
599 # This is looking for the first empty spot
600 my ($subloc, $offset, $size) = $self->_find_in_buckets(
601 { content => $subkeys }, '',
604 seek($fh, $newloc[$num] + $offset + $root->{file_offset}, SEEK_SET);
605 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
610 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
612 my $loc = $self->_request_space(
613 $obj, $self->tag_size( $self->{bucket_list_size} ),
616 print( $fh pack($self->{long_pack}, $loc) );
618 my $blist_tag = $self->write_tag(
619 $obj, $loc, SIG_BLIST,
620 chr(0)x$self->{bucket_list_size},
623 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
624 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
626 $newloc[$num] = $blist_tag->{offset};
629 $self->_release_space(
630 $obj, $self->tag_size( $self->{bucket_list_size} ),
631 $tag->{offset} - SIG_SIZE - $self->{data_size},
639 my ($obj, $subloc) = @_;
644 # Found match -- seek to offset and read signature
647 seek($fh, $subloc + $obj->_root->{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,
660 if ($new_obj->_root->{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( $obj, $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 ($obj, $tag, $md5) = @_;
730 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
732 return $self->read_from_loc( $obj, $subloc );
739 # Delete single key/value pair given tag and MD5 digested key.
742 my ($obj, $tag, $md5) = @_;
744 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
745 #XXX This needs _release_space()
748 seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
749 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
750 print( $fh chr(0) x $self->{bucket_size} );
759 # Check existence of single key given tag and MD5 digested key.
762 my ($obj, $tag, $md5) = @_;
764 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
768 sub find_bucket_list {
770 # Locate offset for bucket list, given digested key
773 my ($obj, $md5, $args) = @_;
774 $args = {} unless $args;
777 # Locate offset for bucket list using digest index system
779 my $tag = $self->load_tag($obj, $obj->_base_offset)
780 or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
783 while ($tag->{signature} ne SIG_BLIST) {
784 my $num = ord substr($md5, $ch, 1);
786 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
787 $tag = $self->index_lookup( $obj, $tag, $num );
790 return if !$args->{create};
792 my $loc = $self->_request_space(
793 $obj, $self->tag_size( $self->{bucket_list_size} ),
797 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
798 print( $fh pack($self->{long_pack}, $loc) );
800 $tag = $self->write_tag(
801 $obj, $loc, SIG_BLIST,
802 chr(0)x$self->{bucket_list_size},
805 $tag->{ref_loc} = $ref_loc;
812 $tag->{ref_loc} = $ref_loc;
820 # Given index tag, lookup single entry in index and return .
823 my ($obj, $tag, $index) = @_;
825 my $location = unpack(
829 $index * $self->{long_size},
834 if (!$location) { return; }
836 return $self->load_tag( $obj, $location );
841 # Scan index and recursively step into deeper levels, looking for next key.
844 my ($obj, $offset, $ch, $force_return_next) = @_;
846 my $tag = $self->load_tag($obj, $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 + $obj->_root->{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) = unpack(
954 "a$self->{hash_size} $self->{long_pack} $self->{long_pack}",
957 ($idx * $self->{bucket_size}),
958 $self->{bucket_size},
962 return ($key, $subloc, $size);
965 sub _find_in_buckets {
967 my ($tag, $md5) = @_;
970 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
971 my ($key, $subloc, $size) = $self->_get_key_subloc(
975 return ($subloc, $i * $self->{bucket_size}, $size) unless $subloc;
977 next BUCKET if $key ne $md5;
979 return ($subloc, $i * $self->{bucket_size}, $size);
987 # my ($obj, $spot, $data) = @_;
989 # my $fh = $obj->_fh;
990 # seek( $fh, $spot, SEEK_SET );
991 # print( $fh $data );
998 my ($obj, $size) = @_;
1000 my $loc = $obj->_root->{end};
1001 $obj->_root->{end} += $size;
1006 sub _release_space {
1008 my ($obj, $size, $loc) = @_;
1013 seek( $fh, $loc + $obj->_root->{file_offset}, SEEK_SET );
1015 . pack($self->{long_pack}, $size )
1016 . pack($self->{long_pack}, $next_loc )
1025 # This will be added in later, after more refactoring is done. This is an early
1026 # attempt at refactoring on the physical level instead of the virtual level.
1029 my ($obj, $spot, $amount, $unpack) = @_;
1032 seek( $fh, $spot + $obj->_root->{file_offset}, SEEK_SET );
1035 my $bytes_read = read( $fh, $buffer, $amount );
1038 $buffer = unpack( $unpack, $buffer );
1042 return ($buffer, $bytes_read);