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 my ($obj, $value) = @_;
278 my $is_dbm_deep = eval {
279 local $SIG{'__DIE__'};
280 $value->isa( 'DBM::Deep' );
283 my $internal_ref = $is_dbm_deep && ($value->_root eq $obj->_root);
285 if ( $internal_ref ) {
286 return $self->{long_size};
289 my $r = Scalar::Util::reftype( $value ) || '';
290 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
291 return length( $value );
294 my $actual_length = $self->{index_size};
296 # if autobless is enabled, must also take into consideration
297 # the class name, as it is stored along with key/value.
298 if ( $obj->_root->{autobless} ) {
299 my $value_class = Scalar::Util::blessed($value);
300 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
301 $actual_length += length($value_class);
305 return $actual_length;
310 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
311 # plain (undigested) key and value.
314 my ($obj, $tag, $md5, $plain_key, $value) = @_;
316 # This verifies that only supported values will be stored.
318 my $r = Scalar::Util::reftype( $value );
321 last if $r eq 'HASH';
322 last if $r eq 'ARRAY';
325 "Storage of variables of type '$r' is not supported."
332 my $root = $obj->_root;
336 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
338 # Updating a known md5
342 seek($fh, $subloc + SIG_SIZE + $root->{file_offset}, SEEK_SET);
344 read( $fh, $size, $self->{data_size});
345 $size = unpack($self->{data_pack}, $size);
347 my $actual_length = $self->_length_needed( $obj, $value );
349 if ($actual_length <= $size) {
353 $location = $root->{end};
356 $tag->{offset} + $offset + $self->{hash_size} + $root->{file_offset},
359 print( $fh pack($self->{long_pack}, $location) );
363 elsif ( defined $offset ) {
364 $location = $root->{end};
366 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
367 print( $fh $md5 . pack($self->{long_pack}, $location) );
369 # If bucket didn't fit into list, split into a new index level
371 $self->split_index( $obj, $md5, $tag );
373 $location = $root->{end};
376 $self->write_value( $obj, $location, $plain_key, $value );
383 my ($obj, $location, $key, $value) = @_;
386 my $root = $obj->_root;
388 my $is_dbm_deep = eval {
389 local $SIG{'__DIE__'};
390 $value->isa( 'DBM::Deep' );
393 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
395 seek($fh, $location + $root->{file_offset}, SEEK_SET);
398 # Write signature based on content type, set content length and write
401 my $r = Scalar::Util::reftype($value) || '';
403 if ( $internal_ref ) {
404 print( $fh SIG_INTERNAL );
405 print( $fh pack($self->{data_pack}, $self->{long_size}) );
406 print( $fh pack($self->{long_pack}, $value->_base_offset) );
407 $content_length = $self->{long_size};
411 print( $fh SIG_HASH );
412 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
413 $content_length = $self->{index_size};
415 elsif ($r eq 'ARRAY') {
416 print( $fh SIG_ARRAY );
417 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
418 $content_length = $self->{index_size};
420 elsif (!defined($value)) {
421 print( $fh SIG_NULL );
422 print( $fh pack($self->{data_pack}, 0) );
426 print( $fh SIG_DATA );
427 print( $fh pack($self->{data_pack}, length($value)) . $value );
428 $content_length = length($value);
433 # Plain key is stored AFTER value, as keys are typically fetched less often.
435 print( $fh pack($self->{data_pack}, length($key)) . $key );
438 # If value is blessed, preserve class name
440 if ( $root->{autobless} ) {
441 my $value_class = Scalar::Util::blessed($value);
442 if ( defined $value_class && !$value->isa( 'DBM::Deep' ) ) {
444 # Blessed ref -- will restore later
447 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
448 $content_length += 1;
449 $content_length += $self->{data_size} + length($value_class);
453 $content_length += 1;
458 # If this is a new content area, advance EOF counter
460 if ($location == $root->{end}) {
461 $root->{end} += SIG_SIZE;
462 $root->{end} += $self->{data_size} + $content_length;
463 $root->{end} += $self->{data_size} + length($key);
467 # If content is a hash or array, create new child DBM::Deep object and
468 # pass each key or element to it.
470 if ( ! $internal_ref ) {
472 my $branch = DBM::Deep->new(
473 type => DBM::Deep->TYPE_HASH,
474 base_offset => $location,
477 foreach my $key (keys %{$value}) {
478 $branch->STORE( $key, $value->{$key} );
481 elsif ($r eq 'ARRAY') {
482 my $branch = DBM::Deep->new(
483 type => DBM::Deep->TYPE_ARRAY,
484 base_offset => $location,
488 foreach my $element (@{$value}) {
489 $branch->STORE( $index, $element );
500 my ($obj, $md5, $tag) = @_;
503 my $root = $obj->_root;
504 my $keys = $tag->{content};
506 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
507 print( $fh pack($self->{long_pack}, $root->{end}) );
509 my $index_tag = $self->create_tag(
513 chr(0) x $self->{index_size},
518 $keys .= $md5 . pack($self->{long_pack}, 0);
521 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
522 my ($key, $old_subloc) = $self->_get_key_subloc( $keys, $i );
524 next BUCKET unless $key;
526 my $num = ord(substr($key, $tag->{ch} + 1, 1));
528 if ($offsets[$num]) {
529 my $offset = $offsets[$num] + SIG_SIZE + $self->{data_size};
530 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
532 read( $fh, $subkeys, $self->{bucket_list_size});
534 for (my $k=0; $k<$self->{max_buckets}; $k++) {
535 my ($temp, $subloc) = $self->_get_key_subloc( $subkeys, $k );
538 seek($fh, $offset + ($k * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
539 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
545 $offsets[$num] = $root->{end};
546 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
547 print( $fh pack($self->{long_pack}, $root->{end}) );
549 my $blist_tag = $self->create_tag($obj, $root->{end}, SIG_BLIST, chr(0) x $self->{bucket_list_size});
551 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
552 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
561 my ($obj, $subloc) = @_;
566 # Found match -- seek to offset and read signature
569 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
570 read( $fh, $signature, SIG_SIZE);
573 # If value is a hash or array, return new DBM::Deep object with correct offset
575 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
576 my $obj = DBM::Deep->new(
578 base_offset => $subloc,
582 if ($obj->_root->{autobless}) {
584 # Skip over value and plain key to see if object needs
587 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
590 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
591 if ($size) { seek($fh, $size, SEEK_CUR); }
594 read( $fh, $bless_bit, 1);
595 if (ord($bless_bit)) {
597 # Yes, object needs to be re-blessed
600 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
601 if ($size) { read( $fh, $class_name, $size); }
602 if ($class_name) { $obj = bless( $obj, $class_name ); }
608 elsif ( $signature eq SIG_INTERNAL ) {
610 read( $fh, $size, $self->{data_size});
611 $size = unpack($self->{data_pack}, $size);
615 read( $fh, $new_loc, $size );
616 $new_loc = unpack( $self->{long_pack}, $new_loc );
618 return $self->read_from_loc( $obj, $new_loc );
625 # Otherwise return actual value
627 elsif ($signature eq SIG_DATA) {
629 read( $fh, $size, $self->{data_size});
630 $size = unpack($self->{data_pack}, $size);
633 if ($size) { read( $fh, $value, $size); }
638 # Key exists, but content is null
643 sub get_bucket_value {
645 # Fetch single value given tag and MD5 digested key.
648 my ($obj, $tag, $md5) = @_;
650 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
652 return $self->read_from_loc( $obj, $subloc );
659 # Delete single key/value pair given tag and MD5 digested key.
662 my ($obj, $tag, $md5) = @_;
664 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
667 seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
668 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
669 print( $fh chr(0) x $self->{bucket_size} );
678 # Check existence of single key given tag and MD5 digested key.
681 my ($obj, $tag, $md5) = @_;
683 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
687 sub find_bucket_list {
689 # Locate offset for bucket list, given digested key
692 my ($obj, $md5, $args) = @_;
693 $args = {} unless $args;
696 # Locate offset for bucket list using digest index system
698 my $tag = $self->load_tag($obj, $obj->_base_offset)
699 or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
702 while ($tag->{signature} ne SIG_BLIST) {
703 my $num = ord substr($md5, $ch, 1);
705 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
706 $tag = $self->index_lookup( $obj, $tag, $num );
709 return if !$args->{create};
712 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
713 print( $fh pack($self->{long_pack}, $obj->_root->{end}) );
715 $tag = $self->create_tag(
716 $obj, $obj->_root->{end},
718 chr(0) x $self->{bucket_list_size},
721 $tag->{ref_loc} = $ref_loc;
728 $tag->{ref_loc} = $ref_loc;
738 # Given index tag, lookup single entry in index and return .
741 my ($obj, $tag, $index) = @_;
743 my $location = unpack(
747 $index * $self->{long_size},
752 if (!$location) { return; }
754 return $self->load_tag( $obj, $location );
759 # Scan index and recursively step into deeper levels, looking for next key.
762 my ($obj, $offset, $ch, $force_return_next) = @_;
764 my $tag = $self->load_tag($obj, $offset );
768 if ($tag->{signature} ne SIG_BLIST) {
769 my $content = $tag->{content};
770 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
772 for (my $idx = $start; $idx < (2**8); $idx++) {
777 $idx * $self->{long_size},
783 my $result = $self->traverse_index(
784 $obj, $subloc, $ch + 1, $force_return_next,
787 if (defined($result)) { return $result; }
791 $obj->{return_next} = 1;
795 my $keys = $tag->{content};
796 if ($force_return_next) { $obj->{return_next} = 1; }
799 # Iterate through buckets, looking for a key match
801 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
802 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
804 # End of bucket list -- return to outer loop
806 $obj->{return_next} = 1;
809 # Located previous key -- return next one found
810 elsif ($key eq $obj->{prev_md5}) {
811 $obj->{return_next} = 1;
814 # Seek to bucket location and skip over signature
815 elsif ($obj->{return_next}) {
816 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
818 # Skip over value to get to plain key
820 read( $fh, $sig, SIG_SIZE );
823 read( $fh, $size, $self->{data_size});
824 $size = unpack($self->{data_pack}, $size);
825 if ($size) { seek($fh, $size, SEEK_CUR); }
827 # Read in plain key and return as scalar
829 read( $fh, $size, $self->{data_size});
830 $size = unpack($self->{data_pack}, $size);
831 if ($size) { read( $fh, $plain_key, $size); }
837 $obj->{return_next} = 1;
838 } # tag is a bucket list
845 # Locate next key, given digested previous one
850 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
851 $obj->{return_next} = 0;
854 # If the previous key was not specifed, start at the top and
855 # return the first one found.
857 if (!$obj->{prev_md5}) {
858 $obj->{prev_md5} = chr(0) x $self->{hash_size};
859 $obj->{return_next} = 1;
862 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
867 sub _get_key_subloc {
869 my ($keys, $idx) = @_;
871 my ($key, $subloc) = unpack(
872 "a$self->{hash_size} $self->{long_pack}",
875 ($idx * $self->{bucket_size}),
876 $self->{bucket_size},
880 return ($key, $subloc);
883 sub _find_in_buckets {
885 my ($tag, $md5) = @_;
888 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
889 my ($key, $subloc) = $self->_get_key_subloc( $tag->{content}, $i );
891 return ($subloc, $i * $self->{bucket_size}) unless $subloc;
893 next BUCKET if $key ne $md5;
895 return ($subloc, $i * $self->{bucket_size});
903 my ($obj, $size) = @_;
905 my $loc = $obj->_root->{end};
906 $obj->_root->{end} += $size;
913 my ($obj, $size, $loc) = @_;
921 # This will be added in later, after more refactoring is done. This is an early
922 # attempt at refactoring on the physical level instead of the virtual level.
925 my ($obj, $spot, $amount, $unpack) = @_;
928 seek( $fh, $spot + $obj->_root->{file_offset}, SEEK_SET );
931 my $bytes_read = read( $fh, $buffer, $amount );
934 $buffer = unpack( $unpack, $buffer );
938 return ($buffer, $bytes_read);