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_REF () { 'R' }
15 sub SIG_NULL () { 'N' }
16 sub SIG_DATA () { 'D' }
17 sub SIG_INDEX () { 'I' }
18 sub SIG_BLIST () { 'B' }
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};
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;
111 #XXX We have to make sure we don't mess up when autoflush isn't turned on
112 unless ( $obj->_root->{inode} ) {
113 my @stats = stat($obj->_fh);
114 $obj->_root->{inode} = $stats[1];
115 $obj->_root->{end} = $stats[7];
123 # Open a fh to the database, create if nonexistent.
124 # Make sure file signature matches DBM::Deep spec.
129 if (defined($obj->_fh)) { $self->close_fh( $obj ); }
131 # Theoretically, adding O_BINARY should remove the need for the binmode
132 # Of course, testing it is going to be ... interesting.
133 my $flags = O_RDWR | O_CREAT | O_BINARY;
136 my $filename = $obj->_root->{file};
137 sysopen( $fh, $filename, $flags )
138 or $obj->_throw_error("Cannot sysopen file '$filename': $!");
139 $obj->_root->{fh} = $fh;
141 #XXX Can we remove this by using the right sysopen() flags?
142 # Maybe ... q.v. above
143 binmode $fh; # for win32
145 if ($obj->_root->{autoflush}) {
146 my $old = select $fh;
151 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
153 my $bytes_read = read( $fh, $signature, length(SIG_FILE));
156 # File is empty -- write signature and master index
159 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
160 print( $fh SIG_FILE);
163 $obj, $obj->_base_offset, $obj->_type,
164 chr(0) x $self->{index_size},
167 # Flush the filehandle
168 my $old_fh = select $fh;
169 my $old_af = $|; $| = 1; $| = $old_af;
176 # Check signature was valid
178 unless ($signature eq SIG_FILE) {
179 $self->close_fh( $obj );
180 $obj->_throw_error("Signature not found -- file is not a Deep DB");
184 # Get our type from master index signature
186 my $tag = $self->load_tag($obj, $obj->_base_offset)
187 or $obj->_throw_error("Corrupted file, no master index record");
189 unless ($obj->{type} eq $tag->{signature}) {
190 $obj->_throw_error("File type mismatch");
193 #XXX We probably also want to store the hash algorithm name and not assume anything
194 #XXX The cool thing would be to allow a different hashing algorithm at every level
203 if ( my $fh = $obj->_root->{fh} ) {
206 $obj->_root->{fh} = undef;
213 # Given offset, signature and content, create tag and write to disk
216 my ($obj, $offset, $sig, $content) = @_;
217 my $size = length($content);
221 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
222 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
224 if ($offset == $obj->_root->{end}) {
225 $obj->_root->{end} += SIG_SIZE + $self->{data_size} + $size;
231 offset => $offset + SIG_SIZE + $self->{data_size},
238 # Given offset, load single tag and return signature, size and data
241 my ($obj, $offset) = @_;
245 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
247 #XXX I'm not sure this check will work if autoflush isn't enabled ...
251 read( $fh, $b, SIG_SIZE + $self->{data_size} );
252 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
255 read( $fh, $buffer, $size);
260 offset => $offset + SIG_SIZE + $self->{data_size},
267 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
268 # plain (undigested) key and value.
271 my ($obj, $tag, $md5, $plain_key, $value) = @_;
273 # This verifies that only supported values will be stored.
275 my $r = Scalar::Util::reftype( $value );
278 last if $r eq 'HASH';
279 last if $r eq 'ARRAY';
282 "Storage of variables of type '$r' is not supported."
289 my $root = $obj->_root;
291 my $is_dbm_deep = eval {
292 local $SIG{'__DIE__'};
293 $value->isa( 'DBM::Deep' );
296 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
300 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
302 # Updating a known md5
307 # If value is a hash, array, or raw value with equal or less size, we
308 # can reuse the same content area of the database. Otherwise, we have
309 # to create a new content area at the EOF.
312 if ( $internal_ref ) {
313 $actual_length = $self->{long_size};
316 my $r = Scalar::Util::reftype( $value ) || '';
317 if ( $r eq 'HASH' || $r eq 'ARRAY' ) {
318 $actual_length = $self->{index_size};
320 # if autobless is enabled, must also take into consideration
321 # the class name, as it is stored along with key/value.
322 if ( $root->{autobless} ) {
323 my $value_class = Scalar::Util::blessed($value);
324 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
325 $actual_length += length($value_class);
329 else { $actual_length = length($value); }
332 seek($fh, $subloc + SIG_SIZE + $root->{file_offset}, SEEK_SET);
334 read( $fh, $size, $self->{data_size});
335 $size = unpack($self->{data_pack}, $size);
337 if ($actual_length <= $size) {
341 $location = $root->{end};
344 $tag->{offset} + $offset + $self->{hash_size} + $root->{file_offset},
347 print( $fh pack($self->{long_pack}, $location) );
351 elsif ( defined $offset ) {
352 $location = $root->{end};
354 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
355 print( $fh $md5 . pack($self->{long_pack}, $location) );
357 # If bucket didn't fit into list, split into a new index level
359 $self->split_index( $obj, $md5, $tag );
361 $location = $root->{end};
364 $self->write_value( $obj, $location, $plain_key, $value );
371 my ($obj, $location, $key, $value) = @_;
374 my $root = $obj->_root;
376 my $is_dbm_deep = eval {
377 local $SIG{'__DIE__'};
378 $value->isa( 'DBM::Deep' );
381 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
383 seek($fh, $location + $root->{file_offset}, SEEK_SET);
386 # Write signature based on content type, set content length and write
389 my $r = Scalar::Util::reftype($value) || '';
391 if ( $internal_ref ) {
392 print( $fh SIG_INTERNAL );
393 print( $fh pack($self->{data_pack}, $self->{long_size}) );
394 print( $fh pack($self->{long_pack}, $value->_base_offset) );
395 $content_length = $self->{long_size};
399 print( $fh SIG_HASH );
400 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
401 $content_length = $self->{index_size};
403 elsif ($r eq 'ARRAY') {
404 print( $fh SIG_ARRAY );
405 print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
406 $content_length = $self->{index_size};
408 elsif (!defined($value)) {
409 print( $fh SIG_NULL );
410 print( $fh pack($self->{data_pack}, 0) );
414 print( $fh SIG_DATA );
415 print( $fh pack($self->{data_pack}, length($value)) . $value );
416 $content_length = length($value);
421 # Plain key is stored AFTER value, as keys are typically fetched less often.
423 print( $fh pack($self->{data_pack}, length($key)) . $key );
426 # If value is blessed, preserve class name
428 if ( $root->{autobless} ) {
429 my $value_class = Scalar::Util::blessed($value);
430 if ( defined $value_class && !$value->isa( 'DBM::Deep' ) ) {
432 # Blessed ref -- will restore later
435 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
436 $content_length += 1;
437 $content_length += $self->{data_size} + length($value_class);
441 $content_length += 1;
446 # If this is a new content area, advance EOF counter
448 if ($location == $root->{end}) {
449 $root->{end} += SIG_SIZE;
450 $root->{end} += $self->{data_size} + $content_length;
451 $root->{end} += $self->{data_size} + length($key);
455 # If content is a hash or array, create new child DBM::Deep object and
456 # pass each key or element to it.
458 if ( ! $internal_ref ) {
460 my $branch = DBM::Deep->new(
461 type => DBM::Deep->TYPE_HASH,
462 base_offset => $location,
465 foreach my $key (keys %{$value}) {
466 $branch->STORE( $key, $value->{$key} );
469 elsif ($r eq 'ARRAY') {
470 my $branch = DBM::Deep->new(
471 type => DBM::Deep->TYPE_ARRAY,
472 base_offset => $location,
476 foreach my $element (@{$value}) {
477 $branch->STORE( $index, $element );
488 my ($obj, $md5, $tag) = @_;
491 my $root = $obj->_root;
492 my $keys = $tag->{content};
494 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
495 print( $fh pack($self->{long_pack}, $root->{end}) );
497 my $index_tag = $self->create_tag(
501 chr(0) x $self->{index_size},
506 $keys .= $md5 . pack($self->{long_pack}, 0);
509 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
510 my ($key, $old_subloc) = $self->_get_key_subloc( $keys, $i );
512 next BUCKET unless $key;
514 my $num = ord(substr($key, $tag->{ch} + 1, 1));
516 if ($offsets[$num]) {
517 my $offset = $offsets[$num] + SIG_SIZE + $self->{data_size};
518 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
520 read( $fh, $subkeys, $self->{bucket_list_size});
522 for (my $k=0; $k<$self->{max_buckets}; $k++) {
523 my ($temp, $subloc) = $self->_get_key_subloc( $subkeys, $k );
526 seek($fh, $offset + ($k * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
527 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
533 $offsets[$num] = $root->{end};
534 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
535 print( $fh pack($self->{long_pack}, $root->{end}) );
537 my $blist_tag = $self->create_tag($obj, $root->{end}, SIG_BLIST, chr(0) x $self->{bucket_list_size});
539 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
540 print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
549 my ($obj, $subloc) = @_;
554 # Found match -- seek to offset and read signature
557 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
558 read( $fh, $signature, SIG_SIZE);
561 # If value is a hash or array, return new DBM::Deep object with correct offset
563 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
564 my $obj = DBM::Deep->new(
566 base_offset => $subloc,
570 if ($obj->_root->{autobless}) {
572 # Skip over value and plain key to see if object needs
575 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
578 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
579 if ($size) { seek($fh, $size, SEEK_CUR); }
582 read( $fh, $bless_bit, 1);
583 if (ord($bless_bit)) {
585 # Yes, object needs to be re-blessed
588 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
589 if ($size) { read( $fh, $class_name, $size); }
590 if ($class_name) { $obj = bless( $obj, $class_name ); }
596 elsif ( $signature eq SIG_INTERNAL ) {
598 read( $fh, $size, $self->{data_size});
599 $size = unpack($self->{data_pack}, $size);
603 read( $fh, $new_loc, $size );
604 $new_loc = unpack( $self->{long_pack}, $new_loc );
606 return $self->read_from_loc( $obj, $new_loc );
613 # Otherwise return actual value
615 elsif ($signature eq SIG_DATA) {
617 read( $fh, $size, $self->{data_size});
618 $size = unpack($self->{data_pack}, $size);
621 if ($size) { read( $fh, $value, $size); }
626 # Key exists, but content is null
631 sub get_bucket_value {
633 # Fetch single value given tag and MD5 digested key.
636 my ($obj, $tag, $md5) = @_;
638 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
640 return $self->read_from_loc( $obj, $subloc );
647 # Delete single key/value pair given tag and MD5 digested key.
650 my ($obj, $tag, $md5) = @_;
652 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
655 seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
656 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
657 print( $fh chr(0) x $self->{bucket_size} );
666 # Check existence of single key given tag and MD5 digested key.
669 my ($obj, $tag, $md5) = @_;
671 my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
675 sub find_bucket_list {
677 # Locate offset for bucket list, given digested key
680 my ($obj, $md5, $args) = @_;
681 $args = {} unless $args;
684 # Locate offset for bucket list using digest index system
686 my $tag = $self->load_tag($obj, $obj->_base_offset)
687 or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
690 while ($tag->{signature} ne SIG_BLIST) {
691 my $num = ord substr($md5, $ch, 1);
693 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
694 $tag = $self->index_lookup( $obj, $tag, $num );
697 return if ! $args->{create};
700 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
701 print( $fh pack($self->{long_pack}, $obj->_root->{end}) );
703 $tag = $self->create_tag(
704 $obj, $obj->_root->{end},
706 chr(0) x $self->{bucket_list_size},
709 $tag->{ref_loc} = $ref_loc;
716 $tag->{ref_loc} = $ref_loc;
726 # Given index tag, lookup single entry in index and return .
729 my ($obj, $tag, $index) = @_;
731 my $location = unpack(
735 $index * $self->{long_size},
740 if (!$location) { return; }
742 return $self->load_tag( $obj, $location );
747 # Scan index and recursively step into deeper levels, looking for next key.
750 my ($obj, $offset, $ch, $force_return_next) = @_;
752 my $tag = $self->load_tag($obj, $offset );
756 if ($tag->{signature} ne SIG_BLIST) {
757 my $content = $tag->{content};
758 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
760 for (my $idx = $start; $idx < (2**8); $idx++) {
763 substr($content, $idx * $self->{long_size}, $self->{long_size}),
767 my $result = $self->traverse_index(
768 $obj, $subloc, $ch + 1, $force_return_next,
771 if (defined($result)) { return $result; }
775 $obj->{return_next} = 1;
779 my $keys = $tag->{content};
780 if ($force_return_next) { $obj->{return_next} = 1; }
783 # Iterate through buckets, looking for a key match
785 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
786 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
788 # End of bucket list -- return to outer loop
790 $obj->{return_next} = 1;
793 # Located previous key -- return next one found
794 elsif ($key eq $obj->{prev_md5}) {
795 $obj->{return_next} = 1;
798 # Seek to bucket location and skip over signature
799 elsif ($obj->{return_next}) {
800 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
802 # Skip over value to get to plain key
804 read( $fh, $sig, SIG_SIZE );
807 read( $fh, $size, $self->{data_size});
808 $size = unpack($self->{data_pack}, $size);
809 if ($size) { seek($fh, $size, SEEK_CUR); }
811 # Read in plain key and return as scalar
813 read( $fh, $size, $self->{data_size});
814 $size = unpack($self->{data_pack}, $size);
815 if ($size) { read( $fh, $plain_key, $size); }
821 $obj->{return_next} = 1;
822 } # tag is a bucket list
829 # Locate next key, given digested previous one
834 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
835 $obj->{return_next} = 0;
838 # If the previous key was not specifed, start at the top and
839 # return the first one found.
841 if (!$obj->{prev_md5}) {
842 $obj->{prev_md5} = chr(0) x $self->{hash_size};
843 $obj->{return_next} = 1;
846 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
851 sub _get_key_subloc {
853 my ($keys, $idx) = @_;
855 my ($key, $subloc) = unpack(
856 "a$self->{hash_size} $self->{long_pack}",
859 ($idx * $self->{bucket_size}),
860 $self->{bucket_size},
864 return ($key, $subloc);
867 sub _find_in_buckets {
869 my ($tag, $md5) = @_;
872 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
873 my ($key, $subloc) = $self->_get_key_subloc( $tag->{content}, $i );
875 return ($subloc, $i * $self->{bucket_size}) unless $subloc;
877 next BUCKET if $key ne $md5;
879 return ($subloc, $i * $self->{bucket_size});
888 # This will be added in later, after more refactoring is done. This is an early
889 # attempt at refactoring on the physical level instead of the virtual level.
892 my ($obj, $spot, $amount, $unpack) = @_;
895 seek( $fh, $spot + $obj->_root->{file_offset}, SEEK_SET );
898 my $bytes_read = read( $fh, $buffer, $amount );
901 $buffer = unpack( $unpack, $buffer );
905 return ($buffer, $bytes_read);