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' }
22 # Precalculate index, bucket and bucket list sizes
26 $self->{index_size} = (2**8) * $self->{long_size};
27 $self->{bucket_size} = $self->{hash_size} + $self->{long_size};
28 $self->{bucket_list_size} = $self->{max_buckets} * $self->{bucket_size};
35 # Set pack/unpack modes (see file header for more)
38 my ($long_s, $long_p, $data_s, $data_p) = @_;
41 # Set to 4 and 'N' for 32-bit offset tags (default). Theoretical limit of 4
43 # (Perl must be compiled with largefile support for files > 2 GB)
45 # Set to 8 and 'Q' for 64-bit offsets. Theoretical limit of 16 XB per file.
46 # (Perl must be compiled with largefile and 64-bit long support)
48 $self->{long_size} = $long_s ? $long_s : 4;
49 $self->{long_pack} = $long_p ? $long_p : 'N';
52 # Set to 4 and 'N' for 32-bit data length prefixes. Limit of 4 GB for each
53 # key/value. Upgrading this is possible (see above) but probably not
54 # necessary. If you need more than 4 GB for a single key or value, this
55 # module is really not for you :-)
57 $self->{data_size} = $data_s ? $data_s : 4;
58 $self->{data_pack} = $data_p ? $data_p : 'N';
60 return $self->precalc_sizes();
65 # Set key digest function (default is MD5)
68 my ($digest_func, $hash_size) = @_;
70 $self->{digest} = $digest_func ? $digest_func : \&Digest::MD5::md5;
71 $self->{hash_size} = $hash_size ? $hash_size : 16;
73 return $self->precalc_sizes();
86 digest => \&Digest::MD5::md5,
90 # Maximum number of buckets per list before another level of indexing is
92 # Increase this value for slightly greater speed, but larger database
93 # files. DO NOT decrease this value below 16, due to risk of recursive
108 $self->open( $obj ) if !defined $obj->_fh;
113 unless ( $obj->{base_offset} ) {
114 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
116 my $bytes_read = read( $fh, $signature, length(SIG_FILE));
119 # File is empty -- write signature and master index
122 my $loc = $self->_request_space( $obj, length( SIG_FILE ) );
123 seek($fh, $loc + $obj->_root->{file_offset}, SEEK_SET);
124 print( $fh SIG_FILE);
126 $obj->{base_offset} = $self->_request_space(
127 $obj, $self->{index_size},
131 $obj, $obj->_base_offset, $obj->_type,
132 chr(0) x $self->{index_size},
135 # Flush the filehandle
136 my $old_fh = select $fh;
137 my $old_af = $|; $| = 1; $| = $old_af;
141 $obj->{base_offset} = $bytes_read;
144 # Check signature was valid
146 unless ($signature eq SIG_FILE) {
147 $self->close_fh( $obj );
148 $obj->_throw_error("Signature not found -- file is not a Deep DB");
152 # Get our type from master index signature
154 my $tag = $self->load_tag($obj, $obj->_base_offset)
155 or $obj->_throw_error("Corrupted file, no master index record");
157 unless ($obj->{type} eq $tag->{signature}) {
158 $obj->_throw_error("File type mismatch");
163 #XXX We have to make sure we don't mess up when autoflush isn't turned on
164 unless ( $obj->_root->{inode} ) {
165 my @stats = stat($obj->_fh);
166 $obj->_root->{inode} = $stats[1];
167 $obj->_root->{end} = $stats[7];
177 # Open a fh to the database, create if nonexistent.
178 # Make sure file signature matches DBM::Deep spec.
183 # Theoretically, adding O_BINARY should remove the need for the binmode
184 # Of course, testing it is going to be ... interesting.
185 my $flags = O_RDWR | O_CREAT | O_BINARY;
188 my $filename = $obj->_root->{file};
189 sysopen( $fh, $filename, $flags )
190 or $obj->_throw_error("Cannot sysopen file '$filename': $!");
191 $obj->_root->{fh} = $fh;
193 #XXX Can we remove this by using the right sysopen() flags?
194 # Maybe ... q.v. above
195 binmode $fh; # for win32
197 if ($obj->_root->{autoflush}) {
198 my $old = select $fh;
210 if ( my $fh = $obj->_root->{fh} ) {
213 $obj->_root->{fh} = undef;
220 # Given offset, signature and content, create tag and write to disk
223 my ($obj, $offset, $sig, $content) = @_;
224 my $size = length($content);
228 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
229 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
231 if ($offset == $obj->_root->{end}) {
232 $obj->_root->{end} += SIG_SIZE + $self->{data_size} + $size;
238 offset => $offset + SIG_SIZE + $self->{data_size},
245 # Given offset, load single tag and return signature, size and data
248 my ($obj, $offset) = @_;
250 # print join(':',map{$_||''}caller(1)), $/;
254 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
256 #XXX I'm not sure this check will work if autoflush isn't enabled ...
260 read( $fh, $b, SIG_SIZE + $self->{data_size} );
261 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
264 read( $fh, $buffer, $size);
269 offset => $offset + SIG_SIZE + $self->{data_size},
276 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
277 # plain (undigested) key and value.
280 my ($obj, $tag, $md5, $plain_key, $value) = @_;
282 # This verifies that only supported values will be stored.
284 my $r = Scalar::Util::reftype( $value );
287 last if $r eq 'HASH';
288 last if $r eq 'ARRAY';
291 "Storage of variables of type '$r' is not supported."
298 my $root = $obj->_root;
300 my $is_dbm_deep = eval {
301 local $SIG{'__DIE__'};
302 $value->isa( 'DBM::Deep' );
305 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
309 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
311 # Updating a known md5
316 # If value is a hash, array, or raw value with equal or less size, we
317 # can reuse the same content area of the database. Otherwise, we have
318 # to create a new content area at the EOF.
321 if ( $internal_ref ) {
322 $actual_length = $self->{long_size};
325 my $r = Scalar::Util::reftype( $value ) || '';
326 if ( $r eq 'HASH' || $r eq 'ARRAY' ) {
327 $actual_length = $self->{index_size};
329 # if autobless is enabled, must also take into consideration
330 # the class name, as it is stored along with key/value.
331 if ( $root->{autobless} ) {
332 my $value_class = Scalar::Util::blessed($value);
333 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
334 $actual_length += length($value_class);
338 else { $actual_length = length($value); }
341 seek($fh, $subloc + SIG_SIZE + $root->{file_offset}, SEEK_SET);
343 read( $fh, $size, $self->{data_size});
344 $size = unpack($self->{data_pack}, $size);
346 if ($actual_length <= $size) {
350 $location = $root->{end};
353 $tag->{offset} + $offset + $self->{hash_size} + $root->{file_offset},
356 print( $fh pack($self->{long_pack}, $location) );
360 elsif ( defined $offset ) {
361 $location = $root->{end};
363 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
364 print( $fh $md5 . pack($self->{long_pack}, $location) );
366 # If bucket didn't fit into list, split into a new index level
368 $self->split_index( $obj, $md5, $tag );
370 $location = $root->{end};
373 $self->write_value( $obj, $location, $plain_key, $value );
380 my ($obj, $location, $key, $value) = @_;
383 my $root = $obj->_root;
385 my $is_dbm_deep = eval {
386 local $SIG{'__DIE__'};
387 $value->isa( 'DBM::Deep' );
390 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
392 seek($fh, $location + $root->{file_offset}, SEEK_SET);
395 # Write signature based on content type, set content length and write
398 my $r = Scalar::Util::reftype($value) || '';
400 if ( $internal_ref ) {
401 print( $fh SIG_INTERNAL );
402 print( $fh pack($self->{data_pack}, $self->{long_size}) );
403 print( $fh pack($self->{long_pack}, $value->_base_offset) );
404 $content_length = $self->{long_size};
408 print( $fh SIG_HASH );
409 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
410 $content_length = $self->{index_size};
412 elsif ($r eq 'ARRAY') {
413 print( $fh SIG_ARRAY );
414 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
415 $content_length = $self->{index_size};
417 elsif (!defined($value)) {
418 print( $fh SIG_NULL );
419 print( $fh pack($self->{data_pack}, 0) );
423 print( $fh SIG_DATA );
424 print( $fh pack($self->{data_pack}, length($value)) . $value );
425 $content_length = length($value);
430 # Plain key is stored AFTER value, as keys are typically fetched less often.
432 print( $fh pack($self->{data_pack}, length($key)) . $key );
435 # If value is blessed, preserve class name
437 if ( $root->{autobless} ) {
438 my $value_class = Scalar::Util::blessed($value);
439 if ( defined $value_class && !$value->isa( 'DBM::Deep' ) ) {
441 # Blessed ref -- will restore later
444 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
445 $content_length += 1;
446 $content_length += $self->{data_size} + length($value_class);
450 $content_length += 1;
455 # If this is a new content area, advance EOF counter
457 if ($location == $root->{end}) {
458 $root->{end} += SIG_SIZE;
459 $root->{end} += $self->{data_size} + $content_length;
460 $root->{end} += $self->{data_size} + length($key);
464 # If content is a hash or array, create new child DBM::Deep object and
465 # pass each key or element to it.
467 if ( ! $internal_ref ) {
469 my $branch = DBM::Deep->new(
470 type => DBM::Deep->TYPE_HASH,
471 base_offset => $location,
474 foreach my $key (keys %{$value}) {
475 $branch->STORE( $key, $value->{$key} );
478 elsif ($r eq 'ARRAY') {
479 my $branch = DBM::Deep->new(
480 type => DBM::Deep->TYPE_ARRAY,
481 base_offset => $location,
485 foreach my $element (@{$value}) {
486 $branch->STORE( $index, $element );
497 my ($obj, $md5, $tag) = @_;
500 my $root = $obj->_root;
501 my $keys = $tag->{content};
503 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
504 print( $fh pack($self->{long_pack}, $root->{end}) );
506 my $index_tag = $self->create_tag(
510 chr(0) x $self->{index_size},
515 $keys .= $md5 . pack($self->{long_pack}, 0);
518 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
519 my ($key, $old_subloc) = $self->_get_key_subloc( $keys, $i );
521 next BUCKET unless $key;
523 my $num = ord(substr($key, $tag->{ch} + 1, 1));
525 if ($offsets[$num]) {
526 my $offset = $offsets[$num] + SIG_SIZE + $self->{data_size};
527 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
529 read( $fh, $subkeys, $self->{bucket_list_size});
531 for (my $k=0; $k<$self->{max_buckets}; $k++) {
532 my ($temp, $subloc) = $self->_get_key_subloc( $subkeys, $k );
535 seek($fh, $offset + ($k * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
536 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
542 $offsets[$num] = $root->{end};
543 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
544 print( $fh pack($self->{long_pack}, $root->{end}) );
546 my $blist_tag = $self->create_tag($obj, $root->{end}, SIG_BLIST, chr(0) x $self->{bucket_list_size});
548 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
549 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
558 my ($obj, $subloc) = @_;
563 # Found match -- seek to offset and read signature
566 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
567 read( $fh, $signature, SIG_SIZE);
570 # If value is a hash or array, return new DBM::Deep object with correct offset
572 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
573 my $obj = DBM::Deep->new(
575 base_offset => $subloc,
579 if ($obj->_root->{autobless}) {
581 # Skip over value and plain key to see if object needs
584 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
587 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
588 if ($size) { seek($fh, $size, SEEK_CUR); }
591 read( $fh, $bless_bit, 1);
592 if (ord($bless_bit)) {
594 # Yes, object needs to be re-blessed
597 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
598 if ($size) { read( $fh, $class_name, $size); }
599 if ($class_name) { $obj = bless( $obj, $class_name ); }
605 elsif ( $signature eq SIG_INTERNAL ) {
607 read( $fh, $size, $self->{data_size});
608 $size = unpack($self->{data_pack}, $size);
612 read( $fh, $new_loc, $size );
613 $new_loc = unpack( $self->{long_pack}, $new_loc );
615 return $self->read_from_loc( $obj, $new_loc );
622 # Otherwise return actual value
624 elsif ($signature eq SIG_DATA) {
626 read( $fh, $size, $self->{data_size});
627 $size = unpack($self->{data_pack}, $size);
630 if ($size) { read( $fh, $value, $size); }
635 # Key exists, but content is null
640 sub get_bucket_value {
642 # Fetch single value given tag and MD5 digested key.
645 my ($obj, $tag, $md5) = @_;
647 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
649 return $self->read_from_loc( $obj, $subloc );
656 # Delete single key/value pair given tag and MD5 digested key.
659 my ($obj, $tag, $md5) = @_;
661 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
664 seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
665 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
666 print( $fh chr(0) x $self->{bucket_size} );
675 # Check existence of single key given tag and MD5 digested key.
678 my ($obj, $tag, $md5) = @_;
680 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
684 sub find_bucket_list {
686 # Locate offset for bucket list, given digested key
689 my ($obj, $md5, $args) = @_;
690 $args = {} unless $args;
693 # Locate offset for bucket list using digest index system
695 my $tag = $self->load_tag($obj, $obj->_base_offset)
696 or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
699 while ($tag->{signature} ne SIG_BLIST) {
700 my $num = ord substr($md5, $ch, 1);
702 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
703 $tag = $self->index_lookup( $obj, $tag, $num );
706 return if ! $args->{create};
709 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
710 print( $fh pack($self->{long_pack}, $obj->_root->{end}) );
712 $tag = $self->create_tag(
713 $obj, $obj->_root->{end},
715 chr(0) x $self->{bucket_list_size},
718 $tag->{ref_loc} = $ref_loc;
725 $tag->{ref_loc} = $ref_loc;
735 # Given index tag, lookup single entry in index and return .
738 my ($obj, $tag, $index) = @_;
740 my $location = unpack(
744 $index * $self->{long_size},
749 if (!$location) { return; }
751 return $self->load_tag( $obj, $location );
756 # Scan index and recursively step into deeper levels, looking for next key.
759 my ($obj, $offset, $ch, $force_return_next) = @_;
761 my $tag = $self->load_tag($obj, $offset );
765 if ($tag->{signature} ne SIG_BLIST) {
766 my $content = $tag->{content};
767 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
769 for (my $idx = $start; $idx < (2**8); $idx++) {
774 $idx * $self->{long_size},
780 my $result = $self->traverse_index(
781 $obj, $subloc, $ch + 1, $force_return_next,
784 if (defined($result)) { return $result; }
788 $obj->{return_next} = 1;
792 my $keys = $tag->{content};
793 if ($force_return_next) { $obj->{return_next} = 1; }
796 # Iterate through buckets, looking for a key match
798 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
799 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
801 # End of bucket list -- return to outer loop
803 $obj->{return_next} = 1;
806 # Located previous key -- return next one found
807 elsif ($key eq $obj->{prev_md5}) {
808 $obj->{return_next} = 1;
811 # Seek to bucket location and skip over signature
812 elsif ($obj->{return_next}) {
813 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
815 # Skip over value to get to plain key
817 read( $fh, $sig, SIG_SIZE );
820 read( $fh, $size, $self->{data_size});
821 $size = unpack($self->{data_pack}, $size);
822 if ($size) { seek($fh, $size, SEEK_CUR); }
824 # Read in plain key and return as scalar
826 read( $fh, $size, $self->{data_size});
827 $size = unpack($self->{data_pack}, $size);
828 if ($size) { read( $fh, $plain_key, $size); }
834 $obj->{return_next} = 1;
835 } # tag is a bucket list
842 # Locate next key, given digested previous one
847 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
848 $obj->{return_next} = 0;
851 # If the previous key was not specifed, start at the top and
852 # return the first one found.
854 if (!$obj->{prev_md5}) {
855 $obj->{prev_md5} = chr(0) x $self->{hash_size};
856 $obj->{return_next} = 1;
859 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
864 sub _get_key_subloc {
866 my ($keys, $idx) = @_;
868 my ($key, $subloc) = unpack(
869 "a$self->{hash_size} $self->{long_pack}",
872 ($idx * $self->{bucket_size}),
873 $self->{bucket_size},
877 return ($key, $subloc);
880 sub _find_in_buckets {
882 my ($tag, $md5) = @_;
885 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
886 my ($key, $subloc) = $self->_get_key_subloc( $tag->{content}, $i );
888 return ($subloc, $i * $self->{bucket_size}) unless $subloc;
890 next BUCKET if $key ne $md5;
892 return ($subloc, $i * $self->{bucket_size});
900 my ($obj, $size) = @_;
902 my $loc = $obj->_root->{end};
903 $obj->_root->{end} += $size;
910 my ($obj, $size, $loc) = @_;
918 # This will be added in later, after more refactoring is done. This is an early
919 # attempt at refactoring on the physical level instead of the virtual level.
922 my ($obj, $spot, $amount, $unpack) = @_;
925 seek( $fh, $spot + $obj->_root->{file_offset}, SEEK_SET );
928 my $bytes_read = read( $fh, $buffer, $amount );
931 $buffer = unpack( $unpack, $buffer );
935 return ($buffer, $bytes_read);