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 $obj->{base_offset} = length( SIG_FILE )
111 unless defined $obj->{base_offset};
113 #XXX We have to make sure we don't mess up when autoflush isn't turned on
114 unless ( $obj->_root->{inode} ) {
115 my @stats = stat($obj->_fh);
116 $obj->_root->{inode} = $stats[1];
117 $obj->_root->{end} = $stats[7];
125 # Open a fh to the database, create if nonexistent.
126 # Make sure file signature matches DBM::Deep spec.
131 if (defined($obj->_fh)) { $self->close_fh( $obj ); }
133 # Theoretically, adding O_BINARY should remove the need for the binmode
134 # Of course, testing it is going to be ... interesting.
135 my $flags = O_RDWR | O_CREAT | O_BINARY;
138 my $filename = $obj->_root->{file};
139 sysopen( $fh, $filename, $flags )
140 or $obj->_throw_error("Cannot sysopen file '$filename': $!");
141 $obj->_root->{fh} = $fh;
143 #XXX Can we remove this by using the right sysopen() flags?
144 # Maybe ... q.v. above
145 binmode $fh; # for win32
147 if ($obj->_root->{autoflush}) {
148 my $old = select $fh;
153 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
155 my $bytes_read = read( $fh, $signature, length(SIG_FILE));
158 # File is empty -- write signature and master index
161 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
162 print( $fh SIG_FILE);
164 $obj->_root->{end} = length( SIG_FILE );
166 $obj->{base_offset} = $self->_request_space($obj, $self->{index_size});
169 $obj, $obj->_base_offset, $obj->_type, chr(0) x $self->{index_size},
172 # Flush the filehandle
173 my $old_fh = select $fh;
174 my $old_af = $|; $| = 1; $| = $old_af;
180 $obj->{base_offset} = $bytes_read
181 unless defined $obj->{base_offset};
184 # Check signature was valid
186 unless ($signature eq SIG_FILE) {
187 $self->close_fh( $obj );
188 $obj->_throw_error("Signature not found -- file is not a Deep DB");
192 # Get our type from master index signature
194 my $tag = $self->load_tag($obj, $obj->_base_offset)
195 or $obj->_throw_error("Corrupted file, no master index record");
197 unless ($obj->{type} eq $tag->{signature}) {
198 $obj->_throw_error("File type mismatch");
201 #XXX We probably also want to store the hash algorithm name and not assume anything
202 #XXX The cool thing would be to allow a different hashing algorithm at every level
211 if ( my $fh = $obj->_root->{fh} ) {
214 $obj->_root->{fh} = undef;
221 # Given offset, signature and content, create tag and write to disk
224 my ($obj, $offset, $sig, $content) = @_;
225 my $size = length($content);
229 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
230 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
232 if ($offset == $obj->_root->{end}) {
233 $obj->_root->{end} += SIG_SIZE + $self->{data_size} + $size;
239 offset => $offset + SIG_SIZE + $self->{data_size},
246 # Given offset, load single tag and return signature, size and data
249 my ($obj, $offset) = @_;
251 # print join(':',map{$_||''}caller(1)), $/;
255 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
257 #XXX I'm not sure this check will work if autoflush isn't enabled ...
261 read( $fh, $b, SIG_SIZE + $self->{data_size} );
262 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
265 read( $fh, $buffer, $size);
270 offset => $offset + SIG_SIZE + $self->{data_size},
277 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
278 # plain (undigested) key and value.
281 my ($obj, $tag, $md5, $plain_key, $value) = @_;
283 # This verifies that only supported values will be stored.
285 my $r = Scalar::Util::reftype( $value );
288 last if $r eq 'HASH';
289 last if $r eq 'ARRAY';
292 "Storage of variables of type '$r' is not supported."
299 my $root = $obj->_root;
301 my $is_dbm_deep = eval {
302 local $SIG{'__DIE__'};
303 $value->isa( 'DBM::Deep' );
306 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
310 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
312 # Updating a known md5
317 # If value is a hash, array, or raw value with equal or less size, we
318 # can reuse the same content area of the database. Otherwise, we have
319 # to create a new content area at the EOF.
322 if ( $internal_ref ) {
323 $actual_length = $self->{long_size};
326 my $r = Scalar::Util::reftype( $value ) || '';
327 if ( $r eq 'HASH' || $r eq 'ARRAY' ) {
328 $actual_length = $self->{index_size};
330 # if autobless is enabled, must also take into consideration
331 # the class name, as it is stored along with key/value.
332 if ( $root->{autobless} ) {
333 my $value_class = Scalar::Util::blessed($value);
334 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
335 $actual_length += length($value_class);
339 else { $actual_length = length($value); }
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 if ($actual_length <= $size) {
351 $location = $root->{end};
354 $tag->{offset} + $offset + $self->{hash_size} + $root->{file_offset},
357 print( $fh pack($self->{long_pack}, $location) );
361 elsif ( defined $offset ) {
362 $location = $root->{end};
364 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
365 print( $fh $md5 . pack($self->{long_pack}, $location) );
367 # If bucket didn't fit into list, split into a new index level
369 $self->split_index( $obj, $md5, $tag );
371 $location = $root->{end};
374 $self->write_value( $obj, $location, $plain_key, $value );
381 my ($obj, $location, $key, $value) = @_;
384 my $root = $obj->_root;
386 my $is_dbm_deep = eval {
387 local $SIG{'__DIE__'};
388 $value->isa( 'DBM::Deep' );
391 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
393 seek($fh, $location + $root->{file_offset}, SEEK_SET);
396 # Write signature based on content type, set content length and write
399 my $r = Scalar::Util::reftype($value) || '';
401 if ( $internal_ref ) {
402 print( $fh SIG_INTERNAL );
403 print( $fh pack($self->{data_pack}, $self->{long_size}) );
404 print( $fh pack($self->{long_pack}, $value->_base_offset) );
405 $content_length = $self->{long_size};
409 print( $fh SIG_HASH );
410 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
411 $content_length = $self->{index_size};
413 elsif ($r eq 'ARRAY') {
414 print( $fh SIG_ARRAY );
415 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
416 $content_length = $self->{index_size};
418 elsif (!defined($value)) {
419 print( $fh SIG_NULL );
420 print( $fh pack($self->{data_pack}, 0) );
424 print( $fh SIG_DATA );
425 print( $fh pack($self->{data_pack}, length($value)) . $value );
426 $content_length = length($value);
431 # Plain key is stored AFTER value, as keys are typically fetched less often.
433 print( $fh pack($self->{data_pack}, length($key)) . $key );
436 # If value is blessed, preserve class name
438 if ( $root->{autobless} ) {
439 my $value_class = Scalar::Util::blessed($value);
440 if ( defined $value_class && !$value->isa( 'DBM::Deep' ) ) {
442 # Blessed ref -- will restore later
445 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
446 $content_length += 1;
447 $content_length += $self->{data_size} + length($value_class);
451 $content_length += 1;
456 # If this is a new content area, advance EOF counter
458 if ($location == $root->{end}) {
459 $root->{end} += SIG_SIZE;
460 $root->{end} += $self->{data_size} + $content_length;
461 $root->{end} += $self->{data_size} + length($key);
465 # If content is a hash or array, create new child DBM::Deep object and
466 # pass each key or element to it.
468 if ( ! $internal_ref ) {
470 my $branch = DBM::Deep->new(
471 type => DBM::Deep->TYPE_HASH,
472 base_offset => $location,
475 foreach my $key (keys %{$value}) {
476 $branch->STORE( $key, $value->{$key} );
479 elsif ($r eq 'ARRAY') {
480 my $branch = DBM::Deep->new(
481 type => DBM::Deep->TYPE_ARRAY,
482 base_offset => $location,
486 foreach my $element (@{$value}) {
487 $branch->STORE( $index, $element );
498 my ($obj, $md5, $tag) = @_;
501 my $root = $obj->_root;
502 my $keys = $tag->{content};
504 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
505 print( $fh pack($self->{long_pack}, $root->{end}) );
507 my $index_tag = $self->create_tag(
511 chr(0) x $self->{index_size},
516 $keys .= $md5 . pack($self->{long_pack}, 0);
519 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
520 my ($key, $old_subloc) = $self->_get_key_subloc( $keys, $i );
522 next BUCKET unless $key;
524 my $num = ord(substr($key, $tag->{ch} + 1, 1));
526 if ($offsets[$num]) {
527 my $offset = $offsets[$num] + SIG_SIZE + $self->{data_size};
528 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
530 read( $fh, $subkeys, $self->{bucket_list_size});
532 for (my $k=0; $k<$self->{max_buckets}; $k++) {
533 my ($temp, $subloc) = $self->_get_key_subloc( $subkeys, $k );
536 seek($fh, $offset + ($k * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
537 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
543 $offsets[$num] = $root->{end};
544 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
545 print( $fh pack($self->{long_pack}, $root->{end}) );
547 my $blist_tag = $self->create_tag($obj, $root->{end}, SIG_BLIST, chr(0) x $self->{bucket_list_size});
549 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
550 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
559 my ($obj, $subloc) = @_;
564 # Found match -- seek to offset and read signature
567 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
568 read( $fh, $signature, SIG_SIZE);
571 # If value is a hash or array, return new DBM::Deep object with correct offset
573 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
574 my $obj = DBM::Deep->new(
576 base_offset => $subloc,
580 if ($obj->_root->{autobless}) {
582 # Skip over value and plain key to see if object needs
585 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
588 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
589 if ($size) { seek($fh, $size, SEEK_CUR); }
592 read( $fh, $bless_bit, 1);
593 if (ord($bless_bit)) {
595 # Yes, object needs to be re-blessed
598 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
599 if ($size) { read( $fh, $class_name, $size); }
600 if ($class_name) { $obj = bless( $obj, $class_name ); }
606 elsif ( $signature eq SIG_INTERNAL ) {
608 read( $fh, $size, $self->{data_size});
609 $size = unpack($self->{data_pack}, $size);
613 read( $fh, $new_loc, $size );
614 $new_loc = unpack( $self->{long_pack}, $new_loc );
616 return $self->read_from_loc( $obj, $new_loc );
623 # Otherwise return actual value
625 elsif ($signature eq SIG_DATA) {
627 read( $fh, $size, $self->{data_size});
628 $size = unpack($self->{data_pack}, $size);
631 if ($size) { read( $fh, $value, $size); }
636 # Key exists, but content is null
641 sub get_bucket_value {
643 # Fetch single value given tag and MD5 digested key.
646 my ($obj, $tag, $md5) = @_;
648 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
650 return $self->read_from_loc( $obj, $subloc );
657 # Delete single key/value pair given tag and MD5 digested key.
660 my ($obj, $tag, $md5) = @_;
662 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
665 seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
666 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
667 print( $fh chr(0) x $self->{bucket_size} );
676 # Check existence of single key given tag and MD5 digested key.
679 my ($obj, $tag, $md5) = @_;
681 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
685 sub find_bucket_list {
687 # Locate offset for bucket list, given digested key
690 my ($obj, $md5, $args) = @_;
691 $args = {} unless $args;
694 # Locate offset for bucket list using digest index system
696 my $tag = $self->load_tag($obj, $obj->_base_offset)
697 or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
700 while ($tag->{signature} ne SIG_BLIST) {
701 my $num = ord substr($md5, $ch, 1);
703 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
704 $tag = $self->index_lookup( $obj, $tag, $num );
707 return if ! $args->{create};
710 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
711 print( $fh pack($self->{long_pack}, $obj->_root->{end}) );
713 $tag = $self->create_tag(
714 $obj, $obj->_root->{end},
716 chr(0) x $self->{bucket_list_size},
719 $tag->{ref_loc} = $ref_loc;
726 $tag->{ref_loc} = $ref_loc;
736 # Given index tag, lookup single entry in index and return .
739 my ($obj, $tag, $index) = @_;
741 my $location = unpack(
745 $index * $self->{long_size},
750 if (!$location) { return; }
752 return $self->load_tag( $obj, $location );
757 # Scan index and recursively step into deeper levels, looking for next key.
760 my ($obj, $offset, $ch, $force_return_next) = @_;
762 my $tag = $self->load_tag($obj, $offset );
766 if ($tag->{signature} ne SIG_BLIST) {
767 my $content = $tag->{content};
768 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
770 for (my $idx = $start; $idx < (2**8); $idx++) {
775 $idx * $self->{long_size},
781 my $result = $self->traverse_index(
782 $obj, $subloc, $ch + 1, $force_return_next,
785 if (defined($result)) { return $result; }
789 $obj->{return_next} = 1;
793 my $keys = $tag->{content};
794 if ($force_return_next) { $obj->{return_next} = 1; }
797 # Iterate through buckets, looking for a key match
799 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
800 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
802 # End of bucket list -- return to outer loop
804 $obj->{return_next} = 1;
807 # Located previous key -- return next one found
808 elsif ($key eq $obj->{prev_md5}) {
809 $obj->{return_next} = 1;
812 # Seek to bucket location and skip over signature
813 elsif ($obj->{return_next}) {
814 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
816 # Skip over value to get to plain key
818 read( $fh, $sig, SIG_SIZE );
821 read( $fh, $size, $self->{data_size});
822 $size = unpack($self->{data_pack}, $size);
823 if ($size) { seek($fh, $size, SEEK_CUR); }
825 # Read in plain key and return as scalar
827 read( $fh, $size, $self->{data_size});
828 $size = unpack($self->{data_pack}, $size);
829 if ($size) { read( $fh, $plain_key, $size); }
835 $obj->{return_next} = 1;
836 } # tag is a bucket list
843 # Locate next key, given digested previous one
848 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
849 $obj->{return_next} = 0;
852 # If the previous key was not specifed, start at the top and
853 # return the first one found.
855 if (!$obj->{prev_md5}) {
856 $obj->{prev_md5} = chr(0) x $self->{hash_size};
857 $obj->{return_next} = 1;
860 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
865 sub _get_key_subloc {
867 my ($keys, $idx) = @_;
869 my ($key, $subloc) = unpack(
870 "a$self->{hash_size} $self->{long_pack}",
873 ($idx * $self->{bucket_size}),
874 $self->{bucket_size},
878 return ($key, $subloc);
881 sub _find_in_buckets {
883 my ($tag, $md5) = @_;
886 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
887 my ($key, $subloc) = $self->_get_key_subloc( $tag->{content}, $i );
889 return ($subloc, $i * $self->{bucket_size}) unless $subloc;
891 next BUCKET if $key ne $md5;
893 return ($subloc, $i * $self->{bucket_size});
901 my ($obj, $size) = @_;
903 my $loc = $obj->_root->{end};
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);