7 # Multi-level database module for storing hash trees, arrays and simple
8 # key/value pairs into FTP-able, cross-platform binary database files.
10 # Type `perldoc DBM::Deep` for complete documentation.
14 # tie %db, 'DBM::Deep', 'my_database.db'; # standard tie() method
16 # my $db = new DBM::Deep( 'my_database.db' ); # preferred OO method
18 # $db->{my_scalar} = 'hello world';
19 # $db->{my_hash} = { larry => 'genius', hashes => 'fast' };
20 # $db->{my_array} = [ 1, 2, 3, time() ];
21 # $db->{my_complex} = [ 'hello', { perl => 'rules' }, 42, 99 ];
22 # push @{$db->{my_array}}, 'another value';
23 # my @key_list = keys %{$db->{my_hash}};
24 # print "This module " . $db->{my_complex}->[1]->{perl} . "!\n";
27 # (c) 2002-2005 Joseph Huckaby. All Rights Reserved.
28 # This program is free software; you can redistribute it and/or
29 # modify it under the same terms as Perl itself.
38 use vars qw/$VERSION/;
43 # Set to 4 and 'N' for 32-bit offset tags (default). Theoretical limit of 4 GB per file.
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)
53 # Set to 4 and 'N' for 32-bit data length prefixes. Limit of 4 GB for each key/value.
54 # Upgrading this is possible (see above) but probably not necessary. If you need
55 # more than 4 GB for a single key or value, this module is really not for you :-)
57 #my $DATA_LENGTH_SIZE = 4;
58 #my $DATA_LENGTH_PACK = 'N';
59 my ($LONG_SIZE, $LONG_PACK, $DATA_LENGTH_SIZE, $DATA_LENGTH_PACK);
62 # Maximum number of buckets per list before another level of indexing is done.
63 # Increase this value for slightly greater speed, but larger database files.
64 # DO NOT decrease this value below 16, due to risk of recursive reindex overrun.
69 # Better not adjust anything below here, unless you're me :-)
73 # Setup digest function for keys
75 my ($DIGEST_FUNC, $HASH_SIZE);
76 #my $DIGEST_FUNC = \&Digest::MD5::md5;
79 # Precalculate index and bucket sizes based on values above.
82 my ($INDEX_SIZE, $BUCKET_SIZE, $BUCKET_LIST_SIZE);
89 # Setup file and tag signatures. These should never change.
91 sub SIG_FILE () { 'DPDB' }
92 sub SIG_HASH () { 'H' }
93 sub SIG_ARRAY () { 'A' }
94 sub SIG_NULL () { 'N' }
95 sub SIG_DATA () { 'D' }
96 sub SIG_INDEX () { 'I' }
97 sub SIG_BLIST () { 'B' }
101 # Setup constants for users to pass to new()
103 sub TYPE_HASH () { return SIG_HASH; }
104 sub TYPE_ARRAY () { return SIG_ARRAY; }
108 # Class constructor method for Perl OO interface.
109 # Calls tie() and returns blessed reference to tied hash or array,
110 # providing a hybrid OO/tie interface.
114 if (scalar(@_) > 1) { $args = {@_}; }
115 else { $args = { file => shift }; }
118 # Check if we want a tied hash or array.
121 if (defined($args->{type}) && $args->{type} eq TYPE_ARRAY) {
122 tie @$self, $class, %$args;
125 tie %$self, $class, %$args;
128 return bless $self, $class;
132 my @outer_params = qw( type base_offset );
135 # Setup $self and bless into this class.
142 base_offset => length(SIG_FILE),
153 filter_store_key => undef,
154 filter_store_value => undef,
155 filter_fetch_key => undef,
156 filter_fetch_value => undef,
165 foreach my $outer_parm ( @outer_params ) {
166 next unless exists $args->{$outer_parm};
167 $self->{$outer_parm} = $args->{$outer_parm}
170 if ( exists $args->{root} ) {
171 $self->{root} = $args->{root};
174 # This is cleanup based on the fact that the $args
175 # coming in is for both the root and non-root items
176 delete $self->root->{$_} for @outer_params;
178 $self->root->{links}++;
180 if (!defined($self->fh)) { $self->_open(); }
186 sub _get_self { tied( %{$_[0]} ) || $_[0] }
190 # Tied hash constructor method, called by Perl's tie() function.
194 if (scalar(@_) > 1) { $args = {@_}; }
195 #XXX This use of ref() is bad and is a bug
196 elsif (ref($_[0])) { $args = $_[0]; }
197 else { $args = { file => shift }; }
199 $args->{type} = TYPE_HASH;
201 return $class->_init($args);
206 # Tied array constructor method, called by Perl's tie() function.
210 if (scalar(@_) > 1) { $args = {@_}; }
211 #XXX This use of ref() is bad and is a bug
212 elsif (ref($_[0])) { $args = $_[0]; }
213 else { $args = { file => shift }; }
215 $args->{type} = TYPE_ARRAY;
217 return $class->_init($args);
222 # Class deconstructor. Close file handle if there are no more refs.
224 my $self = _get_self($_[0]);
227 $self->root->{links}--;
229 if (!$self->root->{links}) {
236 # Open a FileHandle to the database, create if nonexistent.
237 # Make sure file signature matches DeepDB spec.
239 my $self = _get_self($_[0]);
241 if (defined($self->fh)) { $self->_close(); }
244 if (!(-e $self->root->{file}) && $self->root->{mode} eq 'r+') {
245 my $temp = FileHandle->new( $self->root->{file}, 'w' );
248 #XXX Convert to set_fh()
249 $self->root->{fh} = FileHandle->new( $self->root->{file}, $self->root->{mode} );
250 # }; if ($@ ) { $self->_throw_error( "Received error: $@\n" ); }
251 if (! defined($self->fh)) {
252 return $self->_throw_error("Cannot open file: " . $self->root->{file} . ": $!");
257 #XXX Can we remove this by using the right sysopen() flags?
258 binmode $fh; # for win32
260 if ($self->root->{autoflush}) {
261 # $self->fh->autoflush();
262 my $old = select $fh;
269 my $bytes_read = read( $fh, $signature, length(SIG_FILE));
272 # File is empty -- write signature and master index
277 $self->root->{end} = length(SIG_FILE);
278 $self->_create_tag($self->base_offset, $self->type, chr(0) x $INDEX_SIZE);
280 my $plain_key = "[base]";
281 print($fh pack($DATA_LENGTH_PACK, length($plain_key)) . $plain_key );
282 $self->root->{end} += $DATA_LENGTH_SIZE + length($plain_key);
285 my $old_fh = select $fh;
295 # Check signature was valid
297 unless ($signature eq SIG_FILE) {
299 return $self->_throw_error("Signature not found -- file is not a Deep DB");
302 $self->root->{end} = (stat($fh))[7];
305 # Get our type from master index signature
307 my $tag = $self->_load_tag($self->base_offset);
308 #XXX We probably also want to store the hash algorithm name and not assume anything
310 return $self->_throw_error("Corrupted file, no master index record");
312 if ($self->{type} ne $tag->{signature}) {
313 return $self->_throw_error("File type mismatch");
321 # Close database FileHandle
323 my $self = _get_self($_[0]);
324 undef $self->root->{fh};
329 # Given offset, signature and content, create tag and write to disk
331 my ($self, $offset, $sig, $content) = @_;
332 my $size = length($content);
336 seek($fh, $offset, 0);
337 print($fh $sig . pack($DATA_LENGTH_PACK, $size) . $content );
339 if ($offset == $self->root->{end}) {
340 $self->root->{end} += SIG_SIZE + $DATA_LENGTH_SIZE + $size;
346 offset => $offset + SIG_SIZE + $DATA_LENGTH_SIZE,
353 # Given offset, load single tag and return signature, size and data
360 seek($fh, $offset, 0);
361 if (eof $fh) { return undef; }
364 read( $fh, $sig, SIG_SIZE);
367 read( $fh, $size, $DATA_LENGTH_SIZE);
368 $size = unpack($DATA_LENGTH_PACK, $size);
371 read( $fh, $buffer, $size);
376 offset => $offset + SIG_SIZE + $DATA_LENGTH_SIZE,
383 # Given index tag, lookup single entry in index and return .
386 my ($tag, $index) = @_;
388 my $location = unpack($LONG_PACK, substr($tag->{content}, $index * $LONG_SIZE, $LONG_SIZE) );
389 if (!$location) { return; }
391 return $self->_load_tag( $location );
396 # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
397 # plain (undigested) key and value.
400 my ($tag, $md5, $plain_key, $value) = @_;
401 my $keys = $tag->{content};
405 my $is_dbm_deep = eval { $value->isa( 'DBM::Deep' ) };
406 my $internal_ref = $is_dbm_deep && ($value->root eq $self->root);
411 # Iterate through buckets, seeing if this is a new entry or a replace.
413 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
414 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
415 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
418 # Found empty bucket (end of list). Populate and exit loop.
422 $location = $internal_ref
423 ? $value->base_offset
424 : $self->root->{end};
426 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE), 0);
427 print($fh $md5 . pack($LONG_PACK, $location) );
430 elsif ($md5 eq $key) {
432 # Found existing bucket with same key. Replace with new value.
437 $location = $value->base_offset;
438 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE), 0);
439 print($fh $md5 . pack($LONG_PACK, $location) );
442 seek($fh, $subloc + SIG_SIZE, 0);
444 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
447 # If value is a hash, array, or raw value with equal or less size, we can
448 # reuse the same content area of the database. Otherwise, we have to create
449 # a new content area at the EOF.
452 my $r = Scalar::Util::reftype( $value ) || '';
453 if ( $r eq 'HASH' || $r eq 'ARRAY' ) { $actual_length = $INDEX_SIZE; }
454 else { $actual_length = length($value); }
456 if ($actual_length <= $size) {
460 $location = $self->root->{end};
461 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE) + $HASH_SIZE, 0);
462 print($fh pack($LONG_PACK, $location) );
470 # If this is an internal reference, return now.
471 # No need to write value or plain key
478 # If bucket didn't fit into list, split into a new index level
481 seek($fh, $tag->{ref_loc}, 0);
482 print($fh pack($LONG_PACK, $self->root->{end}) );
484 my $index_tag = $self->_create_tag($self->root->{end}, SIG_INDEX, chr(0) x $INDEX_SIZE);
487 $keys .= $md5 . pack($LONG_PACK, 0);
489 for (my $i=0; $i<=$MAX_BUCKETS; $i++) {
490 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
492 my $old_subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
493 my $num = ord(substr($key, $tag->{ch} + 1, 1));
495 if ($offsets[$num]) {
496 my $offset = $offsets[$num] + SIG_SIZE + $DATA_LENGTH_SIZE;
497 seek($fh, $offset, 0);
499 read( $fh, $subkeys, $BUCKET_LIST_SIZE);
501 for (my $k=0; $k<$MAX_BUCKETS; $k++) {
502 my $subloc = unpack($LONG_PACK, substr($subkeys, ($k * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
504 seek($fh, $offset + ($k * $BUCKET_SIZE), 0);
505 print($fh $key . pack($LONG_PACK, $old_subloc || $self->root->{end}) );
511 $offsets[$num] = $self->root->{end};
512 seek($fh, $index_tag->{offset} + ($num * $LONG_SIZE), 0);
513 print($fh pack($LONG_PACK, $self->root->{end}) );
515 my $blist_tag = $self->_create_tag($self->root->{end}, SIG_BLIST, chr(0) x $BUCKET_LIST_SIZE);
517 seek($fh, $blist_tag->{offset}, 0);
518 print($fh $key . pack($LONG_PACK, $old_subloc || $self->root->{end}) );
523 $location ||= $self->root->{end};
524 } # re-index bucket list
527 # Seek to content area and store signature, value and plaintext key
531 seek($fh, $location, 0);
534 # Write signature based on content type, set content length and write actual value.
536 my $r = Scalar::Util::reftype($value) || '';
538 print($fh TYPE_HASH );
539 print($fh pack($DATA_LENGTH_PACK, $INDEX_SIZE) . chr(0) x $INDEX_SIZE );
540 $content_length = $INDEX_SIZE;
542 elsif ($r eq 'ARRAY') {
543 print($fh TYPE_ARRAY );
544 print($fh pack($DATA_LENGTH_PACK, $INDEX_SIZE) . chr(0) x $INDEX_SIZE );
545 $content_length = $INDEX_SIZE;
547 elsif (!defined($value)) {
548 print($fh SIG_NULL );
549 print($fh pack($DATA_LENGTH_PACK, 0) );
553 print($fh SIG_DATA );
554 print($fh pack($DATA_LENGTH_PACK, length($value)) . $value );
555 $content_length = length($value);
559 # Plain key is stored AFTER value, as keys are typically fetched less often.
561 print($fh pack($DATA_LENGTH_PACK, length($plain_key)) . $plain_key );
564 # If value is blessed, preserve class name
566 if ( $self->root->{autobless} ) {
567 my $value_class = Scalar::Util::blessed($value);
568 if ( defined $value_class && $value_class ne 'DBM::Deep' ) {
570 # Blessed ref -- will restore later
573 print($fh pack($DATA_LENGTH_PACK, length($value_class)) . $value_class );
574 $content_length += 1;
575 $content_length += $DATA_LENGTH_SIZE + length($value_class);
579 $content_length += 1;
584 # If this is a new content area, advance EOF counter
586 if ($location == $self->root->{end}) {
587 $self->root->{end} += SIG_SIZE;
588 $self->root->{end} += $DATA_LENGTH_SIZE + $content_length;
589 $self->root->{end} += $DATA_LENGTH_SIZE + length($plain_key);
593 # If content is a hash or array, create new child DeepDB object and
594 # pass each key or element to it.
597 my $branch = DBM::Deep->new(
599 base_offset => $location,
602 foreach my $key (keys %{$value}) {
603 $branch->{$key} = $value->{$key};
606 elsif ($r eq 'ARRAY') {
607 my $branch = DBM::Deep->new(
609 base_offset => $location,
613 foreach my $element (@{$value}) {
614 $branch->[$index] = $element;
622 return $self->_throw_error("Fatal error: indexing failed -- possibly due to corruption in file");
625 sub _get_bucket_value {
627 # Fetch single value given tag and MD5 digested key.
630 my ($tag, $md5) = @_;
631 my $keys = $tag->{content};
636 # Iterate through buckets, looking for a key match
639 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
640 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
641 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
645 # Hit end of list, no match
650 if ( $md5 ne $key ) {
655 # Found match -- seek to offset and read signature
658 seek($fh, $subloc, 0);
659 read( $fh, $signature, SIG_SIZE);
662 # If value is a hash or array, return new DeepDB object with correct offset
664 if (($signature eq TYPE_HASH) || ($signature eq TYPE_ARRAY)) {
665 my $obj = DBM::Deep->new(
667 base_offset => $subloc,
671 if ($self->root->{autobless}) {
673 # Skip over value and plain key to see if object needs
676 seek($fh, $DATA_LENGTH_SIZE + $INDEX_SIZE, 1);
679 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
680 if ($size) { seek($fh, $size, 1); }
683 read( $fh, $bless_bit, 1);
684 if (ord($bless_bit)) {
686 # Yes, object needs to be re-blessed
689 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
690 if ($size) { read( $fh, $class_name, $size); }
691 if ($class_name) { $obj = bless( $obj, $class_name ); }
699 # Otherwise return actual value
701 elsif ($signature eq SIG_DATA) {
704 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
705 if ($size) { read( $fh, $value, $size); }
710 # Key exists, but content is null
720 # Delete single key/value pair given tag and MD5 digested key.
723 my ($tag, $md5) = @_;
724 my $keys = $tag->{content};
729 # Iterate through buckets, looking for a key match
732 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
733 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
734 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
738 # Hit end of list, no match
743 if ( $md5 ne $key ) {
748 # Matched key -- delete bucket and return
750 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE), 0);
751 print($fh substr($keys, ($i+1) * $BUCKET_SIZE ) );
752 print($fh chr(0) x $BUCKET_SIZE );
762 # Check existence of single key given tag and MD5 digested key.
765 my ($tag, $md5) = @_;
766 my $keys = $tag->{content};
769 # Iterate through buckets, looking for a key match
772 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
773 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
774 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
778 # Hit end of list, no match
783 if ( $md5 ne $key ) {
788 # Matched key -- return true
796 sub _find_bucket_list {
798 # Locate offset for bucket list, given digested key
804 # Locate offset for bucket list using digest index system
807 my $tag = $self->_load_tag($self->base_offset);
808 if (!$tag) { return; }
810 while ($tag->{signature} ne SIG_BLIST) {
811 $tag = $self->_index_lookup($tag, ord(substr($md5, $ch, 1)));
812 if (!$tag) { return; }
819 sub _traverse_index {
821 # Scan index and recursively step into deeper levels, looking for next key.
823 my ($self, $offset, $ch, $force_return_next) = @_;
824 $force_return_next = undef unless $force_return_next;
826 my $tag = $self->_load_tag( $offset );
830 if ($tag->{signature} ne SIG_BLIST) {
831 my $content = $tag->{content};
833 if ($self->{return_next}) { $start = 0; }
834 else { $start = ord(substr($self->{prev_md5}, $ch, 1)); }
836 for (my $index = $start; $index < 256; $index++) {
837 my $subloc = unpack($LONG_PACK, substr($content, $index * $LONG_SIZE, $LONG_SIZE) );
839 my $result = $self->_traverse_index( $subloc, $ch + 1, $force_return_next );
840 if (defined($result)) { return $result; }
844 $self->{return_next} = 1;
847 elsif ($tag->{signature} eq SIG_BLIST) {
848 my $keys = $tag->{content};
849 if ($force_return_next) { $self->{return_next} = 1; }
852 # Iterate through buckets, looking for a key match
854 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
855 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
856 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
860 # End of bucket list -- return to outer loop
862 $self->{return_next} = 1;
865 elsif ($key eq $self->{prev_md5}) {
867 # Located previous key -- return next one found
869 $self->{return_next} = 1;
872 elsif ($self->{return_next}) {
874 # Seek to bucket location and skip over signature
876 seek($fh, $subloc + SIG_SIZE, 0);
879 # Skip over value to get to plain key
882 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
883 if ($size) { seek($fh, $size, 1); }
886 # Read in plain key and return as scalar
889 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
890 if ($size) { read( $fh, $plain_key, $size); }
896 $self->{return_next} = 1;
897 } # tag is a bucket list
904 # Locate next key, given digested previous one
906 my $self = _get_self($_[0]);
908 $self->{prev_md5} = $_[1] ? $_[1] : undef;
909 $self->{return_next} = 0;
912 # If the previous key was not specifed, start at the top and
913 # return the first one found.
915 if (!$self->{prev_md5}) {
916 $self->{prev_md5} = chr(0) x $HASH_SIZE;
917 $self->{return_next} = 1;
920 return $self->_traverse_index( $self->base_offset, 0 );
925 # If db locking is set, flock() the db file. If called multiple
926 # times before unlock(), then the same number of unlocks() must
927 # be called before the lock is released.
929 my $self = _get_self($_[0]);
931 $type = LOCK_EX unless defined $type;
933 if ($self->root->{locking}) {
934 if (!$self->root->{locked}) { flock($self->fh, $type); }
935 $self->root->{locked}++;
941 # If db locking is set, unlock the db file. See note in lock()
942 # regarding calling lock() multiple times.
944 my $self = _get_self($_[0]);
946 if ($self->root->{locking} && $self->root->{locked} > 0) {
947 $self->root->{locked}--;
948 if (!$self->root->{locked}) { flock($self->fh, LOCK_UN); }
952 #XXX These uses of ref() need verified
955 # Copy single level of keys or elements to new DB handle.
956 # Recurse for nested structures
958 my $self = _get_self($_[0]);
961 if ($self->type eq TYPE_HASH) {
962 my $key = $self->first_key();
964 my $value = $self->get($key);
965 #XXX This doesn't work with autobless
966 if (!ref($value)) { $db_temp->{$key} = $value; }
968 my $type = $value->type;
969 if ($type eq TYPE_HASH) { $db_temp->{$key} = {}; }
970 else { $db_temp->{$key} = []; }
971 $value->_copy_node( $db_temp->{$key} );
973 $key = $self->next_key($key);
977 my $length = $self->length();
978 for (my $index = 0; $index < $length; $index++) {
979 my $value = $self->get($index);
980 if (!ref($value)) { $db_temp->[$index] = $value; }
981 #XXX NO tests for this code
983 my $type = $value->type;
984 if ($type eq TYPE_HASH) { $db_temp->[$index] = {}; }
985 else { $db_temp->[$index] = []; }
986 $value->_copy_node( $db_temp->[$index] );
994 # Recursively export into standard Perl hashes and arrays.
996 my $self = _get_self($_[0]);
999 if ($self->type eq TYPE_HASH) { $temp = {}; }
1000 elsif ($self->type eq TYPE_ARRAY) { $temp = []; }
1003 $self->_copy_node( $temp );
1011 # Recursively import Perl hash/array structure
1013 #XXX This use of ref() seems to be ok
1014 if (!ref($_[0])) { return; } # Perl calls import() on use -- ignore
1016 my $self = _get_self($_[0]);
1019 #XXX This use of ref() seems to be ok
1020 if (!ref($struct)) {
1022 # struct is not a reference, so just import based on our type
1026 if ($self->type eq TYPE_HASH) { $struct = {@_}; }
1027 elsif ($self->type eq TYPE_ARRAY) { $struct = [@_]; }
1030 my $r = Scalar::Util::reftype($struct) || '';
1031 if ($r eq "HASH" && $self->type eq TYPE_HASH) {
1032 foreach my $key (keys %$struct) { $self->put($key, $struct->{$key}); }
1034 elsif ($r eq "ARRAY" && $self->type eq TYPE_ARRAY) {
1035 $self->push( @$struct );
1038 return $self->_throw_error("Cannot import: type mismatch");
1046 # Rebuild entire database into new file, then move
1047 # it back on top of original.
1049 my $self = _get_self($_[0]);
1050 if ($self->root->{links} > 1) {
1051 return $self->_throw_error("Cannot optimize: reference count is greater than 1");
1054 my $db_temp = DBM::Deep->new(
1055 file => $self->root->{file} . '.tmp',
1059 return $self->_throw_error("Cannot optimize: failed to open temp file: $!");
1063 $self->_copy_node( $db_temp );
1067 # Attempt to copy user, group and permissions over to new file
1069 my @stats = stat($self->fh);
1070 my $perms = $stats[2] & 07777;
1071 my $uid = $stats[4];
1072 my $gid = $stats[5];
1073 chown( $uid, $gid, $self->root->{file} . '.tmp' );
1074 chmod( $perms, $self->root->{file} . '.tmp' );
1076 # q.v. perlport for more information on this variable
1077 if ( $^O eq 'MSWin32' ) {
1079 # Potential race condition when optmizing on Win32 with locking.
1080 # The Windows filesystem requires that the filehandle be closed
1081 # before it is overwritten with rename(). This could be redone
1088 if (!rename $self->root->{file} . '.tmp', $self->root->{file}) {
1089 unlink $self->root->{file} . '.tmp';
1091 return $self->_throw_error("Optimize failed: Cannot copy temp file over original: $!");
1103 # Make copy of object and return
1105 my $self = _get_self($_[0]);
1107 return DBM::Deep->new(
1108 type => $self->type,
1109 base_offset => $self->base_offset,
1115 my %is_legal_filter = map {
1118 store_key store_value
1119 fetch_key fetch_value
1124 # Setup filter function for storing or fetching the key or value
1126 my $self = _get_self($_[0]);
1127 my $type = lc $_[1];
1128 my $func = $_[2] ? $_[2] : undef;
1130 if ( $is_legal_filter{$type} ) {
1131 $self->root->{"filter_$type"} = $func;
1145 # Get access to the root structure
1147 my $self = _get_self($_[0]);
1148 return $self->{root};
1153 # Get access to the raw FileHandle
1155 #XXX It will be useful, though, when we split out HASH and ARRAY
1156 my $self = _get_self($_[0]);
1157 return $self->root->{fh};
1162 # Get type of current node (TYPE_HASH or TYPE_ARRAY)
1164 my $self = _get_self($_[0]);
1165 return $self->{type};
1170 # Get base_offset of current node (TYPE_HASH or TYPE_ARRAY)
1172 my $self = _get_self($_[0]);
1173 return $self->{base_offset};
1178 # Get last error string, or undef if no error
1181 ? ( _get_self($_[0])->{root}->{error} or undef )
1191 # Store error string in self
1193 my $self = _get_self($_[0]);
1194 my $error_text = $_[1];
1196 $self->root->{error} = $error_text;
1198 unless ($self->root->{debug}) {
1199 die "DBM::Deep: $error_text\n";
1202 warn "DBM::Deep: $error_text\n";
1210 my $self = _get_self($_[0]);
1212 undef $self->root->{error};
1217 # Precalculate index, bucket and bucket list sizes
1220 #XXX I don't like this ...
1221 set_pack() unless defined $LONG_SIZE;
1223 $INDEX_SIZE = 256 * $LONG_SIZE;
1224 $BUCKET_SIZE = $HASH_SIZE + $LONG_SIZE;
1225 $BUCKET_LIST_SIZE = $MAX_BUCKETS * $BUCKET_SIZE;
1230 # Set pack/unpack modes (see file header for more)
1232 my ($long_s, $long_p, $data_s, $data_p) = @_;
1234 $LONG_SIZE = $long_s ? $long_s : 4;
1235 $LONG_PACK = $long_p ? $long_p : 'N';
1237 $DATA_LENGTH_SIZE = $data_s ? $data_s : 4;
1238 $DATA_LENGTH_PACK = $data_p ? $data_p : 'N';
1245 # Set key digest function (default is MD5)
1247 my ($digest_func, $hash_size) = @_;
1249 $DIGEST_FUNC = $digest_func ? $digest_func : \&Digest::MD5::md5;
1250 $HASH_SIZE = $hash_size ? $hash_size : 16;
1256 # tie() methods (hashes and arrays)
1261 # Store single hash key/value or array element in database.
1263 my $self = _get_self($_[0]);
1264 my $key = ($self->root->{filter_store_key} && $self->type eq TYPE_HASH) ? $self->root->{filter_store_key}->($_[1]) : $_[1];
1265 #XXX What is ref() checking here?
1266 #YYY User may be storing a hash, in which case we do not want it run
1267 #YYY through the filtering system
1268 my $value = ($self->root->{filter_store_value} && !ref($_[2])) ? $self->root->{filter_store_value}->($_[2]) : $_[2];
1270 my $unpacked_key = $key;
1271 if (($self->type eq TYPE_ARRAY) && ($key =~ /^\d+$/)) { $key = pack($LONG_PACK, $key); }
1272 my $md5 = $DIGEST_FUNC->($key);
1275 # Make sure file is open
1277 if (!defined($self->fh) && !$self->_open()) {
1284 # Request exclusive lock for writing
1286 $self->lock( LOCK_EX );
1289 # If locking is enabled, set 'end' parameter again, in case another
1290 # DB instance appended to our file while we were unlocked.
1292 if ($self->root->{locking} || $self->root->{volatile}) {
1293 $self->root->{end} = (stat($fh))[7];
1297 # Locate offset for bucket list using digest index system
1299 my $tag = $self->_load_tag($self->base_offset);
1301 $tag = $self->_create_tag($self->base_offset, SIG_INDEX, chr(0) x $INDEX_SIZE);
1305 while ($tag->{signature} ne SIG_BLIST) {
1306 my $num = ord(substr($md5, $ch, 1));
1307 my $new_tag = $self->_index_lookup($tag, $num);
1309 my $ref_loc = $tag->{offset} + ($num * $LONG_SIZE);
1310 seek($fh, $ref_loc, 0);
1311 print($fh pack($LONG_PACK, $self->root->{end}) );
1313 $tag = $self->_create_tag($self->root->{end}, SIG_BLIST, chr(0) x $BUCKET_LIST_SIZE);
1314 $tag->{ref_loc} = $ref_loc;
1319 my $ref_loc = $tag->{offset} + ($num * $LONG_SIZE);
1321 $tag->{ref_loc} = $ref_loc;
1328 # Add key/value to bucket list
1330 my $result = $self->_add_bucket( $tag, $md5, $key, $value );
1333 # If this object is an array, and bucket was not a replace, and key is numerical,
1334 # and index is equal or greater than current length, advance length variable.
1336 if (($result == 2) && ($self->type eq TYPE_ARRAY) && ($unpacked_key =~ /^\d+$/) && ($unpacked_key >= $self->FETCHSIZE())) {
1337 $self->STORESIZE( $unpacked_key + 1 );
1347 # Fetch single value or element given plain key or array index
1349 my $self = _get_self($_[0]);
1352 if ( $self->type eq TYPE_HASH ) {
1353 if ( my $filter = $self->root->{filter_store_key} ) {
1354 $key = $filter->( $key );
1357 elsif ( $self->type eq TYPE_ARRAY ) {
1358 if ( $key =~ /^\d+$/ ) {
1359 $key = pack($LONG_PACK, $key);
1363 my $md5 = $DIGEST_FUNC->($key);
1366 # Make sure file is open
1368 if (!defined($self->fh)) { $self->_open(); }
1371 # Request shared lock for reading
1373 $self->lock( LOCK_SH );
1375 my $tag = $self->_find_bucket_list( $md5 );
1382 # Get value from bucket list
1384 my $result = $self->_get_bucket_value( $tag, $md5 );
1388 #XXX What is ref() checking here?
1389 return ($result && !ref($result) && $self->root->{filter_fetch_value}) ? $self->root->{filter_fetch_value}->($result) : $result;
1394 # Delete single key/value pair or element given plain key or array index
1396 my $self = _get_self($_[0]);
1397 my $key = ($self->root->{filter_store_key} && $self->type eq TYPE_HASH) ? $self->root->{filter_store_key}->($_[1]) : $_[1];
1399 my $unpacked_key = $key;
1400 if (($self->type eq TYPE_ARRAY) && ($key =~ /^\d+$/)) { $key = pack($LONG_PACK, $key); }
1401 my $md5 = $DIGEST_FUNC->($key);
1404 # Make sure file is open
1406 if (!defined($self->fh)) { $self->_open(); }
1409 # Request exclusive lock for writing
1411 $self->lock( LOCK_EX );
1413 my $tag = $self->_find_bucket_list( $md5 );
1422 my $result = $self->_delete_bucket( $tag, $md5 );
1425 # If this object is an array and the key deleted was on the end of the stack,
1426 # decrement the length variable.
1428 if ($result && ($self->type eq TYPE_ARRAY) && ($unpacked_key == $self->FETCHSIZE() - 1)) {
1429 $self->STORESIZE( $unpacked_key );
1439 # Check if a single key or element exists given plain key or array index
1441 my $self = _get_self($_[0]);
1442 my $key = ($self->root->{filter_store_key} && $self->type eq TYPE_HASH) ? $self->root->{filter_store_key}->($_[1]) : $_[1];
1444 if (($self->type eq TYPE_ARRAY) && ($key =~ /^\d+$/)) { $key = pack($LONG_PACK, $key); }
1445 my $md5 = $DIGEST_FUNC->($key);
1448 # Make sure file is open
1450 if (!defined($self->fh)) { $self->_open(); }
1453 # Request shared lock for reading
1455 $self->lock( LOCK_SH );
1457 my $tag = $self->_find_bucket_list( $md5 );
1460 # For some reason, the built-in exists() function returns '' for false
1468 # Check if bucket exists and return 1 or ''
1470 my $result = $self->_bucket_exists( $tag, $md5 ) || '';
1479 # Clear all keys from hash, or all elements from array.
1481 my $self = _get_self($_[0]);
1484 # Make sure file is open
1486 if (!defined($self->fh)) { $self->_open(); }
1489 # Request exclusive lock for writing
1491 $self->lock( LOCK_EX );
1495 seek($fh, $self->base_offset, 0);
1501 $self->_create_tag($self->base_offset, $self->type, chr(0) x $INDEX_SIZE);
1510 # Locate and return first key (in no particular order)
1512 my $self = _get_self($_[0]);
1513 if ($self->type ne TYPE_HASH) {
1514 return $self->_throw_error("FIRSTKEY method only supported for hashes");
1518 # Make sure file is open
1520 if (!defined($self->fh)) { $self->_open(); }
1523 # Request shared lock for reading
1525 $self->lock( LOCK_SH );
1527 my $result = $self->_get_next_key();
1531 return ($result && $self->root->{filter_fetch_key}) ? $self->root->{filter_fetch_key}->($result) : $result;
1536 # Return next key (in no particular order), given previous one
1538 my $self = _get_self($_[0]);
1539 if ($self->type ne TYPE_HASH) {
1540 return $self->_throw_error("NEXTKEY method only supported for hashes");
1542 my $prev_key = ($self->root->{filter_store_key} && $self->type eq TYPE_HASH) ? $self->root->{filter_store_key}->($_[1]) : $_[1];
1543 my $prev_md5 = $DIGEST_FUNC->($prev_key);
1546 # Make sure file is open
1548 if (!defined($self->fh)) { $self->_open(); }
1551 # Request shared lock for reading
1553 $self->lock( LOCK_SH );
1555 my $result = $self->_get_next_key( $prev_md5 );
1559 return ($result && $self->root->{filter_fetch_key}) ? $self->root->{filter_fetch_key}->($result) : $result;
1563 # The following methods are for arrays only
1568 # Return the length of the array
1570 my $self = _get_self($_[0]);
1571 if ($self->type ne TYPE_ARRAY) {
1572 return $self->_throw_error("FETCHSIZE method only supported for arrays");
1575 my $SAVE_FILTER = $self->root->{filter_fetch_value};
1576 $self->root->{filter_fetch_value} = undef;
1578 my $packed_size = $self->FETCH('length');
1580 $self->root->{filter_fetch_value} = $SAVE_FILTER;
1582 if ($packed_size) { return int(unpack($LONG_PACK, $packed_size)); }
1588 # Set the length of the array
1590 my $self = _get_self($_[0]);
1591 if ($self->type ne TYPE_ARRAY) {
1592 return $self->_throw_error("STORESIZE method only supported for arrays");
1594 my $new_length = $_[1];
1596 my $SAVE_FILTER = $self->root->{filter_store_value};
1597 $self->root->{filter_store_value} = undef;
1599 my $result = $self->STORE('length', pack($LONG_PACK, $new_length));
1601 $self->root->{filter_store_value} = $SAVE_FILTER;
1608 # Remove and return the last element on the array
1610 my $self = _get_self($_[0]);
1611 if ($self->type ne TYPE_ARRAY) {
1612 return $self->_throw_error("POP method only supported for arrays");
1614 my $length = $self->FETCHSIZE();
1617 my $content = $self->FETCH( $length - 1 );
1618 $self->DELETE( $length - 1 );
1628 # Add new element(s) to the end of the array
1630 my $self = _get_self(shift);
1631 if ($self->type ne TYPE_ARRAY) {
1632 return $self->_throw_error("PUSH method only supported for arrays");
1634 my $length = $self->FETCHSIZE();
1636 while (my $content = shift @_) {
1637 $self->STORE( $length, $content );
1644 # Remove and return first element on the array.
1645 # Shift over remaining elements to take up space.
1647 my $self = _get_self($_[0]);
1648 if ($self->type ne TYPE_ARRAY) {
1649 return $self->_throw_error("SHIFT method only supported for arrays");
1651 my $length = $self->FETCHSIZE();
1654 my $content = $self->FETCH( 0 );
1657 # Shift elements over and remove last one.
1659 for (my $i = 0; $i < $length - 1; $i++) {
1660 $self->STORE( $i, $self->FETCH($i + 1) );
1662 $self->DELETE( $length - 1 );
1673 # Insert new element(s) at beginning of array.
1674 # Shift over other elements to make space.
1676 my $self = _get_self($_[0]);shift @_;
1677 if ($self->type ne TYPE_ARRAY) {
1678 return $self->_throw_error("UNSHIFT method only supported for arrays");
1680 my @new_elements = @_;
1681 my $length = $self->FETCHSIZE();
1682 my $new_size = scalar @new_elements;
1685 for (my $i = $length - 1; $i >= 0; $i--) {
1686 $self->STORE( $i + $new_size, $self->FETCH($i) );
1690 for (my $i = 0; $i < $new_size; $i++) {
1691 $self->STORE( $i, $new_elements[$i] );
1697 # Splices section of array with optional new section.
1698 # Returns deleted section, or last element deleted in scalar context.
1700 my $self = _get_self($_[0]);shift @_;
1701 if ($self->type ne TYPE_ARRAY) {
1702 return $self->_throw_error("SPLICE method only supported for arrays");
1704 my $length = $self->FETCHSIZE();
1707 # Calculate offset and length of splice
1709 my $offset = shift || 0;
1710 if ($offset < 0) { $offset += $length; }
1713 if (scalar @_) { $splice_length = shift; }
1714 else { $splice_length = $length - $offset; }
1715 if ($splice_length < 0) { $splice_length += ($length - $offset); }
1718 # Setup array with new elements, and copy out old elements for return
1720 my @new_elements = @_;
1721 my $new_size = scalar @new_elements;
1723 my @old_elements = ();
1724 for (my $i = $offset; $i < $offset + $splice_length; $i++) {
1725 push @old_elements, $self->FETCH( $i );
1729 # Adjust array length, and shift elements to accomodate new section.
1731 if ( $new_size != $splice_length ) {
1732 if ($new_size > $splice_length) {
1733 for (my $i = $length - 1; $i >= $offset + $splice_length; $i--) {
1734 $self->STORE( $i + ($new_size - $splice_length), $self->FETCH($i) );
1738 for (my $i = $offset + $splice_length; $i < $length; $i++) {
1739 $self->STORE( $i + ($new_size - $splice_length), $self->FETCH($i) );
1741 for (my $i = 0; $i < $splice_length - $new_size; $i++) {
1742 $self->DELETE( $length - 1 );
1749 # Insert new elements into array
1751 for (my $i = $offset; $i < $offset + $new_size; $i++) {
1752 $self->STORE( $i, shift @new_elements );
1756 # Return deleted section, or last element in scalar context.
1758 return wantarray ? @old_elements : $old_elements[-1];
1761 #XXX We don't need to define it.
1762 #XXX It will be useful, though, when we split out HASH and ARRAY
1765 # Perl will call EXTEND() when the array is likely to grow.
1766 # We don't care, but include it for compatibility.
1771 # Public method aliases
1773 *put = *store = *STORE;
1774 *get = *fetch = *FETCH;
1778 *first_key = *FIRSTKEY;
1779 *next_key = *NEXTKEY;
1780 *length = *FETCHSIZE;
1784 *unshift = *UNSHIFT;
1793 DBM::Deep - A pure perl multi-level hash/array DBM
1798 my $db = DBM::Deep->new( "foo.db" );
1800 $db->{key} = 'value'; # tie() style
1803 $db->put('key', 'value'); # OO style
1804 print $db->get('key');
1806 # true multi-level support
1807 $db->{my_complex} = [
1808 'hello', { perl => 'rules' },
1813 A unique flat-file database module, written in pure perl. True
1814 multi-level hash/array support (unlike MLDBM, which is faked), hybrid
1815 OO / tie() interface, cross-platform FTPable files, and quite fast. Can
1816 handle millions of keys and unlimited hash levels without significant
1817 slow-down. Written from the ground-up in pure perl -- this is NOT a
1818 wrapper around a C-based DBM. Out-of-the-box compatibility with Unix,
1819 Mac OS X and Windows.
1823 Hopefully you are using CPAN's excellent Perl module, which will download
1824 and install the module for you. If not, get the tarball, and run these
1836 Construction can be done OO-style (which is the recommended way), or using
1837 Perl's tie() function. Both are examined here.
1839 =head2 OO CONSTRUCTION
1841 The recommended way to construct a DBM::Deep object is to use the new()
1842 method, which gets you a blessed, tied hash or array reference.
1844 my $db = DBM::Deep->new( "foo.db" );
1846 This opens a new database handle, mapped to the file "foo.db". If this
1847 file does not exist, it will automatically be created. DB files are
1848 opened in "r+" (read/write) mode, and the type of object returned is a
1849 hash, unless otherwise specified (see L<OPTIONS> below).
1853 You can pass a number of options to the constructor to specify things like
1854 locking, autoflush, etc. This is done by passing an inline hash:
1856 my $db = DBM::Deep->new(
1862 Notice that the filename is now specified I<inside> the hash with
1863 the "file" parameter, as opposed to being the sole argument to the
1864 constructor. This is required if any options are specified.
1865 See L<OPTIONS> below for the complete list.
1869 You can also start with an array instead of a hash. For this, you must
1870 specify the C<type> parameter:
1872 my $db = DBM::Deep->new(
1874 type => DBM::Deep->TYPE_ARRAY
1877 B<Note:> Specifing the C<type> parameter only takes effect when beginning
1878 a new DB file. If you create a DBM::Deep object with an existing file, the
1879 C<type> will be loaded from the file header, and ignored if it is passed
1882 =head2 TIE CONSTRUCTION
1884 Alternatively, you can create a DBM::Deep handle by using Perl's built-in
1885 tie() function. This is not ideal, because you get only a basic, tied hash
1886 (or array) which is not blessed, so you can't call any functions on it.
1889 tie %hash, "DBM::Deep", "foo.db";
1892 tie @array, "DBM::Deep", "bar.db";
1894 As with the OO constructor, you can replace the DB filename parameter with
1895 a hash containing one or more options (see L<OPTIONS> just below for the
1898 tie %hash, "DBM::Deep", {
1906 There are a number of options that can be passed in when constructing your
1907 DBM::Deep objects. These apply to both the OO- and tie- based approaches.
1913 Filename of the DB file to link the handle to. You can pass a full absolute
1914 filesystem path, partial path, or a plain filename if the file is in the
1915 current working directory. This is a required parameter.
1919 File open mode (read-only, read-write, etc.) string passed to Perl's FileHandle
1920 module. This is an optional parameter, and defaults to "r+" (read/write).
1921 B<Note:> If the default (r+) mode is selected, the file will also be auto-
1922 created if it doesn't exist.
1926 This parameter specifies what type of object to create, a hash or array. Use
1927 one of these two constants: C<DBM::Deep-E<gt>TYPE_HASH> or C<DBM::Deep-E<gt>TYPE_ARRAY>.
1928 This only takes effect when beginning a new file. This is an optional
1929 parameter, and defaults to C<DBM::Deep-E<gt>TYPE_HASH>.
1933 Specifies whether locking is to be enabled. DBM::Deep uses Perl's Fnctl flock()
1934 function to lock the database in exclusive mode for writes, and shared mode for
1935 reads. Pass any true value to enable. This affects the base DB handle I<and
1936 any child hashes or arrays> that use the same DB file. This is an optional
1937 parameter, and defaults to 0 (disabled). See L<LOCKING> below for more.
1941 Specifies whether autoflush is to be enabled on the underlying FileHandle.
1942 This obviously slows down write operations, but is required if you may have
1943 multiple processes accessing the same DB file (also consider enable I<locking>
1944 or at least I<volatile>). Pass any true value to enable. This is an optional
1945 parameter, and defaults to 0 (disabled).
1949 If I<volatile> mode is enabled, DBM::Deep will stat() the DB file before each
1950 STORE() operation. This is required if an outside force may change the size of
1951 the file between transactions. Locking also implicitly enables volatile. This
1952 is useful if you want to use a different locking system or write your own. Pass
1953 any true value to enable. This is an optional parameter, and defaults to 0
1958 If I<autobless> mode is enabled, DBM::Deep will preserve blessed hashes, and
1959 restore them when fetched. This is an B<experimental> feature, and does have
1960 side-effects. Basically, when hashes are re-blessed into their original
1961 classes, they are no longer blessed into the DBM::Deep class! So you won't be
1962 able to call any DBM::Deep methods on them. You have been warned.
1963 This is an optional parameter, and defaults to 0 (disabled).
1967 See L<FILTERS> below.
1971 Setting I<debug> mode will make all errors non-fatal, dump them out to
1972 STDERR, and continue on. This is for debugging purposes only, and probably
1973 not what you want. This is an optional parameter, and defaults to 0 (disabled).
1977 Instead of passing a file path, you can instead pass a handle to an pre-opened
1978 filehandle. Note: Beware of using the magick *DATA handle, as this actually
1979 contains your entire Perl script, as well as the data following the __DATA__
1980 marker. This will not work, because DBM::Deep uses absolute seek()s into the
1981 file. Instead, consider reading *DATA into an IO::Scalar handle, then passing
1986 =head1 TIE INTERFACE
1988 With DBM::Deep you can access your databases using Perl's standard hash/array
1989 syntax. Because all DBM::Deep objects are I<tied> to hashes or arrays, you can treat
1990 them as such. DBM::Deep will intercept all reads/writes and direct them to the right
1991 place -- the DB file. This has nothing to do with the L<TIE CONSTRUCTION>
1992 section above. This simply tells you how to use DBM::Deep using regular hashes
1993 and arrays, rather than calling functions like C<get()> and C<put()> (although those
1994 work too). It is entirely up to you how to want to access your databases.
1998 You can treat any DBM::Deep object like a normal Perl hash reference. Add keys,
1999 or even nested hashes (or arrays) using standard Perl syntax:
2001 my $db = DBM::Deep->new( "foo.db" );
2003 $db->{mykey} = "myvalue";
2005 $db->{myhash}->{subkey} = "subvalue";
2007 print $db->{myhash}->{subkey} . "\n";
2009 You can even step through hash keys using the normal Perl C<keys()> function:
2011 foreach my $key (keys %$db) {
2012 print "$key: " . $db->{$key} . "\n";
2015 Remember that Perl's C<keys()> function extracts I<every> key from the hash and
2016 pushes them onto an array, all before the loop even begins. If you have an
2017 extra large hash, this may exhaust Perl's memory. Instead, consider using
2018 Perl's C<each()> function, which pulls keys/values one at a time, using very
2021 while (my ($key, $value) = each %$db) {
2022 print "$key: $value\n";
2025 Please note that when using C<each()>, you should always pass a direct
2026 hash reference, not a lookup. Meaning, you should B<never> do this:
2029 while (my ($key, $value) = each %{$db->{foo}}) { # BAD
2031 This causes an infinite loop, because for each iteration, Perl is calling
2032 FETCH() on the $db handle, resulting in a "new" hash for foo every time, so
2033 it effectively keeps returning the first key over and over again. Instead,
2034 assign a temporary variable to C<$db->{foo}>, then pass that to each().
2038 As with hashes, you can treat any DBM::Deep object like a normal Perl array
2039 reference. This includes inserting, removing and manipulating elements,
2040 and the C<push()>, C<pop()>, C<shift()>, C<unshift()> and C<splice()> functions.
2041 The object must have first been created using type C<DBM::Deep-E<gt>TYPE_ARRAY>,
2042 or simply be a nested array reference inside a hash. Example:
2044 my $db = DBM::Deep->new(
2045 file => "foo-array.db",
2046 type => DBM::Deep->TYPE_ARRAY
2050 push @$db, "bar", "baz";
2051 unshift @$db, "bah";
2053 my $last_elem = pop @$db; # baz
2054 my $first_elem = shift @$db; # bah
2055 my $second_elem = $db->[1]; # bar
2057 my $num_elements = scalar @$db;
2061 In addition to the I<tie()> interface, you can also use a standard OO interface
2062 to manipulate all aspects of DBM::Deep databases. Each type of object (hash or
2063 array) has its own methods, but both types share the following common methods:
2064 C<put()>, C<get()>, C<exists()>, C<delete()> and C<clear()>.
2070 Stores a new hash key/value pair, or sets an array element value. Takes two
2071 arguments, the hash key or array index, and the new value. The value can be
2072 a scalar, hash ref or array ref. Returns true on success, false on failure.
2074 $db->put("foo", "bar"); # for hashes
2075 $db->put(1, "bar"); # for arrays
2079 Fetches the value of a hash key or array element. Takes one argument: the hash
2080 key or array index. Returns a scalar, hash ref or array ref, depending on the
2083 my $value = $db->get("foo"); # for hashes
2084 my $value = $db->get(1); # for arrays
2088 Checks if a hash key or array index exists. Takes one argument: the hash key
2089 or array index. Returns true if it exists, false if not.
2091 if ($db->exists("foo")) { print "yay!\n"; } # for hashes
2092 if ($db->exists(1)) { print "yay!\n"; } # for arrays
2096 Deletes one hash key/value pair or array element. Takes one argument: the hash
2097 key or array index. Returns true on success, false if not found. For arrays,
2098 the remaining elements located after the deleted element are NOT moved over.
2099 The deleted element is essentially just undefined, which is exactly how Perl's
2100 internal arrays work. Please note that the space occupied by the deleted
2101 key/value or element is B<not> reused again -- see L<UNUSED SPACE RECOVERY>
2102 below for details and workarounds.
2104 $db->delete("foo"); # for hashes
2105 $db->delete(1); # for arrays
2109 Deletes B<all> hash keys or array elements. Takes no arguments. No return
2110 value. Please note that the space occupied by the deleted keys/values or
2111 elements is B<not> reused again -- see L<UNUSED SPACE RECOVERY> below for
2112 details and workarounds.
2114 $db->clear(); # hashes or arrays
2120 For hashes, DBM::Deep supports all the common methods described above, and the
2121 following additional methods: C<first_key()> and C<next_key()>.
2127 Returns the "first" key in the hash. As with built-in Perl hashes, keys are
2128 fetched in an undefined order (which appears random). Takes no arguments,
2129 returns the key as a scalar value.
2131 my $key = $db->first_key();
2135 Returns the "next" key in the hash, given the previous one as the sole argument.
2136 Returns undef if there are no more keys to be fetched.
2138 $key = $db->next_key($key);
2142 Here are some examples of using hashes:
2144 my $db = DBM::Deep->new( "foo.db" );
2146 $db->put("foo", "bar");
2147 print "foo: " . $db->get("foo") . "\n";
2149 $db->put("baz", {}); # new child hash ref
2150 $db->get("baz")->put("buz", "biz");
2151 print "buz: " . $db->get("baz")->get("buz") . "\n";
2153 my $key = $db->first_key();
2155 print "$key: " . $db->get($key) . "\n";
2156 $key = $db->next_key($key);
2159 if ($db->exists("foo")) { $db->delete("foo"); }
2163 For arrays, DBM::Deep supports all the common methods described above, and the
2164 following additional methods: C<length()>, C<push()>, C<pop()>, C<shift()>,
2165 C<unshift()> and C<splice()>.
2171 Returns the number of elements in the array. Takes no arguments.
2173 my $len = $db->length();
2177 Adds one or more elements onto the end of the array. Accepts scalars, hash
2178 refs or array refs. No return value.
2180 $db->push("foo", "bar", {});
2184 Fetches the last element in the array, and deletes it. Takes no arguments.
2185 Returns undef if array is empty. Returns the element value.
2187 my $elem = $db->pop();
2191 Fetches the first element in the array, deletes it, then shifts all the
2192 remaining elements over to take up the space. Returns the element value. This
2193 method is not recommended with large arrays -- see L<LARGE ARRAYS> below for
2196 my $elem = $db->shift();
2200 Inserts one or more elements onto the beginning of the array, shifting all
2201 existing elements over to make room. Accepts scalars, hash refs or array refs.
2202 No return value. This method is not recommended with large arrays -- see
2203 <LARGE ARRAYS> below for details.
2205 $db->unshift("foo", "bar", {});
2209 Performs exactly like Perl's built-in function of the same name. See L<perldoc
2210 -f splice> for usage -- it is too complicated to document here. This method is
2211 not recommended with large arrays -- see L<LARGE ARRAYS> below for details.
2215 Here are some examples of using arrays:
2217 my $db = DBM::Deep->new(
2219 type => DBM::Deep->TYPE_ARRAY
2222 $db->push("bar", "baz");
2223 $db->unshift("foo");
2226 my $len = $db->length();
2227 print "length: $len\n"; # 4
2229 for (my $k=0; $k<$len; $k++) {
2230 print "$k: " . $db->get($k) . "\n";
2233 $db->splice(1, 2, "biz", "baf");
2235 while (my $elem = shift @$db) {
2236 print "shifted: $elem\n";
2241 Enable automatic file locking by passing a true value to the C<locking>
2242 parameter when constructing your DBM::Deep object (see L<SETUP> above).
2244 my $db = DBM::Deep->new(
2249 This causes DBM::Deep to C<flock()> the underlying FileHandle object with exclusive
2250 mode for writes, and shared mode for reads. This is required if you have
2251 multiple processes accessing the same database file, to avoid file corruption.
2252 Please note that C<flock()> does NOT work for files over NFS. See L<DB OVER
2253 NFS> below for more.
2255 =head2 EXPLICIT LOCKING
2257 You can explicitly lock a database, so it remains locked for multiple
2258 transactions. This is done by calling the C<lock()> method, and passing an
2259 optional lock mode argument (defaults to exclusive mode). This is particularly
2260 useful for things like counters, where the current value needs to be fetched,
2261 then incremented, then stored again.
2264 my $counter = $db->get("counter");
2266 $db->put("counter", $counter);
2275 You can pass C<lock()> an optional argument, which specifies which mode to use
2276 (exclusive or shared). Use one of these two constants: C<DBM::Deep-E<gt>LOCK_EX>
2277 or C<DBM::Deep-E<gt>LOCK_SH>. These are passed directly to C<flock()>, and are the
2278 same as the constants defined in Perl's C<Fcntl> module.
2280 $db->lock( DBM::Deep->LOCK_SH );
2284 If you want to implement your own file locking scheme, be sure to create your
2285 DBM::Deep objects setting the C<volatile> option to true. This hints to DBM::Deep
2286 that the DB file may change between transactions. See L<LOW-LEVEL ACCESS>
2289 =head1 IMPORTING/EXPORTING
2291 You can import existing complex structures by calling the C<import()> method,
2292 and export an entire database into an in-memory structure using the C<export()>
2293 method. Both are examined here.
2297 Say you have an existing hash with nested hashes/arrays inside it. Instead of
2298 walking the structure and adding keys/elements to the database as you go,
2299 simply pass a reference to the C<import()> method. This recursively adds
2300 everything to an existing DBM::Deep object for you. Here is an example:
2305 array1 => [ "elem0", "elem1", "elem2" ],
2307 subkey1 => "subvalue1",
2308 subkey2 => "subvalue2"
2312 my $db = DBM::Deep->new( "foo.db" );
2313 $db->import( $struct );
2315 print $db->{key1} . "\n"; # prints "value1"
2317 This recursively imports the entire C<$struct> object into C<$db>, including
2318 all nested hashes and arrays. If the DBM::Deep object contains exsiting data,
2319 keys are merged with the existing ones, replacing if they already exist.
2320 The C<import()> method can be called on any database level (not just the base
2321 level), and works with both hash and array DB types.
2325 B<Note:> Make sure your existing structure has no circular references in it.
2326 These will cause an infinite loop when importing.
2330 Calling the C<export()> method on an existing DBM::Deep object will return
2331 a reference to a new in-memory copy of the database. The export is done
2332 recursively, so all nested hashes/arrays are all exported to standard Perl
2333 objects. Here is an example:
2335 my $db = DBM::Deep->new( "foo.db" );
2337 $db->{key1} = "value1";
2338 $db->{key2} = "value2";
2340 $db->{hash1}->{subkey1} = "subvalue1";
2341 $db->{hash1}->{subkey2} = "subvalue2";
2343 my $struct = $db->export();
2345 print $struct->{key1} . "\n"; # prints "value1"
2347 This makes a complete copy of the database in memory, and returns a reference
2348 to it. The C<export()> method can be called on any database level (not just
2349 the base level), and works with both hash and array DB types. Be careful of
2350 large databases -- you can store a lot more data in a DBM::Deep object than an
2351 in-memory Perl structure.
2355 B<Note:> Make sure your database has no circular references in it.
2356 These will cause an infinite loop when exporting.
2360 DBM::Deep has a number of hooks where you can specify your own Perl function
2361 to perform filtering on incoming or outgoing data. This is a perfect
2362 way to extend the engine, and implement things like real-time compression or
2363 encryption. Filtering applies to the base DB level, and all child hashes /
2364 arrays. Filter hooks can be specified when your DBM::Deep object is first
2365 constructed, or by calling the C<set_filter()> method at any time. There are
2366 four available filter hooks, described below:
2370 =item * filter_store_key
2372 This filter is called whenever a hash key is stored. It
2373 is passed the incoming key, and expected to return a transformed key.
2375 =item * filter_store_value
2377 This filter is called whenever a hash key or array element is stored. It
2378 is passed the incoming value, and expected to return a transformed value.
2380 =item * filter_fetch_key
2382 This filter is called whenever a hash key is fetched (i.e. via
2383 C<first_key()> or C<next_key()>). It is passed the transformed key,
2384 and expected to return the plain key.
2386 =item * filter_fetch_value
2388 This filter is called whenever a hash key or array element is fetched.
2389 It is passed the transformed value, and expected to return the plain value.
2393 Here are the two ways to setup a filter hook:
2395 my $db = DBM::Deep->new(
2397 filter_store_value => \&my_filter_store,
2398 filter_fetch_value => \&my_filter_fetch
2403 $db->set_filter( "filter_store_value", \&my_filter_store );
2404 $db->set_filter( "filter_fetch_value", \&my_filter_fetch );
2406 Your filter function will be called only when dealing with SCALAR keys or
2407 values. When nested hashes and arrays are being stored/fetched, filtering
2408 is bypassed. Filters are called as static functions, passed a single SCALAR
2409 argument, and expected to return a single SCALAR value. If you want to
2410 remove a filter, set the function reference to C<undef>:
2412 $db->set_filter( "filter_store_value", undef );
2414 =head2 REAL-TIME ENCRYPTION EXAMPLE
2416 Here is a working example that uses the I<Crypt::Blowfish> module to
2417 do real-time encryption / decryption of keys & values with DBM::Deep Filters.
2418 Please visit L<http://search.cpan.org/search?module=Crypt::Blowfish> for more
2419 on I<Crypt::Blowfish>. You'll also need the I<Crypt::CBC> module.
2422 use Crypt::Blowfish;
2425 my $cipher = Crypt::CBC->new({
2426 'key' => 'my secret key',
2427 'cipher' => 'Blowfish',
2429 'regenerate_key' => 0,
2430 'padding' => 'space',
2434 my $db = DBM::Deep->new(
2435 file => "foo-encrypt.db",
2436 filter_store_key => \&my_encrypt,
2437 filter_store_value => \&my_encrypt,
2438 filter_fetch_key => \&my_decrypt,
2439 filter_fetch_value => \&my_decrypt,
2442 $db->{key1} = "value1";
2443 $db->{key2} = "value2";
2444 print "key1: " . $db->{key1} . "\n";
2445 print "key2: " . $db->{key2} . "\n";
2451 return $cipher->encrypt( $_[0] );
2454 return $cipher->decrypt( $_[0] );
2457 =head2 REAL-TIME COMPRESSION EXAMPLE
2459 Here is a working example that uses the I<Compress::Zlib> module to do real-time
2460 compression / decompression of keys & values with DBM::Deep Filters.
2461 Please visit L<http://search.cpan.org/search?module=Compress::Zlib> for
2462 more on I<Compress::Zlib>.
2467 my $db = DBM::Deep->new(
2468 file => "foo-compress.db",
2469 filter_store_key => \&my_compress,
2470 filter_store_value => \&my_compress,
2471 filter_fetch_key => \&my_decompress,
2472 filter_fetch_value => \&my_decompress,
2475 $db->{key1} = "value1";
2476 $db->{key2} = "value2";
2477 print "key1: " . $db->{key1} . "\n";
2478 print "key2: " . $db->{key2} . "\n";
2484 return Compress::Zlib::memGzip( $_[0] ) ;
2487 return Compress::Zlib::memGunzip( $_[0] ) ;
2490 B<Note:> Filtering of keys only applies to hashes. Array "keys" are
2491 actually numerical index numbers, and are not filtered.
2493 =head1 ERROR HANDLING
2495 Most DBM::Deep methods return a true value for success, and call die() on
2496 failure. You can wrap calls in an eval block to catch the die. Also, the
2497 actual error message is stored in an internal scalar, which can be fetched by
2498 calling the C<error()> method.
2500 my $db = DBM::Deep->new( "foo.db" ); # create hash
2501 eval { $db->push("foo"); }; # ILLEGAL -- push is array-only call
2503 print $db->error(); # prints error message
2505 You can then call C<clear_error()> to clear the current error state.
2509 If you set the C<debug> option to true when creating your DBM::Deep object,
2510 all errors are considered NON-FATAL, and dumped to STDERR. This is only
2511 for debugging purposes.
2513 =head1 LARGEFILE SUPPORT
2515 If you have a 64-bit system, and your Perl is compiled with both LARGEFILE
2516 and 64-bit support, you I<may> be able to create databases larger than 2 GB.
2517 DBM::Deep by default uses 32-bit file offset tags, but these can be changed
2518 by calling the static C<set_pack()> method before you do anything else.
2520 DBM::Deep::set_pack(8, 'Q');
2522 This tells DBM::Deep to pack all file offsets with 8-byte (64-bit) quad words
2523 instead of 32-bit longs. After setting these values your DB files have a
2524 theoretical maximum size of 16 XB (exabytes).
2528 B<Note:> Changing these values will B<NOT> work for existing database files.
2529 Only change this for new files, and make sure it stays set consistently
2530 throughout the file's life. If you do set these values, you can no longer
2531 access 32-bit DB files. You can, however, call C<set_pack(4, 'N')> to change
2532 back to 32-bit mode.
2536 B<Note:> I have not personally tested files > 2 GB -- all my systems have
2537 only a 32-bit Perl. However, I have received user reports that this does
2540 =head1 LOW-LEVEL ACCESS
2542 If you require low-level access to the underlying FileHandle that DBM::Deep uses,
2543 you can call the C<fh()> method, which returns the handle:
2547 This method can be called on the root level of the datbase, or any child
2548 hashes or arrays. All levels share a I<root> structure, which contains things
2549 like the FileHandle, a reference counter, and all your options you specified
2550 when you created the object. You can get access to this root structure by
2551 calling the C<root()> method.
2553 my $root = $db->root();
2555 This is useful for changing options after the object has already been created,
2556 such as enabling/disabling locking, volatile or debug modes. You can also
2557 store your own temporary user data in this structure (be wary of name
2558 collision), which is then accessible from any child hash or array.
2560 =head1 CUSTOM DIGEST ALGORITHM
2562 DBM::Deep by default uses the I<Message Digest 5> (MD5) algorithm for hashing
2563 keys. However you can override this, and use another algorithm (such as SHA-256)
2564 or even write your own. But please note that DBM::Deep currently expects zero
2565 collisions, so your algorithm has to be I<perfect>, so to speak.
2566 Collision detection may be introduced in a later version.
2570 You can specify a custom digest algorithm by calling the static C<set_digest()>
2571 function, passing a reference to a subroutine, and the length of the algorithm's
2572 hashes (in bytes). This is a global static function, which affects ALL DBM::Deep
2573 objects. Here is a working example that uses a 256-bit hash from the
2574 I<Digest::SHA256> module. Please see
2575 L<http://search.cpan.org/search?module=Digest::SHA256> for more.
2580 my $context = Digest::SHA256::new(256);
2582 DBM::Deep::set_digest( \&my_digest, 32 );
2584 my $db = DBM::Deep->new( "foo-sha.db" );
2586 $db->{key1} = "value1";
2587 $db->{key2} = "value2";
2588 print "key1: " . $db->{key1} . "\n";
2589 print "key2: " . $db->{key2} . "\n";
2595 return substr( $context->hash($_[0]), 0, 32 );
2598 B<Note:> Your returned digest strings must be B<EXACTLY> the number
2599 of bytes you specify in the C<set_digest()> function (in this case 32).
2601 =head1 CIRCULAR REFERENCES
2603 DBM::Deep has B<experimental> support for circular references. Meaning you
2604 can have a nested hash key or array element that points to a parent object.
2605 This relationship is stored in the DB file, and is preserved between sessions.
2608 my $db = DBM::Deep->new( "foo.db" );
2611 $db->{circle} = $db; # ref to self
2613 print $db->{foo} . "\n"; # prints "foo"
2614 print $db->{circle}->{foo} . "\n"; # prints "foo" again
2616 One catch is, passing the object to a function that recursively walks the
2617 object tree (such as I<Data::Dumper> or even the built-in C<optimize()> or
2618 C<export()> methods) will result in an infinite loop. The other catch is,
2619 if you fetch the I<key> of a circular reference (i.e. using the C<first_key()>
2620 or C<next_key()> methods), you will get the I<target object's key>, not the
2621 ref's key. This gets even more interesting with the above example, where
2622 the I<circle> key points to the base DB object, which technically doesn't
2623 have a key. So I made DBM::Deep return "[base]" as the key name in that
2626 =head1 CAVEATS / ISSUES / BUGS
2628 This section describes all the known issues with DBM::Deep. It you have found
2629 something that is not listed here, please send e-mail to L<jhuckaby@cpan.org>.
2631 =head2 UNUSED SPACE RECOVERY
2633 One major caveat with DBM::Deep is that space occupied by existing keys and
2634 values is not recovered when they are deleted. Meaning if you keep deleting
2635 and adding new keys, your file will continuously grow. I am working on this,
2636 but in the meantime you can call the built-in C<optimize()> method from time to
2637 time (perhaps in a crontab or something) to recover all your unused space.
2639 $db->optimize(); # returns true on success
2641 This rebuilds the ENTIRE database into a new file, then moves it on top of
2642 the original. The new file will have no unused space, thus it will take up as
2643 little disk space as possible. Please note that this operation can take
2644 a long time for large files, and you need enough disk space to temporarily hold
2645 2 copies of your DB file. The temporary file is created in the same directory
2646 as the original, named with a ".tmp" extension, and is deleted when the
2647 operation completes. Oh, and if locking is enabled, the DB is automatically
2648 locked for the entire duration of the copy.
2652 B<WARNING:> Only call optimize() on the top-level node of the database, and
2653 make sure there are no child references lying around. DBM::Deep keeps a reference
2654 counter, and if it is greater than 1, optimize() will abort and return undef.
2656 =head2 AUTOVIVIFICATION
2658 Unfortunately, autovivification doesn't work with tied hashes. This appears to
2659 be a bug in Perl's tie() system, as I<Jakob Schmidt> encountered the very same
2660 issue with his I<DWH_FIle> module (see L<http://search.cpan.org/search?module=DWH_File>),
2661 and it is also mentioned in the BUGS section for the I<MLDBM> module <see
2662 L<http://search.cpan.org/search?module=MLDBM>). Basically, on a new db file,
2665 $db->{foo}->{bar} = "hello";
2667 Since "foo" doesn't exist, you cannot add "bar" to it. You end up with "foo"
2668 being an empty hash. Try this instead, which works fine:
2670 $db->{foo} = { bar => "hello" };
2672 As of Perl 5.8.7, this bug still exists. I have walked very carefully through
2673 the execution path, and Perl indeed passes an empty hash to the STORE() method.
2674 Probably a bug in Perl.
2676 =head2 FILE CORRUPTION
2678 The current level of error handling in DBM::Deep is minimal. Files I<are> checked
2679 for a 32-bit signature when opened, but other corruption in files can cause
2680 segmentation faults. DBM::Deep may try to seek() past the end of a file, or get
2681 stuck in an infinite loop depending on the level of corruption. File write
2682 operations are not checked for failure (for speed), so if you happen to run
2683 out of disk space, DBM::Deep will probably fail in a bad way. These things will
2684 be addressed in a later version of DBM::Deep.
2688 Beware of using DB files over NFS. DBM::Deep uses flock(), which works well on local
2689 filesystems, but will NOT protect you from file corruption over NFS. I've heard
2690 about setting up your NFS server with a locking daemon, then using lockf() to
2691 lock your files, but your milage may vary there as well. From what I
2692 understand, there is no real way to do it. However, if you need access to the
2693 underlying FileHandle in DBM::Deep for using some other kind of locking scheme like
2694 lockf(), see the L<LOW-LEVEL ACCESS> section above.
2696 =head2 COPYING OBJECTS
2698 Beware of copying tied objects in Perl. Very strange things can happen.
2699 Instead, use DBM::Deep's C<clone()> method which safely copies the object and
2700 returns a new, blessed, tied hash or array to the same level in the DB.
2702 my $copy = $db->clone();
2706 Beware of using C<shift()>, C<unshift()> or C<splice()> with large arrays.
2707 These functions cause every element in the array to move, which can be murder
2708 on DBM::Deep, as every element has to be fetched from disk, then stored again in
2709 a different location. This may be addressed in a later version.
2713 This section discusses DBM::Deep's speed and memory usage.
2717 Obviously, DBM::Deep isn't going to be as fast as some C-based DBMs, such as
2718 the almighty I<BerkeleyDB>. But it makes up for it in features like true
2719 multi-level hash/array support, and cross-platform FTPable files. Even so,
2720 DBM::Deep is still pretty fast, and the speed stays fairly consistent, even
2721 with huge databases. Here is some test data:
2723 Adding 1,000,000 keys to new DB file...
2725 At 100 keys, avg. speed is 2,703 keys/sec
2726 At 200 keys, avg. speed is 2,642 keys/sec
2727 At 300 keys, avg. speed is 2,598 keys/sec
2728 At 400 keys, avg. speed is 2,578 keys/sec
2729 At 500 keys, avg. speed is 2,722 keys/sec
2730 At 600 keys, avg. speed is 2,628 keys/sec
2731 At 700 keys, avg. speed is 2,700 keys/sec
2732 At 800 keys, avg. speed is 2,607 keys/sec
2733 At 900 keys, avg. speed is 2,190 keys/sec
2734 At 1,000 keys, avg. speed is 2,570 keys/sec
2735 At 2,000 keys, avg. speed is 2,417 keys/sec
2736 At 3,000 keys, avg. speed is 1,982 keys/sec
2737 At 4,000 keys, avg. speed is 1,568 keys/sec
2738 At 5,000 keys, avg. speed is 1,533 keys/sec
2739 At 6,000 keys, avg. speed is 1,787 keys/sec
2740 At 7,000 keys, avg. speed is 1,977 keys/sec
2741 At 8,000 keys, avg. speed is 2,028 keys/sec
2742 At 9,000 keys, avg. speed is 2,077 keys/sec
2743 At 10,000 keys, avg. speed is 2,031 keys/sec
2744 At 20,000 keys, avg. speed is 1,970 keys/sec
2745 At 30,000 keys, avg. speed is 2,050 keys/sec
2746 At 40,000 keys, avg. speed is 2,073 keys/sec
2747 At 50,000 keys, avg. speed is 1,973 keys/sec
2748 At 60,000 keys, avg. speed is 1,914 keys/sec
2749 At 70,000 keys, avg. speed is 2,091 keys/sec
2750 At 80,000 keys, avg. speed is 2,103 keys/sec
2751 At 90,000 keys, avg. speed is 1,886 keys/sec
2752 At 100,000 keys, avg. speed is 1,970 keys/sec
2753 At 200,000 keys, avg. speed is 2,053 keys/sec
2754 At 300,000 keys, avg. speed is 1,697 keys/sec
2755 At 400,000 keys, avg. speed is 1,838 keys/sec
2756 At 500,000 keys, avg. speed is 1,941 keys/sec
2757 At 600,000 keys, avg. speed is 1,930 keys/sec
2758 At 700,000 keys, avg. speed is 1,735 keys/sec
2759 At 800,000 keys, avg. speed is 1,795 keys/sec
2760 At 900,000 keys, avg. speed is 1,221 keys/sec
2761 At 1,000,000 keys, avg. speed is 1,077 keys/sec
2763 This test was performed on a PowerMac G4 1gHz running Mac OS X 10.3.2 & Perl
2764 5.8.1, with an 80GB Ultra ATA/100 HD spinning at 7200RPM. The hash keys and
2765 values were between 6 - 12 chars in length. The DB file ended up at 210MB.
2766 Run time was 12 min 3 sec.
2770 One of the great things about DBM::Deep is that it uses very little memory.
2771 Even with huge databases (1,000,000+ keys) you will not see much increased
2772 memory on your process. DBM::Deep relies solely on the filesystem for storing
2773 and fetching data. Here is output from I</usr/bin/top> before even opening a
2776 PID USER PRI NI SIZE RSS SHARE STAT %CPU %MEM TIME COMMAND
2777 22831 root 11 0 2716 2716 1296 R 0.0 0.2 0:07 perl
2779 Basically the process is taking 2,716K of memory. And here is the same
2780 process after storing and fetching 1,000,000 keys:
2782 PID USER PRI NI SIZE RSS SHARE STAT %CPU %MEM TIME COMMAND
2783 22831 root 14 0 2772 2772 1328 R 0.0 0.2 13:32 perl
2785 Notice the memory usage increased by only 56K. Test was performed on a 700mHz
2786 x86 box running Linux RedHat 7.2 & Perl 5.6.1.
2788 =head1 DB FILE FORMAT
2790 In case you were interested in the underlying DB file format, it is documented
2791 here in this section. You don't need to know this to use the module, it's just
2792 included for reference.
2796 DBM::Deep files always start with a 32-bit signature to identify the file type.
2797 This is at offset 0. The signature is "DPDB" in network byte order. This is
2798 checked when the file is opened.
2802 The DBM::Deep file is in a I<tagged format>, meaning each section of the file
2803 has a standard header containing the type of data, the length of data, and then
2804 the data itself. The type is a single character (1 byte), the length is a
2805 32-bit unsigned long in network byte order, and the data is, well, the data.
2806 Here is how it unfolds:
2810 Immediately after the 32-bit file signature is the I<Master Index> record.
2811 This is a standard tag header followed by 1024 bytes (in 32-bit mode) or 2048
2812 bytes (in 64-bit mode) of data. The type is I<H> for hash or I<A> for array,
2813 depending on how the DBM::Deep object was constructed.
2817 The index works by looking at a I<MD5 Hash> of the hash key (or array index
2818 number). The first 8-bit char of the MD5 signature is the offset into the
2819 index, multipled by 4 in 32-bit mode, or 8 in 64-bit mode. The value of the
2820 index element is a file offset of the next tag for the key/element in question,
2821 which is usually a I<Bucket List> tag (see below).
2825 The next tag I<could> be another index, depending on how many keys/elements
2826 exist. See L<RE-INDEXING> below for details.
2830 A I<Bucket List> is a collection of 16 MD5 hashes for keys/elements, plus
2831 file offsets to where the actual data is stored. It starts with a standard
2832 tag header, with type I<B>, and a data size of 320 bytes in 32-bit mode, or
2833 384 bytes in 64-bit mode. Each MD5 hash is stored in full (16 bytes), plus
2834 the 32-bit or 64-bit file offset for the I<Bucket> containing the actual data.
2835 When the list fills up, a I<Re-Index> operation is performed (See
2836 L<RE-INDEXING> below).
2840 A I<Bucket> is a tag containing a key/value pair (in hash mode), or a
2841 index/value pair (in array mode). It starts with a standard tag header with
2842 type I<D> for scalar data (string, binary, etc.), or it could be a nested
2843 hash (type I<H>) or array (type I<A>). The value comes just after the tag
2844 header. The size reported in the tag header is only for the value, but then,
2845 just after the value is another size (32-bit unsigned long) and then the plain
2846 key itself. Since the value is likely to be fetched more often than the plain
2847 key, I figured it would be I<slightly> faster to store the value first.
2851 If the type is I<H> (hash) or I<A> (array), the value is another I<Master Index>
2852 record for the nested structure, where the process begins all over again.
2856 After a I<Bucket List> grows to 16 records, its allocated space in the file is
2857 exhausted. Then, when another key/element comes in, the list is converted to a
2858 new index record. However, this index will look at the next char in the MD5
2859 hash, and arrange new Bucket List pointers accordingly. This process is called
2860 I<Re-Indexing>. Basically, a new index tag is created at the file EOF, and all
2861 17 (16 + new one) keys/elements are removed from the old Bucket List and
2862 inserted into the new index. Several new Bucket Lists are created in the
2863 process, as a new MD5 char from the key is being examined (it is unlikely that
2864 the keys will all share the same next char of their MD5s).
2868 Because of the way the I<MD5> algorithm works, it is impossible to tell exactly
2869 when the Bucket Lists will turn into indexes, but the first round tends to
2870 happen right around 4,000 keys. You will see a I<slight> decrease in
2871 performance here, but it picks back up pretty quick (see L<SPEED> above). Then
2872 it takes B<a lot> more keys to exhaust the next level of Bucket Lists. It's
2873 right around 900,000 keys. This process can continue nearly indefinitely --
2874 right up until the point the I<MD5> signatures start colliding with each other,
2875 and this is B<EXTREMELY> rare -- like winning the lottery 5 times in a row AND
2876 getting struck by lightning while you are walking to cash in your tickets.
2877 Theoretically, since I<MD5> hashes are 128-bit values, you I<could> have up to
2878 340,282,366,921,000,000,000,000,000,000,000,000,000 keys/elements (I believe
2879 this is 340 unodecillion, but don't quote me).
2883 When a new key/element is stored, the key (or index number) is first ran through
2884 I<Digest::MD5> to get a 128-bit signature (example, in hex:
2885 b05783b0773d894396d475ced9d2f4f6). Then, the I<Master Index> record is checked
2886 for the first char of the signature (in this case I<b>). If it does not exist,
2887 a new I<Bucket List> is created for our key (and the next 15 future keys that
2888 happen to also have I<b> as their first MD5 char). The entire MD5 is written
2889 to the I<Bucket List> along with the offset of the new I<Bucket> record (EOF at
2890 this point, unless we are replacing an existing I<Bucket>), where the actual
2891 data will be stored.
2895 Fetching an existing key/element involves getting a I<Digest::MD5> of the key
2896 (or index number), then walking along the indexes. If there are enough
2897 keys/elements in this DB level, there might be nested indexes, each linked to
2898 a particular char of the MD5. Finally, a I<Bucket List> is pointed to, which
2899 contains up to 16 full MD5 hashes. Each is checked for equality to the key in
2900 question. If we found a match, the I<Bucket> tag is loaded, where the value and
2901 plain key are stored.
2905 Fetching the plain key occurs when calling the I<first_key()> and I<next_key()>
2906 methods. In this process the indexes are walked systematically, and each key
2907 fetched in increasing MD5 order (which is why it appears random). Once the
2908 I<Bucket> is found, the value is skipped the plain key returned instead.
2909 B<Note:> Do not count on keys being fetched as if the MD5 hashes were
2910 alphabetically sorted. This only happens on an index-level -- as soon as the
2911 I<Bucket Lists> are hit, the keys will come out in the order they went in --
2912 so it's pretty much undefined how the keys will come out -- just like Perl's
2915 =head1 CODE COVERAGE
2917 I use B<Devel::Cover> to test the code coverage of my tests, below is the B<Devel::Cover> report on this
2918 module's test suite.
2920 ---------------------------- ------ ------ ------ ------ ------ ------ ------
2921 File stmt bran cond sub pod time total
2922 ---------------------------- ------ ------ ------ ------ ------ ------ ------
2923 blib/lib/DBM/Deep.pm 94.9 84.5 77.8 100.0 11.1 100.0 89.7
2924 Total 94.9 84.5 77.8 100.0 11.1 100.0 89.7
2925 ---------------------------- ------ ------ ------ ------ ------ ------ ------
2929 Joseph Huckaby, L<jhuckaby@cpan.org>
2931 Special thanks to Adam Sah and Rich Gaushell! You know why :-)
2935 perltie(1), Tie::Hash(3), Digest::MD5(3), Fcntl(3), flock(2), lockf(3), nfs(5),
2936 Digest::SHA256(3), Crypt::Blowfish(3), Compress::Zlib(3)
2940 Copyright (c) 2002-2005 Joseph Huckaby. All Rights Reserved.
2941 This is free software, you may use it and distribute it under the
2942 same terms as Perl itself.