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;
105 sub write_file_signature {
111 my $loc = $self->_request_space(
112 $obj, length( SIG_FILE ) + $self->{data_size},
114 seek($fh, $loc + $obj->_root->{file_offset}, SEEK_SET);
115 print( $fh SIG_FILE, pack($self->{data_pack}, 0) );
120 sub read_file_signature {
126 seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
128 my $bytes_read = read(
129 $fh, $buffer, length(SIG_FILE) + $self->{data_size},
133 my ($signature, $version) = unpack( "A4 $self->{data_pack}", $buffer );
134 unless ($signature eq SIG_FILE) {
135 $self->close_fh( $obj );
136 $obj->_throw_error("Signature not found -- file is not a Deep DB");
147 $self->open( $obj ) if !defined $obj->_fh;
152 unless ( $obj->{base_offset} ) {
153 my $bytes_read = $self->read_file_signature( $obj );
156 # File is empty -- write signature and master index
159 $self->write_file_signature( $obj );
161 $obj->{base_offset} = $self->_request_space(
162 $obj, $self->tag_size( $self->{index_size} ),
166 $obj, $obj->_base_offset, $obj->_type,
167 chr(0)x$self->{index_size},
170 # Flush the filehandle
171 my $old_fh = select $fh;
172 my $old_af = $|; $| = 1; $| = $old_af;
176 $obj->{base_offset} = $bytes_read;
179 # Get our type from master index signature
181 my $tag = $self->load_tag($obj, $obj->_base_offset)
182 or $obj->_throw_error("Corrupted file, no master index record");
184 unless ($obj->{type} eq $tag->{signature}) {
185 $obj->_throw_error("File type mismatch");
190 #XXX We have to make sure we don't mess up when autoflush isn't turned on
191 unless ( $obj->_root->{inode} ) {
192 my @stats = stat($obj->_fh);
193 $obj->_root->{inode} = $stats[1];
194 $obj->_root->{end} = $stats[7];
204 # Open a fh to the database, create if nonexistent.
205 # Make sure file signature matches DBM::Deep spec.
210 # Theoretically, adding O_BINARY should remove the need for the binmode
211 # Of course, testing it is going to be ... interesting.
212 my $flags = O_RDWR | O_CREAT | O_BINARY;
215 my $filename = $obj->_root->{file};
216 sysopen( $fh, $filename, $flags )
217 or $obj->_throw_error("Cannot sysopen file '$filename': $!");
218 $obj->_root->{fh} = $fh;
220 # Even though we use O_BINARY, better be safe than sorry.
223 if ($obj->_root->{autoflush}) {
224 my $old = select $fh;
236 if ( my $fh = $obj->_root->{fh} ) {
239 $obj->_root->{fh} = undef;
247 return SIG_SIZE + $self->{data_size} + $size;
252 # Given offset, signature and content, create tag and write to disk
255 my ($obj, $offset, $sig, $content) = @_;
256 my $size = length( $content );
260 if ( defined $offset ) {
261 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
264 print( $fh $sig . pack($self->{data_pack}, $size) . $content );
266 return unless defined $offset;
271 offset => $offset + SIG_SIZE + $self->{data_size},
278 # Given offset, load single tag and return signature, size and data
281 my ($obj, $offset) = @_;
283 # print join(':',map{$_||''}caller(1)), $/;
287 seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
289 #XXX I'm not sure this check will work if autoflush isn't enabled ...
293 read( $fh, $b, SIG_SIZE + $self->{data_size} );
294 my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
297 read( $fh, $buffer, $size);
302 offset => $offset + SIG_SIZE + $self->{data_size},
309 my ($obj, $value, $key) = @_;
311 my $is_dbm_deep = eval {
312 local $SIG{'__DIE__'};
313 $value->isa( 'DBM::Deep' );
316 my $len = SIG_SIZE + $self->{data_size}
317 + $self->{data_size} + length( $key );
319 if ( $is_dbm_deep && $value->_root eq $obj->_root ) {
320 return $len + $self->{long_size};
323 my $r = Scalar::Util::reftype( $value ) || '';
324 if ( $obj->_root->{autobless} ) {
325 # This is for the bit saying whether or not this thing is blessed.
329 unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
330 if ( defined $value ) {
331 $len += length( $value );
336 $len += $self->{index_size};
338 # if autobless is enabled, must also take into consideration
339 # the class name as it is stored after the key.
340 if ( $obj->_root->{autobless} ) {
341 my $value_class = Scalar::Util::blessed($value);
342 if ( defined $value_class && !$is_dbm_deep ) {
343 $len += $self->{data_size} + length($value_class);
352 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
353 # plain (undigested) key and value.
356 my ($obj, $tag, $md5, $plain_key, $value) = @_;
358 # This verifies that only supported values will be stored.
360 my $r = Scalar::Util::reftype( $value );
363 last if $r eq 'HASH';
364 last if $r eq 'ARRAY';
367 "Storage of variables of type '$r' is not supported."
374 my $root = $obj->_root;
377 my $actual_length = $self->_length_needed( $obj, $value, $plain_key );
379 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
381 # $self->_release_space( $obj, $size, $subloc );
382 # Updating a known md5
383 #XXX This needs updating to use _release_space
387 if ($actual_length <= $size) {
391 $location = $self->_request_space( $obj, $actual_length );
394 $tag->{offset} + $offset
395 + $self->{hash_size} + $root->{file_offset},
398 print( $fh pack($self->{long_pack}, $location ) );
399 print( $fh pack($self->{long_pack}, $actual_length ) );
403 elsif ( defined $offset ) {
404 $location = $self->_request_space( $obj, $actual_length );
406 seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
407 print( $fh $md5 . pack($self->{long_pack}, $location ) );
408 print( $fh pack($self->{long_pack}, $actual_length ) );
410 # If bucket didn't fit into list, split into a new index level
411 # split_index() will do the _request_space() call
413 $location = $self->split_index( $obj, $md5, $tag );
416 $self->write_value( $obj, $location, $plain_key, $value );
423 my $r = Scalar::Util::reftype( $item ) || return;
424 if ( $r eq 'HASH' ) {
427 elsif ( $r eq 'ARRAY' ) {
435 sub _get_dbm_object {
440 if ($item->isa( 'DBM::Deep' )) {
447 my $r = Scalar::Util::reftype( $item ) || '';
448 if ( $r eq 'HASH' ) {
451 my $obj = tied(%$item);
452 if ($obj->isa( 'DBM::Deep' )) {
459 elsif ( $r eq 'ARRAY' ) {
462 my $obj = tied(@$item);
463 if ($obj->isa( 'DBM::Deep' )) {
476 my ($obj, $location, $key, $value) = @_;
479 my $root = $obj->_root;
481 my $dbm_deep_obj = _get_dbm_object( $value );
482 if ( $dbm_deep_obj && $dbm_deep_obj->_root ne $obj->_root ) {
483 $obj->_throw_error( "Cannot cross-reference. Use export() instead" );
486 seek($fh, $location + $root->{file_offset}, SEEK_SET);
489 # Write signature based on content type, set content length and write
492 my $r = Scalar::Util::reftype( $value ) || '';
493 if ( $dbm_deep_obj ) {
494 $self->write_tag( $obj, undef, SIG_INTERNAL,pack($self->{long_pack}, $dbm_deep_obj->_base_offset) );
496 elsif ($r eq 'HASH') {
497 if ( !$dbm_deep_obj && tied %{$value} ) {
498 $obj->_throw_error( "Cannot store something that is tied" );
500 $self->write_tag( $obj, undef, SIG_HASH, chr(0)x$self->{index_size} );
502 elsif ($r eq 'ARRAY') {
503 if ( !$dbm_deep_obj && tied @{$value} ) {
504 $obj->_throw_error( "Cannot store something that is tied" );
506 $self->write_tag( $obj, undef, SIG_ARRAY, chr(0)x$self->{index_size} );
508 elsif (!defined($value)) {
509 $self->write_tag( $obj, undef, SIG_NULL, '' );
512 $self->write_tag( $obj, undef, SIG_DATA, $value );
516 # Plain key is stored AFTER value, as keys are typically fetched less often.
518 print( $fh pack($self->{data_pack}, length($key)) . $key );
520 # Internal references don't care about autobless
521 return 1 if $dbm_deep_obj;
524 # If value is blessed, preserve class name
526 if ( $root->{autobless} ) {
527 my $value_class = Scalar::Util::blessed($value);
528 if ( defined $value_class && !$dbm_deep_obj ) {
530 print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
538 # If content is a hash or array, create new child DBM::Deep object and
539 # pass each key or element to it.
543 tie %$value, 'DBM::Deep', {
544 base_offset => $location,
549 elsif ($r eq 'ARRAY') {
551 tie @$value, 'DBM::Deep', {
552 base_offset => $location,
563 my ($obj, $md5, $tag) = @_;
566 my $root = $obj->_root;
568 my $loc = $self->_request_space(
569 $obj, $self->tag_size( $self->{index_size} ),
572 seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
573 print( $fh pack($self->{long_pack}, $loc) );
575 my $index_tag = $self->write_tag(
576 $obj, $loc, SIG_INDEX,
577 chr(0)x$self->{index_size},
580 my $newtag_loc = $self->_request_space(
581 $obj, $self->tag_size( $self->{bucket_list_size} ),
584 my $keys = $tag->{content}
585 . $md5 . pack($self->{long_pack}, $newtag_loc)
586 . pack($self->{long_pack}, 0);
590 for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
591 my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
593 die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
594 die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
596 my $num = ord(substr($key, $tag->{ch} + 1, 1));
599 seek($fh, $newloc[$num] + $root->{file_offset}, SEEK_SET);
601 read( $fh, $subkeys, $self->{bucket_list_size});
603 # This is looking for the first empty spot
604 my ($subloc, $offset, $size) = $self->_find_in_buckets(
605 { content => $subkeys }, '',
608 seek($fh, $newloc[$num] + $offset + $root->{file_offset}, SEEK_SET);
609 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
614 seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
616 my $loc = $self->_request_space(
617 $obj, $self->tag_size( $self->{bucket_list_size} ),
620 print( $fh pack($self->{long_pack}, $loc) );
622 my $blist_tag = $self->write_tag(
623 $obj, $loc, SIG_BLIST,
624 chr(0)x$self->{bucket_list_size},
627 seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
628 print( $fh $key . pack($self->{long_pack}, $old_subloc) );
630 $newloc[$num] = $blist_tag->{offset};
633 $self->_release_space(
634 $obj, $self->tag_size( $self->{bucket_list_size} ),
635 $tag->{offset} - SIG_SIZE - $self->{data_size},
643 my ($obj, $subloc) = @_;
648 # Found match -- seek to offset and read signature
651 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
652 read( $fh, $signature, SIG_SIZE);
655 # If value is a hash or array, return new DBM::Deep object with correct offset
657 if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
658 my $new_obj = DBM::Deep->new({
660 base_offset => $subloc,
664 if ($new_obj->_root->{autobless}) {
666 # Skip over value and plain key to see if object needs
669 seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
672 read( $fh, $size, $self->{data_size});
673 $size = unpack($self->{data_pack}, $size);
674 if ($size) { seek($fh, $size, SEEK_CUR); }
677 read( $fh, $bless_bit, 1);
678 if (ord($bless_bit)) {
680 # Yes, object needs to be re-blessed
683 read( $fh, $size, $self->{data_size});
684 $size = unpack($self->{data_pack}, $size);
685 if ($size) { read( $fh, $class_name, $size); }
686 if ($class_name) { $new_obj = bless( $new_obj, $class_name ); }
692 elsif ( $signature eq SIG_INTERNAL ) {
694 read( $fh, $size, $self->{data_size});
695 $size = unpack($self->{data_pack}, $size);
699 read( $fh, $new_loc, $size );
700 $new_loc = unpack( $self->{long_pack}, $new_loc );
702 return $self->read_from_loc( $obj, $new_loc );
709 # Otherwise return actual value
711 elsif ($signature eq SIG_DATA) {
713 read( $fh, $size, $self->{data_size});
714 $size = unpack($self->{data_pack}, $size);
717 if ($size) { read( $fh, $value, $size); }
722 # Key exists, but content is null
727 sub get_bucket_value {
729 # Fetch single value given tag and MD5 digested key.
732 my ($obj, $tag, $md5) = @_;
734 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
736 return $self->read_from_loc( $obj, $subloc );
743 # Delete single key/value pair given tag and MD5 digested key.
746 my ($obj, $tag, $md5) = @_;
748 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
749 #XXX This needs _release_space()
752 seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
753 print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
754 print( $fh chr(0) x $self->{bucket_size} );
763 # Check existence of single key given tag and MD5 digested key.
766 my ($obj, $tag, $md5) = @_;
768 my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
772 sub find_bucket_list {
774 # Locate offset for bucket list, given digested key
777 my ($obj, $md5, $args) = @_;
778 $args = {} unless $args;
781 # Locate offset for bucket list using digest index system
783 my $tag = $self->load_tag($obj, $obj->_base_offset)
784 or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
787 while ($tag->{signature} ne SIG_BLIST) {
788 my $num = ord substr($md5, $ch, 1);
790 my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
791 $tag = $self->index_lookup( $obj, $tag, $num );
794 return if !$args->{create};
796 my $loc = $self->_request_space(
797 $obj, $self->tag_size( $self->{bucket_list_size} ),
801 seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
802 print( $fh pack($self->{long_pack}, $loc) );
804 $tag = $self->write_tag(
805 $obj, $loc, SIG_BLIST,
806 chr(0)x$self->{bucket_list_size},
809 $tag->{ref_loc} = $ref_loc;
816 $tag->{ref_loc} = $ref_loc;
824 # Given index tag, lookup single entry in index and return .
827 my ($obj, $tag, $index) = @_;
829 my $location = unpack(
833 $index * $self->{long_size},
838 if (!$location) { return; }
840 return $self->load_tag( $obj, $location );
845 # Scan index and recursively step into deeper levels, looking for next key.
848 my ($obj, $offset, $ch, $force_return_next) = @_;
850 my $tag = $self->load_tag($obj, $offset );
854 if ($tag->{signature} ne SIG_BLIST) {
855 my $content = $tag->{content};
856 my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
858 for (my $idx = $start; $idx < (2**8); $idx++) {
863 $idx * $self->{long_size},
869 my $result = $self->traverse_index(
870 $obj, $subloc, $ch + 1, $force_return_next,
873 if (defined($result)) { return $result; }
877 $obj->{return_next} = 1;
881 my $keys = $tag->{content};
882 if ($force_return_next) { $obj->{return_next} = 1; }
885 # Iterate through buckets, looking for a key match
887 for (my $i = 0; $i < $self->{max_buckets}; $i++) {
888 my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
890 # End of bucket list -- return to outer loop
892 $obj->{return_next} = 1;
895 # Located previous key -- return next one found
896 elsif ($key eq $obj->{prev_md5}) {
897 $obj->{return_next} = 1;
900 # Seek to bucket location and skip over signature
901 elsif ($obj->{return_next}) {
902 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
904 # Skip over value to get to plain key
906 read( $fh, $sig, SIG_SIZE );
909 read( $fh, $size, $self->{data_size});
910 $size = unpack($self->{data_pack}, $size);
911 if ($size) { seek($fh, $size, SEEK_CUR); }
913 # Read in plain key and return as scalar
915 read( $fh, $size, $self->{data_size});
916 $size = unpack($self->{data_pack}, $size);
917 if ($size) { read( $fh, $plain_key, $size); }
923 $obj->{return_next} = 1;
924 } # tag is a bucket list
931 # Locate next key, given digested previous one
936 $obj->{prev_md5} = $_[1] ? $_[1] : undef;
937 $obj->{return_next} = 0;
940 # If the previous key was not specifed, start at the top and
941 # return the first one found.
943 if (!$obj->{prev_md5}) {
944 $obj->{prev_md5} = chr(0) x $self->{hash_size};
945 $obj->{return_next} = 1;
948 return $self->traverse_index( $obj, $obj->_base_offset, 0 );
953 sub _get_key_subloc {
955 my ($keys, $idx) = @_;
957 my ($key, $subloc, $size) = unpack(
958 "a$self->{hash_size} $self->{long_pack} $self->{long_pack}",
961 ($idx * $self->{bucket_size}),
962 $self->{bucket_size},
966 return ($key, $subloc, $size);
969 sub _find_in_buckets {
971 my ($tag, $md5) = @_;
974 for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
975 my ($key, $subloc, $size) = $self->_get_key_subloc(
979 return ($subloc, $i * $self->{bucket_size}, $size) unless $subloc;
981 next BUCKET if $key ne $md5;
983 return ($subloc, $i * $self->{bucket_size}, $size);
991 # my ($obj, $spot, $data) = @_;
993 # my $fh = $obj->_fh;
994 # seek( $fh, $spot, SEEK_SET );
995 # print( $fh $data );
1000 sub _request_space {
1002 my ($obj, $size) = @_;
1004 my $loc = $obj->_root->{end};
1005 $obj->_root->{end} += $size;
1010 sub _release_space {
1012 my ($obj, $size, $loc) = @_;
1017 seek( $fh, $loc + $obj->_root->{file_offset}, SEEK_SET );
1019 . pack($self->{long_pack}, $size )
1020 . pack($self->{long_pack}, $next_loc )
1029 # This will be added in later, after more refactoring is done. This is an early
1030 # attempt at refactoring on the physical level instead of the virtual level.
1033 my ($obj, $spot, $amount, $unpack) = @_;
1036 seek( $fh, $spot + $obj->_root->{file_offset}, SEEK_SET );
1039 my $bytes_read = read( $fh, $buffer, $amount );
1042 $buffer = unpack( $unpack, $buffer );
1046 return ($buffer, $bytes_read);