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 $self->precalc_sizes;
109 $self->open( $obj ) if !defined $obj->_fh;
116 unless ( $obj->{base_offset} ) {
117 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
119 my $bytes_read = read( $fh, $signature, length(SIG_FILE));
122 # File is empty -- write signature and master index
125 my $loc = $self->_request_space( $obj, length( SIG_FILE ) );
126 seek($fh, $loc + $obj->_root->{file_offset}, SEEK_SET);
127 print( $fh SIG_FILE);
129 $obj->{base_offset} = $self->_request_space(
130 $obj, $self->tag_size( $self->{index_size} ),
134 $obj, $obj->_base_offset, $obj->_type,
135 chr(0)x$self->{index_size},
138 # Flush the filehandle
139 my $old_fh = select $fh;
140 my $old_af = $|; $| = 1; $| = $old_af;
144 $obj->{base_offset} = $bytes_read;
147 # Check signature was valid
149 unless ($signature eq SIG_FILE) {
150 $self->close_fh( $obj );
151 $obj->_throw_error("Signature not found -- file is not a Deep DB");
155 # Get our type from master index signature
157 my $tag = $self->load_tag($obj, $obj->_base_offset)
158 or $obj->_throw_error("Corrupted file, no master index record");
160 unless ($obj->{type} eq $tag->{signature}) {
161 $obj->_throw_error("File type mismatch");
166 #XXX We have to make sure we don't mess up when autoflush isn't turned on
167 unless ( $obj->_root->{inode} ) {
168 my @stats = stat($obj->_fh);
169 $obj->_root->{inode} = $stats[1];
170 $obj->_root->{end} = $stats[7];
180 # Open a fh to the database, create if nonexistent.
181 # Make sure file signature matches DBM::Deep spec.
186 # Theoretically, adding O_BINARY should remove the need for the binmode
187 # Of course, testing it is going to be ... interesting.
188 my $flags = O_RDWR | O_CREAT | O_BINARY;
191 my $filename = $obj->_root->{file};
192 sysopen( $fh, $filename, $flags )
193 or $obj->_throw_error("Cannot sysopen file '$filename': $!");
194 $obj->_root->{fh} = $fh;
196 #XXX Can we remove this by using the right sysopen() flags?
197 # Maybe ... q.v. above
198 binmode $fh; # for win32
200 if ($obj->_root->{autoflush}) {
201 my $old = select $fh;
213 if ( my $fh = $obj->_root->{fh} ) {
216 $obj->_root->{fh} = undef;
224 return SIG_SIZE + $self->{data_size} + $size;
229 # Given offset, signature and content, create tag and write to disk
232 my ($obj, $offset, $sig, $content) = @_;
233 my $size = length( $content );
237 if ( defined $offset ) {
238 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
241 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
243 return unless defined $offset;
248 offset => $offset + SIG_SIZE + $self->{data_size},
255 # Given offset, load single tag and return signature, size and data
258 my ($obj, $offset) = @_;
260 # print join(':',map{$_||''}caller(1)), $/;
264 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
266 #XXX I'm not sure this check will work if autoflush isn't enabled ...
270 read( $fh, $b, SIG_SIZE + $self->{data_size} );
271 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
274 read( $fh, $buffer, $size);
279 offset => $offset + SIG_SIZE + $self->{data_size},
286 my ($obj, $value, $key) = @_;
288 my $is_dbm_deep = eval {
289 local $SIG{'__DIE__'};
290 $value->isa( 'DBM::Deep' );
293 my $len = SIG_SIZE + $self->{data_size}
294 + $self->{data_size} + length( $key );
296 if ( $is_dbm_deep && $value->_root eq $obj->_root ) {
297 return $len + $self->{long_size};
300 my $r = Scalar::Util::reftype( $value ) || '';
301 if ( $obj->_root->{autobless} ) {
302 # This is for the bit saying whether or not this thing is blessed.
306 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
307 if ( defined $value ) {
308 $len += length( $value );
313 $len += $self->{index_size};
315 # if autobless is enabled, must also take into consideration
316 # the class name as it is stored after the key.
317 if ( $obj->_root->{autobless} ) {
318 my $value_class = Scalar::Util::blessed($value);
319 if ( defined $value_class && !$is_dbm_deep ) {
320 $len += $self->{data_size} + length($value_class);
329 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
330 # plain (undigested) key and value.
333 my ($obj, $tag, $md5, $plain_key, $value) = @_;
335 # This verifies that only supported values will be stored.
337 my $r = Scalar::Util::reftype( $value );
340 last if $r eq 'HASH';
341 last if $r eq 'ARRAY';
344 "Storage of variables of type '$r' is not supported."
351 my $root = $obj->_root;
354 my $actual_length = $self->_length_needed( $obj, $value, $plain_key );
356 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
358 # $self->_release_space( $obj, $size, $subloc );
359 # Updating a known md5
360 #XXX This needs updating to use _release_space
364 if ($actual_length <= $size) {
368 $location = $self->_request_space( $obj, $actual_length );
371 $tag->{offset} + $offset
372 + $self->{hash_size} + $root->{file_offset},
375 print( $fh pack($self->{long_pack}, $location ) );
376 print( $fh pack($self->{long_pack}, $actual_length ) );
380 elsif ( defined $offset ) {
381 $location = $self->_request_space( $obj, $actual_length );
383 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
384 print( $fh $md5 . pack($self->{long_pack}, $location ) );
385 print( $fh pack($self->{long_pack}, $actual_length ) );
387 # If bucket didn't fit into list, split into a new index level
388 # split_index() will do the _request_space() call
390 $location = $self->split_index( $obj, $md5, $tag );
393 $self->write_value( $obj, $location, $plain_key, $value );
400 my ($obj, $location, $key, $value) = @_;
403 my $root = $obj->_root;
405 my $is_dbm_deep = eval {
406 local $SIG{'__DIE__'};
407 $value->isa( 'DBM::Deep' );
410 my $is_internal_ref = $is_dbm_deep && ($value->_root eq $root);
412 seek($fh, $location + $root->{file_offset}, SEEK_SET);
415 # Write signature based on content type, set content length and write
418 my $r = Scalar::Util::reftype($value) || '';
419 if ( $is_internal_ref ) {
420 $self->write_tag( $obj, undef, SIG_INTERNAL,pack($self->{long_pack}, $value->_base_offset) );
422 elsif ($r eq 'HASH') {
423 $self->write_tag( $obj, undef, SIG_HASH, chr(0)x$self->{index_size} );
425 elsif ($r eq 'ARRAY') {
426 $self->write_tag( $obj, undef, SIG_ARRAY, chr(0)x$self->{index_size} );
428 elsif (!defined($value)) {
429 $self->write_tag( $obj, undef, SIG_NULL, '' );
432 $self->write_tag( $obj, undef, SIG_DATA, $value );
436 # Plain key is stored AFTER value, as keys are typically fetched less often.
438 print( $fh pack($self->{data_pack}, length($key)) . $key );
440 # Internal references don't care about autobless
441 return 1 if $is_internal_ref;
444 # If value is blessed, preserve class name
446 if ( $root->{autobless} ) {
447 my $value_class = Scalar::Util::blessed($value);
448 if ( defined $value_class && !$is_dbm_deep ) {
450 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
458 # If content is a hash or array, create new child DBM::Deep object and
459 # pass each key or element to it.
461 if ( !$is_internal_ref ) {
463 my $branch = DBM::Deep->new(
464 type => DBM::Deep->TYPE_HASH,
465 base_offset => $location,
468 foreach my $key (keys %{$value}) {
469 $branch->STORE( $key, $value->{$key} );
472 elsif ($r eq 'ARRAY') {
473 my $branch = DBM::Deep->new(
474 type => DBM::Deep->TYPE_ARRAY,
475 base_offset => $location,
479 foreach my $element (@{$value}) {
480 $branch->STORE( $index, $element );
491 my ($obj, $md5, $tag) = @_;
494 my $root = $obj->_root;
496 my $loc = $self->_request_space(
497 $obj, $self->tag_size( $self->{index_size} ),
500 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
501 print( $fh pack($self->{long_pack}, $loc) );
503 my $index_tag = $self->write_tag(
504 $obj, $loc, SIG_INDEX,
505 chr(0)x$self->{index_size},
508 my $newtag_loc = $self->_request_space(
509 $obj, $self->tag_size( $self->{bucket_list_size} ),
512 my $keys = $tag->{content}
513 . $md5 . pack($self->{long_pack}, $newtag_loc)
514 . pack($self->{long_pack}, 0);
518 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
519 my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
521 die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
522 die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
524 my $num = ord(substr($key, $tag->{ch} + 1, 1));
527 seek($fh, $newloc[$num] + $root->{file_offset}, SEEK_SET);
529 read( $fh, $subkeys, $self->{bucket_list_size});
531 # This is looking for the first empty spot
532 my ($subloc, $offset, $size) = $self->_find_in_buckets(
533 { content => $subkeys }, '',
536 seek($fh, $newloc[$num] + $offset + $root->{file_offset}, SEEK_SET);
537 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
542 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
544 my $loc = $self->_request_space(
545 $obj, $self->tag_size( $self->{bucket_list_size} ),
548 print( $fh pack($self->{long_pack}, $loc) );
550 my $blist_tag = $self->write_tag(
551 $obj, $loc, SIG_BLIST,
552 chr(0)x$self->{bucket_list_size},
555 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
556 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
558 $newloc[$num] = $blist_tag->{offset};
561 $self->_release_space(
562 $obj, $self->tag_size( $self->{bucket_list_size} ),
563 $tag->{offset} - SIG_SIZE - $self->{data_size},
571 my ($obj, $subloc) = @_;
576 # Found match -- seek to offset and read signature
579 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
580 read( $fh, $signature, SIG_SIZE);
583 # If value is a hash or array, return new DBM::Deep object with correct offset
585 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
586 my $obj = DBM::Deep->new(
588 base_offset => $subloc,
592 if ($obj->_root->{autobless}) {
594 # Skip over value and plain key to see if object needs
597 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
600 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
601 if ($size) { seek($fh, $size, SEEK_CUR); }
604 read( $fh, $bless_bit, 1);
605 if (ord($bless_bit)) {
607 # Yes, object needs to be re-blessed
610 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
611 if ($size) { read( $fh, $class_name, $size); }
612 if ($class_name) { $obj = bless( $obj, $class_name ); }
618 elsif ( $signature eq SIG_INTERNAL ) {
620 read( $fh, $size, $self->{data_size});
621 $size = unpack($self->{data_pack}, $size);
625 read( $fh, $new_loc, $size );
626 $new_loc = unpack( $self->{long_pack}, $new_loc );
628 return $self->read_from_loc( $obj, $new_loc );
635 # Otherwise return actual value
637 elsif ($signature eq SIG_DATA) {
639 read( $fh, $size, $self->{data_size});
640 $size = unpack($self->{data_pack}, $size);
643 if ($size) { read( $fh, $value, $size); }
648 # Key exists, but content is null
653 sub get_bucket_value {
655 # Fetch single value given tag and MD5 digested key.
658 my ($obj, $tag, $md5) = @_;
660 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
662 return $self->read_from_loc( $obj, $subloc );
669 # Delete single key/value pair given tag and MD5 digested key.
672 my ($obj, $tag, $md5) = @_;
674 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
675 #XXX This needs _release_space()
678 seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
679 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
680 print( $fh chr(0) x $self->{bucket_size} );
689 # Check existence of single key given tag and MD5 digested key.
692 my ($obj, $tag, $md5) = @_;
694 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
698 sub find_bucket_list {
700 # Locate offset for bucket list, given digested key
703 my ($obj, $md5, $args) = @_;
704 $args = {} unless $args;
707 # Locate offset for bucket list using digest index system
709 my $tag = $self->load_tag($obj, $obj->_base_offset)
710 or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
713 while ($tag->{signature} ne SIG_BLIST) {
714 my $num = ord substr($md5, $ch, 1);
716 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
717 $tag = $self->index_lookup( $obj, $tag, $num );
720 return if !$args->{create};
722 my $loc = $self->_request_space(
723 $obj, $self->tag_size( $self->{bucket_list_size} ),
727 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
728 print( $fh pack($self->{long_pack}, $loc) );
730 $tag = $self->write_tag(
731 $obj, $loc, SIG_BLIST,
732 chr(0)x$self->{bucket_list_size},
735 $tag->{ref_loc} = $ref_loc;
742 $tag->{ref_loc} = $ref_loc;
750 # Given index tag, lookup single entry in index and return .
753 my ($obj, $tag, $index) = @_;
755 my $location = unpack(
759 $index * $self->{long_size},
764 if (!$location) { return; }
766 return $self->load_tag( $obj, $location );
771 # Scan index and recursively step into deeper levels, looking for next key.
774 my ($obj, $offset, $ch, $force_return_next) = @_;
776 my $tag = $self->load_tag($obj, $offset );
780 if ($tag->{signature} ne SIG_BLIST) {
781 my $content = $tag->{content};
782 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
784 for (my $idx = $start; $idx < (2**8); $idx++) {
789 $idx * $self->{long_size},
795 my $result = $self->traverse_index(
796 $obj, $subloc, $ch + 1, $force_return_next,
799 if (defined($result)) { return $result; }
803 $obj->{return_next} = 1;
807 my $keys = $tag->{content};
808 if ($force_return_next) { $obj->{return_next} = 1; }
811 # Iterate through buckets, looking for a key match
813 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
814 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
816 # End of bucket list -- return to outer loop
818 $obj->{return_next} = 1;
821 # Located previous key -- return next one found
822 elsif ($key eq $obj->{prev_md5}) {
823 $obj->{return_next} = 1;
826 # Seek to bucket location and skip over signature
827 elsif ($obj->{return_next}) {
828 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
830 # Skip over value to get to plain key
832 read( $fh, $sig, SIG_SIZE );
835 read( $fh, $size, $self->{data_size});
836 $size = unpack($self->{data_pack}, $size);
837 if ($size) { seek($fh, $size, SEEK_CUR); }
839 # Read in plain key and return as scalar
841 read( $fh, $size, $self->{data_size});
842 $size = unpack($self->{data_pack}, $size);
843 if ($size) { read( $fh, $plain_key, $size); }
849 $obj->{return_next} = 1;
850 } # tag is a bucket list
857 # Locate next key, given digested previous one
862 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
863 $obj->{return_next} = 0;
866 # If the previous key was not specifed, start at the top and
867 # return the first one found.
869 if (!$obj->{prev_md5}) {
870 $obj->{prev_md5} = chr(0) x $self->{hash_size};
871 $obj->{return_next} = 1;
874 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
879 sub _get_key_subloc {
881 my ($keys, $idx) = @_;
883 my ($key, $subloc, $size) = unpack(
884 "a$self->{hash_size} $self->{long_pack} $self->{long_pack}",
887 ($idx * $self->{bucket_size}),
888 $self->{bucket_size},
892 return ($key, $subloc, $size);
895 sub _find_in_buckets {
897 my ($tag, $md5) = @_;
900 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
901 my ($key, $subloc, $size) = $self->_get_key_subloc(
905 return ($subloc, $i * $self->{bucket_size}, $size) unless $subloc;
907 next BUCKET if $key ne $md5;
909 return ($subloc, $i * $self->{bucket_size}, $size);
917 # my ($obj, $spot, $data) = @_;
919 # my $fh = $obj->_fh;
920 # seek( $fh, $spot, SEEK_SET );
921 # print( $fh $data );
928 my ($obj, $size) = @_;
930 my $loc = $obj->_root->{end};
931 $obj->_root->{end} += $size;
938 my ($obj, $size, $loc) = @_;
943 seek( $fh, $loc + $obj->_root->{file_offset}, SEEK_SET );
945 . pack($self->{long_pack}, $size )
946 . pack($self->{long_pack}, $next_loc )
955 # This will be added in later, after more refactoring is done. This is an early
956 # attempt at refactoring on the physical level instead of the virtual level.
959 my ($obj, $spot, $amount, $unpack) = @_;
962 seek( $fh, $spot + $obj->_root->{file_offset}, SEEK_SET );
965 my $bytes_read = read( $fh, $buffer, $amount );
968 $buffer = unpack( $unpack, $buffer );
972 return ($buffer, $bytes_read);