1 package DBM::Deep::Engine;
5 use Fcntl qw( :DEFAULT :flock :seek );
8 # Set to 4 and 'N' for 32-bit offset tags (default). Theoretical limit of 4 GB per file.
9 # (Perl must be compiled with largefile support for files > 2 GB)
11 # Set to 8 and 'Q' for 64-bit offsets. Theoretical limit of 16 XB per file.
12 # (Perl must be compiled with largefile and 64-bit long support)
15 # Set to 4 and 'N' for 32-bit data length prefixes. Limit of 4 GB for each key/value.
16 # Upgrading this is possible (see above) but probably not necessary. If you need
17 # more than 4 GB for a single key or value, this module is really not for you :-)
19 our ($LONG_SIZE, $LONG_PACK, $DATA_LENGTH_SIZE, $DATA_LENGTH_PACK);
21 # Maximum number of buckets per list before another level of indexing is done.
22 # Increase this value for slightly greater speed, but larger database files.
23 # DO NOT decrease this value below 16, due to risk of recursive reindex overrun.
25 our $MAX_BUCKETS = 16;
27 our ($BUCKET_SIZE, $BUCKET_LIST_SIZE);
32 # Precalculate index, bucket and bucket list sizes
35 #XXX I don't like this ...
36 set_pack() unless defined $LONG_SIZE;
38 $BUCKET_SIZE = $HASH_SIZE + $LONG_SIZE;
39 $BUCKET_LIST_SIZE = $MAX_BUCKETS * $BUCKET_SIZE;
44 # Set pack/unpack modes (see file header for more)
46 my ($long_s, $long_p, $data_s, $data_p) = @_;
48 $LONG_SIZE = $long_s ? $long_s : 4;
49 $LONG_PACK = $long_p ? $long_p : 'N';
51 $DATA_LENGTH_SIZE = $data_s ? $data_s : 4;
52 $DATA_LENGTH_PACK = $data_p ? $data_p : 'N';
60 # Set key digest function (default is MD5)
62 my ($digest_func, $hash_size) = @_;
64 $self->{digest} = $digest_func ? $digest_func : \&Digest::MD5::md5;
66 $HASH_SIZE = $hash_size ? $hash_size : 16;
80 digest => \&Digest::MD5::md5,
85 $self->{index_size} = (2**8) * $self->{long_size};
86 $self->{bucket_size} = $self->{hash_size} + $self->{long_size};
87 $self->{bucket_list_size} = $self->{max_buckets} * $self->{bucket_size};
96 $self->open( $obj ) if !defined $obj->_fh;
98 #XXX Is {end} busted? Can't we just seek( $fh, 0, SEEK_END ) ?
99 unless ( $obj->_root->{inode} ) {
100 my @stats = stat($obj->_fh);
101 $obj->_root->{inode} = $stats[1];
102 $obj->_root->{end} = $stats[7];
110 # Open a fh to the database, create if nonexistent.
111 # Make sure file signature matches DBM::Deep spec.
116 if (defined($obj->_fh)) { $self->close( $obj ); }
119 local $SIG{'__DIE__'};
120 # Theoretically, adding O_BINARY should remove the need for the binmode
121 # Of course, testing it is going to be ... interesting.
122 my $flags = O_RDWR | O_CREAT | O_BINARY;
125 sysopen( $fh, $obj->_root->{file}, $flags )
127 $obj->_root->{fh} = $fh;
128 }; if ($@ ) { $obj->_throw_error( "Received error: $@\n" ); }
129 if (! defined($obj->_fh)) {
130 return $obj->_throw_error("Cannot sysopen file: " . $obj->_root->{file} . ": $!");
135 #XXX Can we remove this by using the right sysopen() flags?
136 # Maybe ... q.v. above
137 binmode $fh; # for win32
139 if ($obj->_root->{autoflush}) {
140 my $old = select $fh;
145 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
148 my $bytes_read = read( $fh, $signature, length(DBM::Deep->SIG_FILE));
151 # File is empty -- write signature and master index
154 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
155 print( $fh DBM::Deep->SIG_FILE);
156 $self->create_tag($obj, $obj->_base_offset, $obj->_type, chr(0) x $self->{index_size});
158 my $plain_key = "[base]";
159 print( $fh pack($DATA_LENGTH_PACK, length($plain_key)) . $plain_key );
161 # Flush the filehandle
162 my $old_fh = select $fh;
163 my $old_af = $|; $| = 1; $| = $old_af;
170 # Check signature was valid
172 unless ($signature eq DBM::Deep->SIG_FILE) {
173 $self->close( $obj );
174 return $obj->_throw_error("Signature not found -- file is not a Deep DB");
178 # Get our type from master index signature
180 my $tag = $self->load_tag($obj, $obj->_base_offset);
182 #XXX We probably also want to store the hash algorithm name and not assume anything
183 #XXX The cool thing would be to allow a different hashing algorithm at every level
186 return $obj->_throw_error("Corrupted file, no master index record");
188 if ($obj->{type} ne $tag->{signature}) {
189 return $obj->_throw_error("File type mismatch");
199 if ( my $fh = $obj->_root->{fh} ) {
202 $obj->_root->{fh} = undef;
209 # Given offset, signature and content, create tag and write to disk
212 my ($obj, $offset, $sig, $content) = @_;
213 my $size = length($content);
217 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
218 print( $fh $sig . pack($DATA_LENGTH_PACK, $size) . $content );
220 if ($offset == $obj->_root->{end}) {
221 $obj->_root->{end} += DBM::Deep->SIG_SIZE + $DATA_LENGTH_SIZE + $size;
227 offset => $offset + DBM::Deep->SIG_SIZE + $DATA_LENGTH_SIZE,
234 # Given offset, load single tag and return signature, size and data
237 my ($obj, $offset) = @_;
241 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
242 if (eof $fh) { return undef; }
245 read( $fh, $b, DBM::Deep->SIG_SIZE + $DATA_LENGTH_SIZE );
246 my ($sig, $size) = unpack( "A $DATA_LENGTH_PACK", $b );
249 read( $fh, $buffer, $size);
254 offset => $offset + DBM::Deep->SIG_SIZE + $DATA_LENGTH_SIZE,
261 # Given index tag, lookup single entry in index and return .
264 my ($obj, $tag, $index) = @_;
266 my $location = unpack($LONG_PACK, substr($tag->{content}, $index * $LONG_SIZE, $LONG_SIZE) );
267 if (!$location) { return; }
269 return $self->load_tag( $obj, $location );
274 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
275 # plain (undigested) key and value.
278 my ($obj, $tag, $md5, $plain_key, $value) = @_;
279 my $keys = $tag->{content};
283 my $root = $obj->_root;
285 my $is_dbm_deep = eval { local $SIG{'__DIE__'}; $value->isa( 'DBM::Deep' ) };
286 my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
291 # Iterate through buckets, seeing if this is a new entry or a replace.
293 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
294 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
297 # Found empty bucket (end of list). Populate and exit loop.
301 $location = $internal_ref
302 ? $value->_base_offset
305 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE) + $root->{file_offset}, SEEK_SET);
306 print( $fh $md5 . pack($LONG_PACK, $location) );
310 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
313 # Found existing bucket with same key. Replace with new value.
318 $location = $value->_base_offset;
319 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE) + $root->{file_offset}, SEEK_SET);
320 print( $fh $md5 . pack($LONG_PACK, $location) );
324 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $root->{file_offset}, SEEK_SET);
326 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
329 # If value is a hash, array, or raw value with equal or less size, we can
330 # reuse the same content area of the database. Otherwise, we have to create
331 # a new content area at the EOF.
334 my $r = Scalar::Util::reftype( $value ) || '';
335 if ( $r eq 'HASH' || $r eq 'ARRAY' ) {
336 $actual_length = $self->{index_size};
338 # if autobless is enabled, must also take into consideration
339 # the class name, as it is stored along with key/value.
340 if ( $root->{autobless} ) {
341 my $value_class = Scalar::Util::blessed($value);
342 if ( defined $value_class && !$value->isa('DBM::Deep') ) {
343 $actual_length += length($value_class);
347 else { $actual_length = length($value); }
349 if ($actual_length <= $size) {
353 $location = $root->{end};
354 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE) + $HASH_SIZE + $root->{file_offset}, SEEK_SET);
355 print( $fh pack($LONG_PACK, $location) );
363 # If this is an internal reference, return now.
364 # No need to write value or plain key
371 # If bucket didn't fit into list, split into a new index level
374 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
375 print( $fh pack($LONG_PACK, $root->{end}) );
377 my $index_tag = $self->create_tag($obj, $root->{end}, DBM::Deep->SIG_INDEX, chr(0) x $self->{index_size});
380 $keys .= $md5 . pack($LONG_PACK, 0);
382 for (my $i=0; $i<=$MAX_BUCKETS; $i++) {
383 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
385 my $old_subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) +
386 $HASH_SIZE, $LONG_SIZE));
387 my $num = ord(substr($key, $tag->{ch} + 1, 1));
389 if ($offsets[$num]) {
390 my $offset = $offsets[$num] + DBM::Deep->SIG_SIZE + $DATA_LENGTH_SIZE;
391 seek($fh, $offset + $root->{file_offset}, SEEK_SET);
393 read( $fh, $subkeys, $BUCKET_LIST_SIZE);
395 for (my $k=0; $k<$MAX_BUCKETS; $k++) {
396 my $subloc = unpack($LONG_PACK, substr($subkeys, ($k * $BUCKET_SIZE) +
397 $HASH_SIZE, $LONG_SIZE));
399 seek($fh, $offset + ($k * $BUCKET_SIZE) + $root->{file_offset}, SEEK_SET);
400 print( $fh $key . pack($LONG_PACK, $old_subloc || $root->{end}) );
406 $offsets[$num] = $root->{end};
407 seek($fh, $index_tag->{offset} + ($num * $LONG_SIZE) + $root->{file_offset}, SEEK_SET);
408 print( $fh pack($LONG_PACK, $root->{end}) );
410 my $blist_tag = $self->create_tag($obj, $root->{end}, DBM::Deep->SIG_BLIST, chr(0) x $BUCKET_LIST_SIZE);
412 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
413 print( $fh $key . pack($LONG_PACK, $old_subloc || $root->{end}) );
418 $location ||= $root->{end};
419 } # re-index bucket list
422 # Seek to content area and store signature, value and plaintext key
426 seek($fh, $location + $root->{file_offset}, SEEK_SET);
429 # Write signature based on content type, set content length and write actual value.
431 my $r = Scalar::Util::reftype($value) || '';
433 print( $fh DBM::Deep->TYPE_HASH );
434 print( $fh pack($DATA_LENGTH_PACK, $self->{index_size}) . chr(0) x $self->{index_size} );
435 $content_length = $self->{index_size};
437 elsif ($r eq 'ARRAY') {
438 print( $fh DBM::Deep->TYPE_ARRAY );
439 print( $fh pack($DATA_LENGTH_PACK, $self->{index_size}) . chr(0) x $self->{index_size} );
440 $content_length = $self->{index_size};
442 elsif (!defined($value)) {
443 print( $fh DBM::Deep->SIG_NULL );
444 print( $fh pack($DATA_LENGTH_PACK, 0) );
448 print( $fh DBM::Deep->SIG_DATA );
449 print( $fh pack($DATA_LENGTH_PACK, length($value)) . $value );
450 $content_length = length($value);
454 # Plain key is stored AFTER value, as keys are typically fetched less often.
456 print( $fh pack($DATA_LENGTH_PACK, length($plain_key)) . $plain_key );
459 # If value is blessed, preserve class name
461 if ( $root->{autobless} ) {
462 my $value_class = Scalar::Util::blessed($value);
463 if ( defined $value_class && $value_class ne 'DBM::Deep' ) {
465 # Blessed ref -- will restore later
468 print( $fh pack($DATA_LENGTH_PACK, length($value_class)) . $value_class );
469 $content_length += 1;
470 $content_length += $DATA_LENGTH_SIZE + length($value_class);
474 $content_length += 1;
479 # If this is a new content area, advance EOF counter
481 if ($location == $root->{end}) {
482 $root->{end} += DBM::Deep->SIG_SIZE;
483 $root->{end} += $DATA_LENGTH_SIZE + $content_length;
484 $root->{end} += $DATA_LENGTH_SIZE + length($plain_key);
488 # If content is a hash or array, create new child DBM::Deep object and
489 # pass each key or element to it.
492 my $branch = DBM::Deep->new(
493 type => DBM::Deep->TYPE_HASH,
494 base_offset => $location,
497 foreach my $key (keys %{$value}) {
498 $branch->STORE( $key, $value->{$key} );
501 elsif ($r eq 'ARRAY') {
502 my $branch = DBM::Deep->new(
503 type => DBM::Deep->TYPE_ARRAY,
504 base_offset => $location,
508 foreach my $element (@{$value}) {
509 $branch->STORE( $index, $element );
517 return $obj->_throw_error("Fatal error: indexing failed -- possibly due to corruption in file");
520 sub get_bucket_value {
522 # Fetch single value given tag and MD5 digested key.
525 my ($obj, $tag, $md5) = @_;
526 my $keys = $tag->{content};
531 # Iterate through buckets, looking for a key match
534 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
535 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
536 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
540 # Hit end of list, no match
545 if ( $md5 ne $key ) {
550 # Found match -- seek to offset and read signature
553 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
554 read( $fh, $signature, DBM::Deep->SIG_SIZE);
557 # If value is a hash or array, return new DBM::Deep object with correct offset
559 if (($signature eq DBM::Deep->TYPE_HASH) || ($signature eq DBM::Deep->TYPE_ARRAY)) {
560 my $obj = DBM::Deep->new(
562 base_offset => $subloc,
566 if ($obj->_root->{autobless}) {
568 # Skip over value and plain key to see if object needs
571 seek($fh, $DATA_LENGTH_SIZE + $self->{index_size}, SEEK_CUR);
574 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
575 if ($size) { seek($fh, $size, SEEK_CUR); }
578 read( $fh, $bless_bit, 1);
579 if (ord($bless_bit)) {
581 # Yes, object needs to be re-blessed
584 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
585 if ($size) { read( $fh, $class_name, $size); }
586 if ($class_name) { $obj = bless( $obj, $class_name ); }
594 # Otherwise return actual value
596 elsif ($signature eq DBM::Deep->SIG_DATA) {
599 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
600 if ($size) { read( $fh, $value, $size); }
605 # Key exists, but content is null
615 # Delete single key/value pair given tag and MD5 digested key.
618 my ($obj, $tag, $md5) = @_;
619 my $keys = $tag->{content};
624 # Iterate through buckets, looking for a key match
627 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
628 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
629 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
633 # Hit end of list, no match
638 if ( $md5 ne $key ) {
643 # Matched key -- delete bucket and return
645 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE) + $obj->_root->{file_offset}, SEEK_SET);
646 print( $fh substr($keys, ($i+1) * $BUCKET_SIZE ) );
647 print( $fh chr(0) x $BUCKET_SIZE );
657 # Check existence of single key given tag and MD5 digested key.
660 my ($obj, $tag, $md5) = @_;
661 my $keys = $tag->{content};
664 # Iterate through buckets, looking for a key match
667 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
668 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
669 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
673 # Hit end of list, no match
678 if ( $md5 ne $key ) {
683 # Matched key -- return true
691 sub find_bucket_list {
693 # Locate offset for bucket list, given digested key
696 my ($obj, $md5) = @_;
699 # Locate offset for bucket list using digest index system
702 my $tag = $self->load_tag($obj, $obj->_base_offset);
703 if (!$tag) { return; }
705 while ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
706 $tag = $self->index_lookup($obj, $tag, ord(substr($md5, $ch, 1)));
707 if (!$tag) { return; }
716 # Scan index and recursively step into deeper levels, looking for next key.
719 my ($obj, $offset, $ch, $force_return_next) = @_;
720 $force_return_next = undef unless $force_return_next;
722 my $tag = $self->load_tag($obj, $offset );
726 if ($tag->{signature} ne DBM::Deep->SIG_BLIST) {
727 my $content = $tag->{content};
729 if ($obj->{return_next}) { $start = 0; }
730 else { $start = ord(substr($obj->{prev_md5}, $ch, 1)); }
732 for (my $index = $start; $index < 256; $index++) {
733 my $subloc = unpack($LONG_PACK, substr($content, $index * $LONG_SIZE, $LONG_SIZE) );
735 my $result = $self->traverse_index( $obj, $subloc, $ch + 1, $force_return_next );
736 if (defined($result)) { return $result; }
740 $obj->{return_next} = 1;
743 elsif ($tag->{signature} eq DBM::Deep->SIG_BLIST) {
744 my $keys = $tag->{content};
745 if ($force_return_next) { $obj->{return_next} = 1; }
748 # Iterate through buckets, looking for a key match
750 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
751 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
752 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
756 # End of bucket list -- return to outer loop
758 $obj->{return_next} = 1;
761 elsif ($key eq $obj->{prev_md5}) {
763 # Located previous key -- return next one found
765 $obj->{return_next} = 1;
768 elsif ($obj->{return_next}) {
770 # Seek to bucket location and skip over signature
772 seek($fh, $subloc + DBM::Deep->SIG_SIZE + $obj->_root->{file_offset}, SEEK_SET);
775 # Skip over value to get to plain key
778 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
779 if ($size) { seek($fh, $size, SEEK_CUR); }
782 # Read in plain key and return as scalar
785 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
786 if ($size) { read( $fh, $plain_key, $size); }
792 $obj->{return_next} = 1;
793 } # tag is a bucket list
800 # Locate next key, given digested previous one
805 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
806 $obj->{return_next} = 0;
809 # If the previous key was not specifed, start at the top and
810 # return the first one found.
812 if (!$obj->{prev_md5}) {
813 $obj->{prev_md5} = chr(0) x $HASH_SIZE;
814 $obj->{return_next} = 1;
817 return $self->traverse_index( $obj, $obj->_base_offset, 0 );