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;
114 unless ( $obj->{base_offset} ) {
115 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
117 my $bytes_read = read( $fh, $signature, length(SIG_FILE));
120 # File is empty -- write signature and master index
123 my $loc = $self->_request_space( $obj, length( SIG_FILE ) );
124 seek($fh, $loc + $obj->_root->{file_offset}, SEEK_SET);
125 print( $fh SIG_FILE);
127 $obj->{base_offset} = $self->_request_space(
128 $obj, $self->tag_size( $self->{index_size} ),
132 $obj, $obj->_base_offset, $obj->_type,
133 chr(0)x$self->{index_size},
136 # Flush the filehandle
137 my $old_fh = select $fh;
138 my $old_af = $|; $| = 1; $| = $old_af;
142 $obj->{base_offset} = $bytes_read;
145 # Check signature was valid
147 unless ($signature eq SIG_FILE) {
148 $self->close_fh( $obj );
149 $obj->_throw_error("Signature not found -- file is not a Deep DB");
153 # Get our type from master index signature
155 my $tag = $self->load_tag($obj, $obj->_base_offset)
156 or $obj->_throw_error("Corrupted file, no master index record");
158 unless ($obj->{type} eq $tag->{signature}) {
159 $obj->_throw_error("File type mismatch");
164 #XXX We have to make sure we don't mess up when autoflush isn't turned on
165 unless ( $obj->_root->{inode} ) {
166 my @stats = stat($obj->_fh);
167 $obj->_root->{inode} = $stats[1];
168 $obj->_root->{end} = $stats[7];
178 # Open a fh to the database, create if nonexistent.
179 # Make sure file signature matches DBM::Deep spec.
184 # Theoretically, adding O_BINARY should remove the need for the binmode
185 # Of course, testing it is going to be ... interesting.
186 my $flags = O_RDWR | O_CREAT | O_BINARY;
189 my $filename = $obj->_root->{file};
190 sysopen( $fh, $filename, $flags )
191 or $obj->_throw_error("Cannot sysopen file '$filename': $!");
192 $obj->_root->{fh} = $fh;
194 #XXX Can we remove this by using the right sysopen() flags?
195 # Maybe ... q.v. above
196 binmode $fh; # for win32
198 if ($obj->_root->{autoflush}) {
199 my $old = select $fh;
211 if ( my $fh = $obj->_root->{fh} ) {
214 $obj->_root->{fh} = undef;
222 return SIG_SIZE + $self->{data_size} + $size;
227 # Given offset, signature and content, create tag and write to disk
230 my ($obj, $offset, $sig, $content) = @_;
231 my $size = length( $content );
235 if ( defined $offset ) {
236 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
239 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
241 return unless defined $offset;
246 offset => $offset + SIG_SIZE + $self->{data_size},
253 # Given offset, load single tag and return signature, size and data
256 my ($obj, $offset) = @_;
258 # print join(':',map{$_||''}caller(1)), $/;
262 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
264 #XXX I'm not sure this check will work if autoflush isn't enabled ...
268 read( $fh, $b, SIG_SIZE + $self->{data_size} );
269 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
272 read( $fh, $buffer, $size);
277 offset => $offset + SIG_SIZE + $self->{data_size},
284 my ($obj, $value, $key) = @_;
286 my $is_dbm_deep = eval {
287 local $SIG{'__DIE__'};
288 $value->isa( 'DBM::Deep' );
291 my $len = SIG_SIZE + $self->{data_size}
292 + $self->{data_size} + length( $key );
294 if ( $is_dbm_deep && $value->_root eq $obj->_root ) {
295 return $len + $self->{long_size};
298 my $r = Scalar::Util::reftype( $value ) || '';
299 if ( $obj->_root->{autobless} ) {
300 # This is for the bit saying whether or not this thing is blessed.
304 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
305 if ( defined $value ) {
306 $len += length( $value );
311 $len += $self->{index_size};
313 # if autobless is enabled, must also take into consideration
314 # the class name as it is stored after the key.
315 if ( $obj->_root->{autobless} ) {
316 my $value_class = Scalar::Util::blessed($value);
317 if ( defined $value_class && !$is_dbm_deep ) {
318 $len += $self->{data_size} + length($value_class);
327 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
328 # plain (undigested) key and value.
331 my ($obj, $tag, $md5, $plain_key, $value) = @_;
333 # This verifies that only supported values will be stored.
335 my $r = Scalar::Util::reftype( $value );
338 last if $r eq 'HASH';
339 last if $r eq 'ARRAY';
342 "Storage of variables of type '$r' is not supported."
349 my $root = $obj->_root;
352 my $actual_length = $self->_length_needed( $obj, $value, $plain_key );
354 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
356 # Updating a known md5
360 if ($actual_length <= $size) {
364 $location = $self->_request_space( $obj, $actual_length );
367 $tag->{offset} + $offset
368 + $self->{hash_size} + $root->{file_offset},
371 print( $fh pack($self->{long_pack}, $location ) );
372 print( $fh pack($self->{long_pack}, $actual_length ) );
376 elsif ( defined $offset ) {
377 $location = $self->_request_space( $obj, $actual_length );
379 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
380 print( $fh $md5 . pack($self->{long_pack}, $location ) );
381 print( $fh pack($self->{long_pack}, $actual_length ) );
383 # If bucket didn't fit into list, split into a new index level
385 #XXX This is going to be a problem.
386 $self->split_index( $obj, $md5, $tag );
388 $location = $self->_request_space( $obj, $actual_length );
391 $self->write_value( $obj, $location, $plain_key, $value );
398 my ($obj, $location, $key, $value) = @_;
401 my $root = $obj->_root;
403 my $is_dbm_deep = eval {
404 local $SIG{'__DIE__'};
405 $value->isa( 'DBM::Deep' );
408 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
410 seek($fh, $location + $root->{file_offset}, SEEK_SET);
413 # Write signature based on content type, set content length and write
416 my $r = Scalar::Util::reftype($value) || '';
417 if ( $internal_ref ) {
418 $self->write_tag( $obj, undef, SIG_INTERNAL,pack($self->{long_pack}, $value->_base_offset) );
420 elsif ($r eq 'HASH') {
421 $self->write_tag( $obj, undef, SIG_HASH, chr(0)x$self->{index_size} );
423 elsif ($r eq 'ARRAY') {
424 $self->write_tag( $obj, undef, SIG_ARRAY, chr(0)x$self->{index_size} );
426 elsif (!defined($value)) {
427 $self->write_tag( $obj, undef, SIG_NULL, '' );
430 $self->write_tag( $obj, undef, SIG_DATA, $value );
434 # Plain key is stored AFTER value, as keys are typically fetched less often.
436 print( $fh pack($self->{data_pack}, length($key)) . $key );
438 # Internal references don't care about autobless
439 return 1 if $internal_ref;
442 # If value is blessed, preserve class name
444 if ( $root->{autobless} ) {
445 my $value_class = Scalar::Util::blessed($value);
446 if ( defined $value_class && !$is_dbm_deep ) {
448 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
456 # If content is a hash or array, create new child DBM::Deep object and
457 # pass each key or element to it.
459 if ( !$internal_ref ) {
461 my $branch = DBM::Deep->new(
462 type => DBM::Deep->TYPE_HASH,
463 base_offset => $location,
466 foreach my $key (keys %{$value}) {
467 $branch->STORE( $key, $value->{$key} );
470 elsif ($r eq 'ARRAY') {
471 my $branch = DBM::Deep->new(
472 type => DBM::Deep->TYPE_ARRAY,
473 base_offset => $location,
477 foreach my $element (@{$value}) {
478 $branch->STORE( $index, $element );
489 my ($obj, $md5, $tag) = @_;
492 my $root = $obj->_root;
494 my $loc = $self->_request_space(
495 $obj, $self->tag_size( $self->{index_size} ),
498 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
499 print( $fh pack($self->{long_pack}, $loc) );
501 my $index_tag = $self->write_tag(
502 $obj, $loc, SIG_INDEX,
503 chr(0)x$self->{index_size},
508 my $keys = $tag->{content}
509 . $md5 . (pack($self->{long_pack}, 0) x 2);
512 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
513 my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
515 next BUCKET unless $key;
517 my $num = ord(substr($key, $tag->{ch} + 1, 1));
519 if ($offsets[$num]) {
520 seek($fh, $offsets[$num] + $root->{file_offset}, SEEK_SET);
522 read( $fh, $subkeys, $self->{bucket_list_size});
524 my ($subloc, $offset, $size) = $self->_find_in_buckets(
525 { content => $subkeys }, ''
528 seek($fh, $offsets[$num] + $offset + $root->{file_offset}, SEEK_SET);
529 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
534 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
536 my $loc = $self->_request_space(
537 $obj, $self->tag_size( $self->{bucket_list_size} ),
540 print( $fh pack($self->{long_pack}, $loc) );
542 my $blist_tag = $self->write_tag(
543 $obj, $loc, SIG_BLIST,
544 chr(0)x$self->{bucket_list_size},
547 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
548 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
550 $offsets[$num] = $blist_tag->{offset};
553 $self->_release_space(
554 $obj, $self->tag_size( $self->{index_size} ),
555 $tag->{offset} - SIG_SIZE - $self->{data_size},
563 my ($obj, $subloc) = @_;
568 # Found match -- seek to offset and read signature
571 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
572 read( $fh, $signature, SIG_SIZE);
575 # If value is a hash or array, return new DBM::Deep object with correct offset
577 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
578 my $obj = DBM::Deep->new(
580 base_offset => $subloc,
584 if ($obj->_root->{autobless}) {
586 # Skip over value and plain key to see if object needs
589 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
592 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
593 if ($size) { seek($fh, $size, SEEK_CUR); }
596 read( $fh, $bless_bit, 1);
597 if (ord($bless_bit)) {
599 # Yes, object needs to be re-blessed
602 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
603 if ($size) { read( $fh, $class_name, $size); }
604 if ($class_name) { $obj = bless( $obj, $class_name ); }
610 elsif ( $signature eq SIG_INTERNAL ) {
612 read( $fh, $size, $self->{data_size});
613 $size = unpack($self->{data_pack}, $size);
617 read( $fh, $new_loc, $size );
618 $new_loc = unpack( $self->{long_pack}, $new_loc );
620 return $self->read_from_loc( $obj, $new_loc );
627 # Otherwise return actual value
629 elsif ($signature eq SIG_DATA) {
631 read( $fh, $size, $self->{data_size});
632 $size = unpack($self->{data_pack}, $size);
635 if ($size) { read( $fh, $value, $size); }
640 # Key exists, but content is null
645 sub get_bucket_value {
647 # Fetch single value given tag and MD5 digested key.
650 my ($obj, $tag, $md5) = @_;
652 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
654 return $self->read_from_loc( $obj, $subloc );
661 # Delete single key/value pair given tag and MD5 digested key.
664 my ($obj, $tag, $md5) = @_;
666 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
669 seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
670 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
671 print( $fh chr(0) x $self->{bucket_size} );
680 # Check existence of single key given tag and MD5 digested key.
683 my ($obj, $tag, $md5) = @_;
685 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
689 sub find_bucket_list {
691 # Locate offset for bucket list, given digested key
694 my ($obj, $md5, $args) = @_;
695 $args = {} unless $args;
698 # Locate offset for bucket list using digest index system
700 my $tag = $self->load_tag($obj, $obj->_base_offset)
701 or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
704 while ($tag->{signature} ne SIG_BLIST) {
705 my $num = ord substr($md5, $ch, 1);
707 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
708 $tag = $self->index_lookup( $obj, $tag, $num );
711 return if !$args->{create};
713 my $loc = $self->_request_space(
714 $obj, $self->tag_size( $self->{bucket_list_size} ),
718 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
719 print( $fh pack($self->{long_pack}, $loc) );
721 $tag = $self->write_tag(
722 $obj, $loc, SIG_BLIST,
723 chr(0)x$self->{bucket_list_size},
726 $tag->{ref_loc} = $ref_loc;
733 $tag->{ref_loc} = $ref_loc;
741 # Given index tag, lookup single entry in index and return .
744 my ($obj, $tag, $index) = @_;
746 my $location = unpack(
750 $index * $self->{long_size},
755 if (!$location) { return; }
757 return $self->load_tag( $obj, $location );
762 # Scan index and recursively step into deeper levels, looking for next key.
765 my ($obj, $offset, $ch, $force_return_next) = @_;
767 my $tag = $self->load_tag($obj, $offset );
771 if ($tag->{signature} ne SIG_BLIST) {
772 my $content = $tag->{content};
773 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
775 for (my $idx = $start; $idx < (2**8); $idx++) {
780 $idx * $self->{long_size},
786 my $result = $self->traverse_index(
787 $obj, $subloc, $ch + 1, $force_return_next,
790 if (defined($result)) { return $result; }
794 $obj->{return_next} = 1;
798 my $keys = $tag->{content};
799 if ($force_return_next) { $obj->{return_next} = 1; }
802 # Iterate through buckets, looking for a key match
804 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
805 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
807 # End of bucket list -- return to outer loop
809 $obj->{return_next} = 1;
812 # Located previous key -- return next one found
813 elsif ($key eq $obj->{prev_md5}) {
814 $obj->{return_next} = 1;
817 # Seek to bucket location and skip over signature
818 elsif ($obj->{return_next}) {
819 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
821 # Skip over value to get to plain key
823 read( $fh, $sig, SIG_SIZE );
826 read( $fh, $size, $self->{data_size});
827 $size = unpack($self->{data_pack}, $size);
828 if ($size) { seek($fh, $size, SEEK_CUR); }
830 # Read in plain key and return as scalar
832 read( $fh, $size, $self->{data_size});
833 $size = unpack($self->{data_pack}, $size);
834 if ($size) { read( $fh, $plain_key, $size); }
840 $obj->{return_next} = 1;
841 } # tag is a bucket list
848 # Locate next key, given digested previous one
853 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
854 $obj->{return_next} = 0;
857 # If the previous key was not specifed, start at the top and
858 # return the first one found.
860 if (!$obj->{prev_md5}) {
861 $obj->{prev_md5} = chr(0) x $self->{hash_size};
862 $obj->{return_next} = 1;
865 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
870 sub _get_key_subloc {
872 my ($keys, $idx) = @_;
874 my ($key, $subloc, $size) = unpack(
875 "a$self->{hash_size} $self->{long_pack} $self->{long_pack}",
878 ($idx * $self->{bucket_size}),
879 $self->{bucket_size},
883 return ($key, $subloc, $size);
886 sub _find_in_buckets {
888 my ($tag, $md5) = @_;
891 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
892 my ($key, $subloc, $size) = $self->_get_key_subloc(
896 return ($subloc, $i * $self->{bucket_size}, $size) unless $subloc;
898 next BUCKET if $key ne $md5;
900 return ($subloc, $i * $self->{bucket_size}, $size);
908 # my ($obj, $spot, $data) = @_;
910 # my $fh = $obj->_fh;
911 # seek( $fh, $spot, SEEK_SET );
912 # print( $fh $data );
919 my ($obj, $size) = @_;
921 my $loc = $obj->_root->{end};
922 $obj->_root->{end} += $size;
929 my ($obj, $size, $loc) = @_;
934 seek( $fh, $loc + $obj->_root->{file_offset}, SEEK_SET );
936 . pack($self->{long_pack}, $size )
937 . pack($self->{long_pack}, $next_loc )
946 # This will be added in later, after more refactoring is done. This is an early
947 # attempt at refactoring on the physical level instead of the virtual level.
950 my ($obj, $spot, $amount, $unpack) = @_;
953 seek( $fh, $spot + $obj->_root->{file_offset}, SEEK_SET );
956 my $bytes_read = read( $fh, $buffer, $amount );
959 $buffer = unpack( $unpack, $buffer );
963 return ($buffer, $bytes_read);