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->tag_size( $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;
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 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
235 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
240 offset => $offset + SIG_SIZE + $self->{data_size},
247 # Given offset, load single tag and return signature, size and data
250 my ($obj, $offset) = @_;
252 # print join(':',map{$_||''}caller(1)), $/;
256 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
258 #XXX I'm not sure this check will work if autoflush isn't enabled ...
262 read( $fh, $b, SIG_SIZE + $self->{data_size} );
263 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
266 read( $fh, $buffer, $size);
271 offset => $offset + SIG_SIZE + $self->{data_size},
278 my ($obj, $value) = @_;
280 my $is_dbm_deep = eval {
281 local $SIG{'__DIE__'};
282 $value->isa( 'DBM::Deep' );
285 my $internal_ref = $is_dbm_deep && ($value->_root eq $obj->_root);
287 if ( $internal_ref ) {
288 return $self->{long_size};
291 my $r = Scalar::Util::reftype( $value ) || '';
292 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
293 return length( $value );
296 my $actual_length = $self->{index_size};
298 # if autobless is enabled, must also take into consideration
299 # the class name, as it is stored along with key/value.
300 if ( $obj->_root->{autobless} ) {
301 my $value_class = Scalar::Util::blessed($value);
302 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
303 $actual_length += length($value_class);
307 return $actual_length;
312 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
313 # plain (undigested) key and value.
316 my ($obj, $tag, $md5, $plain_key, $value) = @_;
318 # This verifies that only supported values will be stored.
320 my $r = Scalar::Util::reftype( $value );
323 last if $r eq 'HASH';
324 last if $r eq 'ARRAY';
327 "Storage of variables of type '$r' is not supported."
334 my $root = $obj->_root;
338 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
340 # Updating a known md5
344 seek($fh, $subloc + SIG_SIZE + $root->{file_offset}, SEEK_SET);
346 read( $fh, $size, $self->{data_size});
347 $size = unpack($self->{data_pack}, $size);
349 my $actual_length = $self->_length_needed( $obj, $value );
351 if ($actual_length <= $size) {
355 $location = $root->{end};
358 $tag->{offset} + $offset + $self->{hash_size} + $root->{file_offset},
361 print( $fh pack($self->{long_pack}, $location) );
365 elsif ( defined $offset ) {
366 $location = $root->{end};
368 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
369 print( $fh $md5 . pack($self->{long_pack}, $location) );
371 # If bucket didn't fit into list, split into a new index level
373 $self->split_index( $obj, $md5, $tag );
375 $location = $root->{end};
378 $self->write_value( $obj, $location, $plain_key, $value );
385 my ($obj, $location, $key, $value) = @_;
388 my $root = $obj->_root;
390 my $is_dbm_deep = eval {
391 local $SIG{'__DIE__'};
392 $value->isa( 'DBM::Deep' );
395 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
397 seek($fh, $location + $root->{file_offset}, SEEK_SET);
400 # Write signature based on content type, set content length and write
403 my $r = Scalar::Util::reftype($value) || '';
405 if ( $internal_ref ) {
406 print( $fh SIG_INTERNAL );
407 print( $fh pack($self->{data_pack}, $self->{long_size}) );
408 print( $fh pack($self->{long_pack}, $value->_base_offset) );
409 $content_length = $self->{long_size};
413 print( $fh SIG_HASH );
414 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
415 $content_length = $self->{index_size};
417 elsif ($r eq 'ARRAY') {
418 print( $fh SIG_ARRAY );
419 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
420 $content_length = $self->{index_size};
422 elsif (!defined($value)) {
423 print( $fh SIG_NULL );
424 print( $fh pack($self->{data_pack}, 0) );
428 print( $fh SIG_DATA );
429 print( $fh pack($self->{data_pack}, length($value)) . $value );
430 $content_length = length($value);
435 # Plain key is stored AFTER value, as keys are typically fetched less often.
437 print( $fh pack($self->{data_pack}, length($key)) . $key );
440 # If value is blessed, preserve class name
442 if ( $root->{autobless} ) {
443 my $value_class = Scalar::Util::blessed($value);
444 if ( defined $value_class && !$value->isa( 'DBM::Deep' ) ) {
446 # Blessed ref -- will restore later
449 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
450 $content_length += 1;
451 $content_length += $self->{data_size} + length($value_class);
455 $content_length += 1;
460 # If this is a new content area, advance EOF counter
462 if ($location == $root->{end}) {
463 $root->{end} += SIG_SIZE;
464 $root->{end} += $self->{data_size} + $content_length;
465 $root->{end} += $self->{data_size} + length($key);
469 # If content is a hash or array, create new child DBM::Deep object and
470 # pass each key or element to it.
472 if ( ! $internal_ref ) {
474 my $branch = DBM::Deep->new(
475 type => DBM::Deep->TYPE_HASH,
476 base_offset => $location,
479 foreach my $key (keys %{$value}) {
480 $branch->STORE( $key, $value->{$key} );
483 elsif ($r eq 'ARRAY') {
484 my $branch = DBM::Deep->new(
485 type => DBM::Deep->TYPE_ARRAY,
486 base_offset => $location,
490 foreach my $element (@{$value}) {
491 $branch->STORE( $index, $element );
502 my ($obj, $md5, $tag) = @_;
505 my $root = $obj->_root;
506 my $keys = $tag->{content};
508 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
510 my $loc = $self->_request_space(
511 $obj, $self->tag_size( $self->{index_size} ),
514 print( $fh pack($self->{long_pack}, $loc) );
516 my $index_tag = $self->create_tag(
517 $obj, $loc, SIG_INDEX,
518 chr(0) x $self->{index_size},
523 $keys .= $md5 . pack($self->{long_pack}, 0);
526 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
527 my ($key, $old_subloc) = $self->_get_key_subloc( $keys, $i );
529 next BUCKET unless $key;
531 my $num = ord(substr($key, $tag->{ch} + 1, 1));
533 if ($offsets[$num]) {
534 my $offset = $offsets[$num] + SIG_SIZE + $self->{data_size};
535 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
537 read( $fh, $subkeys, $self->{bucket_list_size});
539 for (my $k=0; $k<$self->{max_buckets}; $k++) {
540 my ($temp, $subloc) = $self->_get_key_subloc( $subkeys, $k );
543 seek($fh, $offset + ($k * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
544 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
550 $offsets[$num] = $root->{end};
551 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
553 my $loc = $self->_request_space(
554 $obj, $self->tag_size( $self->{bucket_list_size} ),
557 print( $fh pack($self->{long_pack}, $loc) );
559 my $blist_tag = $self->create_tag(
560 $obj, $loc, SIG_BLIST,
561 chr(0) x $self->{bucket_list_size},
564 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
565 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
574 my ($obj, $subloc) = @_;
579 # Found match -- seek to offset and read signature
582 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
583 read( $fh, $signature, SIG_SIZE);
586 # If value is a hash or array, return new DBM::Deep object with correct offset
588 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
589 my $obj = DBM::Deep->new(
591 base_offset => $subloc,
595 if ($obj->_root->{autobless}) {
597 # Skip over value and plain key to see if object needs
600 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
603 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
604 if ($size) { seek($fh, $size, SEEK_CUR); }
607 read( $fh, $bless_bit, 1);
608 if (ord($bless_bit)) {
610 # Yes, object needs to be re-blessed
613 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
614 if ($size) { read( $fh, $class_name, $size); }
615 if ($class_name) { $obj = bless( $obj, $class_name ); }
621 elsif ( $signature eq SIG_INTERNAL ) {
623 read( $fh, $size, $self->{data_size});
624 $size = unpack($self->{data_pack}, $size);
628 read( $fh, $new_loc, $size );
629 $new_loc = unpack( $self->{long_pack}, $new_loc );
631 return $self->read_from_loc( $obj, $new_loc );
638 # Otherwise return actual value
640 elsif ($signature eq SIG_DATA) {
642 read( $fh, $size, $self->{data_size});
643 $size = unpack($self->{data_pack}, $size);
646 if ($size) { read( $fh, $value, $size); }
651 # Key exists, but content is null
656 sub get_bucket_value {
658 # Fetch single value given tag and MD5 digested key.
661 my ($obj, $tag, $md5) = @_;
663 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
665 return $self->read_from_loc( $obj, $subloc );
672 # Delete single key/value pair given tag and MD5 digested key.
675 my ($obj, $tag, $md5) = @_;
677 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
680 seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
681 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
682 print( $fh chr(0) x $self->{bucket_size} );
691 # Check existence of single key given tag and MD5 digested key.
694 my ($obj, $tag, $md5) = @_;
696 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
700 sub find_bucket_list {
702 # Locate offset for bucket list, given digested key
705 my ($obj, $md5, $args) = @_;
706 $args = {} unless $args;
709 # Locate offset for bucket list using digest index system
711 my $tag = $self->load_tag($obj, $obj->_base_offset)
712 or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
715 while ($tag->{signature} ne SIG_BLIST) {
716 my $num = ord substr($md5, $ch, 1);
718 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
719 $tag = $self->index_lookup( $obj, $tag, $num );
722 return if !$args->{create};
725 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
727 my $loc = $self->_request_space(
728 $obj, $self->tag_size( $self->{bucket_list_size} ),
731 print( $fh pack($self->{long_pack}, $loc) );
733 $tag = $self->create_tag(
734 $obj, $loc, SIG_BLIST,
735 chr(0) x $self->{bucket_list_size},
738 $tag->{ref_loc} = $ref_loc;
745 $tag->{ref_loc} = $ref_loc;
753 # Given index tag, lookup single entry in index and return .
756 my ($obj, $tag, $index) = @_;
758 my $location = unpack(
762 $index * $self->{long_size},
767 if (!$location) { return; }
769 return $self->load_tag( $obj, $location );
774 # Scan index and recursively step into deeper levels, looking for next key.
777 my ($obj, $offset, $ch, $force_return_next) = @_;
779 my $tag = $self->load_tag($obj, $offset );
783 if ($tag->{signature} ne SIG_BLIST) {
784 my $content = $tag->{content};
785 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
787 for (my $idx = $start; $idx < (2**8); $idx++) {
792 $idx * $self->{long_size},
798 my $result = $self->traverse_index(
799 $obj, $subloc, $ch + 1, $force_return_next,
802 if (defined($result)) { return $result; }
806 $obj->{return_next} = 1;
810 my $keys = $tag->{content};
811 if ($force_return_next) { $obj->{return_next} = 1; }
814 # Iterate through buckets, looking for a key match
816 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
817 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
819 # End of bucket list -- return to outer loop
821 $obj->{return_next} = 1;
824 # Located previous key -- return next one found
825 elsif ($key eq $obj->{prev_md5}) {
826 $obj->{return_next} = 1;
829 # Seek to bucket location and skip over signature
830 elsif ($obj->{return_next}) {
831 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
833 # Skip over value to get to plain key
835 read( $fh, $sig, SIG_SIZE );
838 read( $fh, $size, $self->{data_size});
839 $size = unpack($self->{data_pack}, $size);
840 if ($size) { seek($fh, $size, SEEK_CUR); }
842 # Read in plain key and return as scalar
844 read( $fh, $size, $self->{data_size});
845 $size = unpack($self->{data_pack}, $size);
846 if ($size) { read( $fh, $plain_key, $size); }
852 $obj->{return_next} = 1;
853 } # tag is a bucket list
860 # Locate next key, given digested previous one
865 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
866 $obj->{return_next} = 0;
869 # If the previous key was not specifed, start at the top and
870 # return the first one found.
872 if (!$obj->{prev_md5}) {
873 $obj->{prev_md5} = chr(0) x $self->{hash_size};
874 $obj->{return_next} = 1;
877 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
882 sub _get_key_subloc {
884 my ($keys, $idx) = @_;
886 my ($key, $subloc) = unpack(
887 "a$self->{hash_size} $self->{long_pack}",
890 ($idx * $self->{bucket_size}),
891 $self->{bucket_size},
895 return ($key, $subloc);
898 sub _find_in_buckets {
900 my ($tag, $md5) = @_;
903 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
904 my ($key, $subloc) = $self->_get_key_subloc( $tag->{content}, $i );
906 return ($subloc, $i * $self->{bucket_size}) unless $subloc;
908 next BUCKET if $key ne $md5;
910 return ($subloc, $i * $self->{bucket_size});
918 my ($obj, $size) = @_;
920 my $loc = $obj->_root->{end};
921 $obj->_root->{end} += $size;
928 my ($obj, $size, $loc) = @_;
936 # This will be added in later, after more refactoring is done. This is an early
937 # attempt at refactoring on the physical level instead of the virtual level.
940 my ($obj, $spot, $amount, $unpack) = @_;
943 seek( $fh, $spot + $obj->_root->{file_offset}, SEEK_SET );
946 my $bytes_read = read( $fh, $buffer, $amount );
949 $buffer = unpack( $unpack, $buffer );
953 return ($buffer, $bytes_read);