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;
110 #XXX We have to make sure we don't mess up when autoflush isn't turned on
111 unless ( $obj->_root->{inode} ) {
112 my @stats = stat($obj->_fh);
113 $obj->_root->{inode} = $stats[1];
114 $obj->_root->{end} = $stats[7];
122 # Open a fh to the database, create if nonexistent.
123 # Make sure file signature matches DBM::Deep spec.
128 if (defined($obj->_fh)) { $self->close_fh( $obj ); }
130 # Theoretically, adding O_BINARY should remove the need for the binmode
131 # Of course, testing it is going to be ... interesting.
132 my $flags = O_RDWR | O_CREAT | O_BINARY;
135 my $filename = $obj->_root->{file};
136 sysopen( $fh, $filename, $flags )
137 or $obj->_throw_error("Cannot sysopen file '$filename': $!");
138 $obj->_root->{fh} = $fh;
140 #XXX Can we remove this by using the right sysopen() flags?
141 # Maybe ... q.v. above
142 binmode $fh; # for win32
144 if ($obj->_root->{autoflush}) {
145 my $old = select $fh;
150 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
152 my $bytes_read = read( $fh, $signature, length(SIG_FILE));
155 # File is empty -- write signature and master index
158 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
159 print( $fh SIG_FILE);
161 $obj->_root->{end} = length( SIG_FILE );
163 $obj->{base_offset} = $self->_request_space($obj, $self->{index_size});
166 $obj, $obj->_base_offset, $obj->_type, chr(0) x $self->{index_size},
169 # Flush the filehandle
170 my $old_fh = select $fh;
171 my $old_af = $|; $| = 1; $| = $old_af;
178 # Check signature was valid
180 unless ($signature eq SIG_FILE) {
181 $self->close_fh( $obj );
182 $obj->_throw_error("Signature not found -- file is not a Deep DB");
186 # Get our type from master index signature
188 my $tag = $self->load_tag($obj, $obj->_base_offset)
189 or $obj->_throw_error("Corrupted file, no master index record");
191 unless ($obj->{type} eq $tag->{signature}) {
192 $obj->_throw_error("File type mismatch");
195 #XXX We probably also want to store the hash algorithm name and not assume anything
196 #XXX The cool thing would be to allow a different hashing algorithm at every level
205 if ( my $fh = $obj->_root->{fh} ) {
208 $obj->_root->{fh} = undef;
215 # Given offset, signature and content, create tag and write to disk
218 my ($obj, $offset, $sig, $content) = @_;
219 my $size = length($content);
223 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
224 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
226 if ($offset == $obj->_root->{end}) {
227 $obj->_root->{end} += SIG_SIZE + $self->{data_size} + $size;
233 offset => $offset + SIG_SIZE + $self->{data_size},
240 # Given offset, load single tag and return signature, size and data
243 my ($obj, $offset) = @_;
247 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
249 #XXX I'm not sure this check will work if autoflush isn't enabled ...
253 read( $fh, $b, SIG_SIZE + $self->{data_size} );
254 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
257 read( $fh, $buffer, $size);
262 offset => $offset + SIG_SIZE + $self->{data_size},
269 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
270 # plain (undigested) key and value.
273 my ($obj, $tag, $md5, $plain_key, $value) = @_;
275 # This verifies that only supported values will be stored.
277 my $r = Scalar::Util::reftype( $value );
280 last if $r eq 'HASH';
281 last if $r eq 'ARRAY';
284 "Storage of variables of type '$r' is not supported."
291 my $root = $obj->_root;
293 my $is_dbm_deep = eval {
294 local $SIG{'__DIE__'};
295 $value->isa( 'DBM::Deep' );
298 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
302 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
304 # Updating a known md5
309 # If value is a hash, array, or raw value with equal or less size, we
310 # can reuse the same content area of the database. Otherwise, we have
311 # to create a new content area at the EOF.
314 if ( $internal_ref ) {
315 $actual_length = $self->{long_size};
318 my $r = Scalar::Util::reftype( $value ) || '';
319 if ( $r eq 'HASH' || $r eq 'ARRAY' ) {
320 $actual_length = $self->{index_size};
322 # if autobless is enabled, must also take into consideration
323 # the class name, as it is stored along with key/value.
324 if ( $root->{autobless} ) {
325 my $value_class = Scalar::Util::blessed($value);
326 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
327 $actual_length += length($value_class);
331 else { $actual_length = length($value); }
334 seek($fh, $subloc + SIG_SIZE + $root->{file_offset}, SEEK_SET);
336 read( $fh, $size, $self->{data_size});
337 $size = unpack($self->{data_pack}, $size);
339 if ($actual_length <= $size) {
343 $location = $root->{end};
346 $tag->{offset} + $offset + $self->{hash_size} + $root->{file_offset},
349 print( $fh pack($self->{long_pack}, $location) );
353 elsif ( defined $offset ) {
354 $location = $root->{end};
356 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
357 print( $fh $md5 . pack($self->{long_pack}, $location) );
359 # If bucket didn't fit into list, split into a new index level
361 $self->split_index( $obj, $md5, $tag );
363 $location = $root->{end};
366 $self->write_value( $obj, $location, $plain_key, $value );
373 my ($obj, $location, $key, $value) = @_;
376 my $root = $obj->_root;
378 my $is_dbm_deep = eval {
379 local $SIG{'__DIE__'};
380 $value->isa( 'DBM::Deep' );
383 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
385 seek($fh, $location + $root->{file_offset}, SEEK_SET);
388 # Write signature based on content type, set content length and write
391 my $r = Scalar::Util::reftype($value) || '';
393 if ( $internal_ref ) {
394 print( $fh SIG_INTERNAL );
395 print( $fh pack($self->{data_pack}, $self->{long_size}) );
396 print( $fh pack($self->{long_pack}, $value->_base_offset) );
397 $content_length = $self->{long_size};
401 print( $fh SIG_HASH );
402 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
403 $content_length = $self->{index_size};
405 elsif ($r eq 'ARRAY') {
406 print( $fh SIG_ARRAY );
407 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
408 $content_length = $self->{index_size};
410 elsif (!defined($value)) {
411 print( $fh SIG_NULL );
412 print( $fh pack($self->{data_pack}, 0) );
416 print( $fh SIG_DATA );
417 print( $fh pack($self->{data_pack}, length($value)) . $value );
418 $content_length = length($value);
423 # Plain key is stored AFTER value, as keys are typically fetched less often.
425 print( $fh pack($self->{data_pack}, length($key)) . $key );
428 # If value is blessed, preserve class name
430 if ( $root->{autobless} ) {
431 my $value_class = Scalar::Util::blessed($value);
432 if ( defined $value_class && !$value->isa( 'DBM::Deep' ) ) {
434 # Blessed ref -- will restore later
437 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
438 $content_length += 1;
439 $content_length += $self->{data_size} + length($value_class);
443 $content_length += 1;
448 # If this is a new content area, advance EOF counter
450 if ($location == $root->{end}) {
451 $root->{end} += SIG_SIZE;
452 $root->{end} += $self->{data_size} + $content_length;
453 $root->{end} += $self->{data_size} + length($key);
457 # If content is a hash or array, create new child DBM::Deep object and
458 # pass each key or element to it.
460 if ( ! $internal_ref ) {
462 my $branch = DBM::Deep->new(
463 type => DBM::Deep->TYPE_HASH,
464 base_offset => $location,
467 foreach my $key (keys %{$value}) {
468 $branch->STORE( $key, $value->{$key} );
471 elsif ($r eq 'ARRAY') {
472 my $branch = DBM::Deep->new(
473 type => DBM::Deep->TYPE_ARRAY,
474 base_offset => $location,
478 foreach my $element (@{$value}) {
479 $branch->STORE( $index, $element );
490 my ($obj, $md5, $tag) = @_;
493 my $root = $obj->_root;
494 my $keys = $tag->{content};
496 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
497 print( $fh pack($self->{long_pack}, $root->{end}) );
499 my $index_tag = $self->create_tag(
503 chr(0) x $self->{index_size},
508 $keys .= $md5 . pack($self->{long_pack}, 0);
511 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
512 my ($key, $old_subloc) = $self->_get_key_subloc( $keys, $i );
514 next BUCKET unless $key;
516 my $num = ord(substr($key, $tag->{ch} + 1, 1));
518 if ($offsets[$num]) {
519 my $offset = $offsets[$num] + SIG_SIZE + $self->{data_size};
520 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
522 read( $fh, $subkeys, $self->{bucket_list_size});
524 for (my $k=0; $k<$self->{max_buckets}; $k++) {
525 my ($temp, $subloc) = $self->_get_key_subloc( $subkeys, $k );
528 seek($fh, $offset + ($k * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
529 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
535 $offsets[$num] = $root->{end};
536 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
537 print( $fh pack($self->{long_pack}, $root->{end}) );
539 my $blist_tag = $self->create_tag($obj, $root->{end}, SIG_BLIST, chr(0) x $self->{bucket_list_size});
541 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
542 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
551 my ($obj, $subloc) = @_;
556 # Found match -- seek to offset and read signature
559 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
560 read( $fh, $signature, SIG_SIZE);
563 # If value is a hash or array, return new DBM::Deep object with correct offset
565 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
566 my $obj = DBM::Deep->new(
568 base_offset => $subloc,
572 if ($obj->_root->{autobless}) {
574 # Skip over value and plain key to see if object needs
577 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
580 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
581 if ($size) { seek($fh, $size, SEEK_CUR); }
584 read( $fh, $bless_bit, 1);
585 if (ord($bless_bit)) {
587 # Yes, object needs to be re-blessed
590 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
591 if ($size) { read( $fh, $class_name, $size); }
592 if ($class_name) { $obj = bless( $obj, $class_name ); }
598 elsif ( $signature eq SIG_INTERNAL ) {
600 read( $fh, $size, $self->{data_size});
601 $size = unpack($self->{data_pack}, $size);
605 read( $fh, $new_loc, $size );
606 $new_loc = unpack( $self->{long_pack}, $new_loc );
608 return $self->read_from_loc( $obj, $new_loc );
615 # Otherwise return actual value
617 elsif ($signature eq SIG_DATA) {
619 read( $fh, $size, $self->{data_size});
620 $size = unpack($self->{data_pack}, $size);
623 if ($size) { read( $fh, $value, $size); }
628 # Key exists, but content is null
633 sub get_bucket_value {
635 # Fetch single value given tag and MD5 digested key.
638 my ($obj, $tag, $md5) = @_;
640 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
642 return $self->read_from_loc( $obj, $subloc );
649 # Delete single key/value pair given tag and MD5 digested key.
652 my ($obj, $tag, $md5) = @_;
654 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
657 seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
658 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
659 print( $fh chr(0) x $self->{bucket_size} );
668 # Check existence of single key given tag and MD5 digested key.
671 my ($obj, $tag, $md5) = @_;
673 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
677 sub find_bucket_list {
679 # Locate offset for bucket list, given digested key
682 my ($obj, $md5, $args) = @_;
683 $args = {} unless $args;
686 # Locate offset for bucket list using digest index system
688 my $tag = $self->load_tag($obj, $obj->_base_offset)
689 or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
692 while ($tag->{signature} ne SIG_BLIST) {
693 my $num = ord substr($md5, $ch, 1);
695 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
696 $tag = $self->index_lookup( $obj, $tag, $num );
699 return if ! $args->{create};
702 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
703 print( $fh pack($self->{long_pack}, $obj->_root->{end}) );
705 $tag = $self->create_tag(
706 $obj, $obj->_root->{end},
708 chr(0) x $self->{bucket_list_size},
711 $tag->{ref_loc} = $ref_loc;
718 $tag->{ref_loc} = $ref_loc;
728 # Given index tag, lookup single entry in index and return .
731 my ($obj, $tag, $index) = @_;
733 my $location = unpack(
737 $index * $self->{long_size},
742 if (!$location) { return; }
744 return $self->load_tag( $obj, $location );
749 # Scan index and recursively step into deeper levels, looking for next key.
752 my ($obj, $offset, $ch, $force_return_next) = @_;
754 my $tag = $self->load_tag($obj, $offset );
758 if ($tag->{signature} ne SIG_BLIST) {
759 my $content = $tag->{content};
760 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
762 for (my $idx = $start; $idx < (2**8); $idx++) {
765 substr($content, $idx * $self->{long_size}, $self->{long_size}),
769 my $result = $self->traverse_index(
770 $obj, $subloc, $ch + 1, $force_return_next,
773 if (defined($result)) { return $result; }
777 $obj->{return_next} = 1;
781 my $keys = $tag->{content};
782 if ($force_return_next) { $obj->{return_next} = 1; }
785 # Iterate through buckets, looking for a key match
787 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
788 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
790 # End of bucket list -- return to outer loop
792 $obj->{return_next} = 1;
795 # Located previous key -- return next one found
796 elsif ($key eq $obj->{prev_md5}) {
797 $obj->{return_next} = 1;
800 # Seek to bucket location and skip over signature
801 elsif ($obj->{return_next}) {
802 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
804 # Skip over value to get to plain key
806 read( $fh, $sig, SIG_SIZE );
809 read( $fh, $size, $self->{data_size});
810 $size = unpack($self->{data_pack}, $size);
811 if ($size) { seek($fh, $size, SEEK_CUR); }
813 # Read in plain key and return as scalar
815 read( $fh, $size, $self->{data_size});
816 $size = unpack($self->{data_pack}, $size);
817 if ($size) { read( $fh, $plain_key, $size); }
823 $obj->{return_next} = 1;
824 } # tag is a bucket list
831 # Locate next key, given digested previous one
836 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
837 $obj->{return_next} = 0;
840 # If the previous key was not specifed, start at the top and
841 # return the first one found.
843 if (!$obj->{prev_md5}) {
844 $obj->{prev_md5} = chr(0) x $self->{hash_size};
845 $obj->{return_next} = 1;
848 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
853 sub _get_key_subloc {
855 my ($keys, $idx) = @_;
857 my ($key, $subloc) = unpack(
858 "a$self->{hash_size} $self->{long_pack}",
861 ($idx * $self->{bucket_size}),
862 $self->{bucket_size},
866 return ($key, $subloc);
869 sub _find_in_buckets {
871 my ($tag, $md5) = @_;
874 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
875 my ($key, $subloc) = $self->_get_key_subloc( $tag->{content}, $i );
877 return ($subloc, $i * $self->{bucket_size}) unless $subloc;
879 next BUCKET if $key ne $md5;
881 return ($subloc, $i * $self->{bucket_size});
889 my ($obj, $size) = @_;
891 my $loc = $obj->_root->{end};
898 my ($obj, $size, $loc) = @_;
906 # This will be added in later, after more refactoring is done. This is an early
907 # attempt at refactoring on the physical level instead of the virtual level.
910 my ($obj, $spot, $amount, $unpack) = @_;
913 seek( $fh, $spot + $obj->_root->{file_offset}, SEEK_SET );
916 my $bytes_read = read( $fh, $buffer, $amount );
919 $buffer = unpack( $unpack, $buffer );
923 return ($buffer, $bytes_read);