1DBM::Deep(3) User Contributed Perl Documentation DBM::Deep(3)
2
3
4
6 DBM::Deep - A pure perl multi-level hash/array DBM
7
9 use DBM::Deep;
10 my $db = DBM::Deep->new( "foo.db" );
11
12 $db->{key} = 'value'; # tie() style
13 print $db->{key};
14
15 $db->put('key' => 'value'); # OO style
16 print $db->get('key');
17
18 # true multi-level support
19 $db->{my_complex} = [
20 'hello', { perl => 'rules' },
21 42, 99,
22 ];
23
25 A unique flat-file database module, written in pure perl. True multi-
26 level hash/array support (unlike MLDBM, which is faked), hybrid OO /
27 tie() interface, cross-platform FTPable files, and quite fast. Can
28 handle millions of keys and unlimited hash levels without significant
29 slow-down. Written from the ground-up in pure perl -- this is NOT a
30 wrapper around a C-based DBM. Out-of-the-box compatibility with Unix,
31 Mac OS X and Windows.
32
34 Hopefully you are using Perl's excellent CPAN module, which will down‐
35 load and install the module for you. If not, get the tarball, and run
36 these commands:
37
38 tar zxf DBM-Deep-*
39 cd DBM-Deep-*
40 perl Makefile.PL
41 make
42 make test
43 make install
44
46 Construction can be done OO-style (which is the recommended way), or
47 using Perl's tie() function. Both are examined here.
48
49 OO CONSTRUCTION
50
51 The recommended way to construct a DBM::Deep object is to use the new()
52 method, which gets you a blessed, tied hash or array reference.
53
54 my $db = DBM::Deep->new( "foo.db" );
55
56 This opens a new database handle, mapped to the file "foo.db". If this
57 file does not exist, it will automatically be created. DB files are
58 opened in "r+" (read/write) mode, and the type of object returned is a
59 hash, unless otherwise specified (see OPTIONS below).
60
61 You can pass a number of options to the constructor to specify things
62 like locking, autoflush, etc. This is done by passing an inline hash:
63
64 my $db = DBM::Deep->new(
65 file => "foo.db",
66 locking => 1,
67 autoflush => 1
68 );
69
70 Notice that the filename is now specified inside the hash with the
71 "file" parameter, as opposed to being the sole argument to the con‐
72 structor. This is required if any options are specified. See OPTIONS
73 below for the complete list.
74
75 You can also start with an array instead of a hash. For this, you must
76 specify the "type" parameter:
77
78 my $db = DBM::Deep->new(
79 file => "foo.db",
80 type => DBM::Deep->TYPE_ARRAY
81 );
82
83 Note: Specifing the "type" parameter only takes effect when beginning a
84 new DB file. If you create a DBM::Deep object with an existing file,
85 the "type" will be loaded from the file header, and an error will be
86 thrown if the wrong type is passed in.
87
88 TIE CONSTRUCTION
89
90 Alternately, you can create a DBM::Deep handle by using Perl's built-in
91 tie() function. The object returned from tie() can be used to call
92 methods, such as lock() and unlock(), but cannot be used to assign to
93 the DBM::Deep file (as expected with most tie'd objects).
94
95 my %hash;
96 my $db = tie %hash, "DBM::Deep", "foo.db";
97
98 my @array;
99 my $db = tie @array, "DBM::Deep", "bar.db";
100
101 As with the OO constructor, you can replace the DB filename parameter
102 with a hash containing one or more options (see OPTIONS just below for
103 the complete list).
104
105 tie %hash, "DBM::Deep", {
106 file => "foo.db",
107 locking => 1,
108 autoflush => 1
109 };
110
111 OPTIONS
112
113 There are a number of options that can be passed in when constructing
114 your DBM::Deep objects. These apply to both the OO- and tie- based
115 approaches.
116
117 * file
118 Filename of the DB file to link the handle to. You can pass a full
119 absolute filesystem path, partial path, or a plain filename if the
120 file is in the current working directory. This is a required
121 parameter (though q.v. fh).
122
123 * fh
124 If you want, you can pass in the fh instead of the file. This is
125 most useful for doing something like:
126
127 my $db = DBM::Deep->new( { fh => \*DATA } );
128
129 You are responsible for making sure that the fh has been opened
130 appropriately for your needs. If you open it read-only and attempt
131 to write, an exception will be thrown. If you open it write-only or
132 append-only, an exception will be thrown immediately as DBM::Deep
133 needs to read from the fh.
134
135 * file_offset
136 This is the offset within the file that the DBM::Deep db starts.
137 Most of the time, you will not need to set this. However, it's
138 there if you want it.
139
140 If you pass in fh and do not set this, it will be set appropri‐
141 ately.
142
143 * type
144 This parameter specifies what type of object to create, a hash or
145 array. Use one of these two constants: "DBM::Deep->TYPE_HASH" or
146 "DBM::Deep->TYPE_ARRAY". This only takes effect when beginning a
147 new file. This is an optional parameter, and defaults to
148 "DBM::Deep->TYPE_HASH".
149
150 * locking
151 Specifies whether locking is to be enabled. DBM::Deep uses Perl's
152 Fnctl flock() function to lock the database in exclusive mode for
153 writes, and shared mode for reads. Pass any true value to enable.
154 This affects the base DB handle and any child hashes or arrays that
155 use the same DB file. This is an optional parameter, and defaults
156 to 0 (disabled). See LOCKING below for more.
157
158 * autoflush
159 Specifies whether autoflush is to be enabled on the underlying
160 filehandle. This obviously slows down write operations, but is
161 required if you may have multiple processes accessing the same DB
162 file (also consider enable locking). Pass any true value to
163 enable. This is an optional parameter, and defaults to 0 (dis‐
164 abled).
165
166 * autobless
167 If autobless mode is enabled, DBM::Deep will preserve blessed
168 hashes, and restore them when fetched. This is an experimental
169 feature, and does have side-effects. Basically, when hashes are
170 re-blessed into their original classes, they are no longer blessed
171 into the DBM::Deep class! So you won't be able to call any
172 DBM::Deep methods on them. You have been warned. This is an
173 optional parameter, and defaults to 0 (disabled).
174
175 * filter_*
176 See FILTERS below.
177
178 * debug
179 Setting debug mode will make all errors non-fatal, dump them out to
180 STDERR, and continue on. This is for debugging purposes only, and
181 probably not what you want. This is an optional parameter, and
182 defaults to 0 (disabled).
183
184 NOTE: This parameter is considered deprecated and should not be
185 used anymore.
186
188 With DBM::Deep you can access your databases using Perl's standard
189 hash/array syntax. Because all DBM::Deep objects are tied to hashes or
190 arrays, you can treat them as such. DBM::Deep will intercept all
191 reads/writes and direct them to the right place -- the DB file. This
192 has nothing to do with the "TIE CONSTRUCTION" section above. This sim‐
193 ply tells you how to use DBM::Deep using regular hashes and arrays,
194 rather than calling functions like "get()" and "put()" (although those
195 work too). It is entirely up to you how to want to access your data‐
196 bases.
197
198 HASHES
199
200 You can treat any DBM::Deep object like a normal Perl hash reference.
201 Add keys, or even nested hashes (or arrays) using standard Perl syntax:
202
203 my $db = DBM::Deep->new( "foo.db" );
204
205 $db->{mykey} = "myvalue";
206 $db->{myhash} = {};
207 $db->{myhash}->{subkey} = "subvalue";
208
209 print $db->{myhash}->{subkey} . "\n";
210
211 You can even step through hash keys using the normal Perl "keys()"
212 function:
213
214 foreach my $key (keys %$db) {
215 print "$key: " . $db->{$key} . "\n";
216 }
217
218 Remember that Perl's "keys()" function extracts every key from the hash
219 and pushes them onto an array, all before the loop even begins. If you
220 have an extra large hash, this may exhaust Perl's memory. Instead,
221 consider using Perl's "each()" function, which pulls keys/values one at
222 a time, using very little memory:
223
224 while (my ($key, $value) = each %$db) {
225 print "$key: $value\n";
226 }
227
228 Please note that when using "each()", you should always pass a direct
229 hash reference, not a lookup. Meaning, you should never do this:
230
231 # NEVER DO THIS
232 while (my ($key, $value) = each %{$db->{foo}}) { # BAD
233
234 This causes an infinite loop, because for each iteration, Perl is call‐
235 ing FETCH() on the $db handle, resulting in a "new" hash for foo every
236 time, so it effectively keeps returning the first key over and over
237 again. Instead, assign a temporary variable to "$db-"{foo}>, then pass
238 that to each().
239
240 ARRAYS
241
242 As with hashes, you can treat any DBM::Deep object like a normal Perl
243 array reference. This includes inserting, removing and manipulating
244 elements, and the "push()", "pop()", "shift()", "unshift()" and
245 "splice()" functions. The object must have first been created using
246 type "DBM::Deep->TYPE_ARRAY", or simply be a nested array reference
247 inside a hash. Example:
248
249 my $db = DBM::Deep->new(
250 file => "foo-array.db",
251 type => DBM::Deep->TYPE_ARRAY
252 );
253
254 $db->[0] = "foo";
255 push @$db, "bar", "baz";
256 unshift @$db, "bah";
257
258 my $last_elem = pop @$db; # baz
259 my $first_elem = shift @$db; # bah
260 my $second_elem = $db->[1]; # bar
261
262 my $num_elements = scalar @$db;
263
265 In addition to the tie() interface, you can also use a standard OO
266 interface to manipulate all aspects of DBM::Deep databases. Each type
267 of object (hash or array) has its own methods, but both types share the
268 following common methods: "put()", "get()", "exists()", "delete()" and
269 "clear()".
270
271 * new() / clone()
272 These are the constructor and copy-functions.
273
274 * put() / store()
275 Stores a new hash key/value pair, or sets an array element value.
276 Takes two arguments, the hash key or array index, and the new
277 value. The value can be a scalar, hash ref or array ref. Returns
278 true on success, false on failure.
279
280 $db->put("foo", "bar"); # for hashes
281 $db->put(1, "bar"); # for arrays
282
283 * get() / fetch()
284 Fetches the value of a hash key or array element. Takes one argu‐
285 ment: the hash key or array index. Returns a scalar, hash ref or
286 array ref, depending on the data type stored.
287
288 my $value = $db->get("foo"); # for hashes
289 my $value = $db->get(1); # for arrays
290
291 * exists()
292 Checks if a hash key or array index exists. Takes one argument:
293 the hash key or array index. Returns true if it exists, false if
294 not.
295
296 if ($db->exists("foo")) { print "yay!\n"; } # for hashes
297 if ($db->exists(1)) { print "yay!\n"; } # for arrays
298
299 * delete()
300 Deletes one hash key/value pair or array element. Takes one argu‐
301 ment: the hash key or array index. Returns true on success, false
302 if not found. For arrays, the remaining elements located after the
303 deleted element are NOT moved over. The deleted element is essen‐
304 tially just undefined, which is exactly how Perl's internal arrays
305 work. Please note that the space occupied by the deleted key/value
306 or element is not reused again -- see "UNUSED SPACE RECOVERY" below
307 for details and workarounds.
308
309 $db->delete("foo"); # for hashes
310 $db->delete(1); # for arrays
311
312 * clear()
313 Deletes all hash keys or array elements. Takes no arguments. No
314 return value. Please note that the space occupied by the deleted
315 keys/values or elements is not reused again -- see "UNUSED SPACE
316 RECOVERY" below for details and workarounds.
317
318 $db->clear(); # hashes or arrays
319
320 * lock() / unlock()
321 q.v. Locking.
322
323 * optimize()
324 Recover lost disk space.
325
326 * import() / export()
327 Data going in and out.
328
329 * set_digest() / set_pack() / set_filter()
330 q.v. adjusting the interal parameters.
331
332 * error() / clear_error()
333 Error handling methods. These are deprecated and will be removed in
334 1.00. . =back
335
336 HASHES
337
338 For hashes, DBM::Deep supports all the common methods described above,
339 and the following additional methods: "first_key()" and "next_key()".
340
341 * first_key()
342 Returns the "first" key in the hash. As with built-in Perl
343 hashes, keys are fetched in an undefined order (which appears
344 random). Takes no arguments, returns the key as a scalar
345 value.
346
347 my $key = $db->first_key();
348
349 * next_key()
350 Returns the "next" key in the hash, given the previous one as
351 the sole argument. Returns undef if there are no more keys to
352 be fetched.
353
354 $key = $db->next_key($key);
355
356 Here are some examples of using hashes:
357
358 my $db = DBM::Deep->new( "foo.db" );
359
360 $db->put("foo", "bar");
361 print "foo: " . $db->get("foo") . "\n";
362
363 $db->put("baz", {}); # new child hash ref
364 $db->get("baz")->put("buz", "biz");
365 print "buz: " . $db->get("baz")->get("buz") . "\n";
366
367 my $key = $db->first_key();
368 while ($key) {
369 print "$key: " . $db->get($key) . "\n";
370 $key = $db->next_key($key);
371 }
372
373 if ($db->exists("foo")) { $db->delete("foo"); }
374
375 ARRAYS
376
377 For arrays, DBM::Deep supports all the common methods described
378 above, and the following additional methods: "length()", "push()",
379 "pop()", "shift()", "unshift()" and "splice()".
380
381 * length()
382 Returns the number of elements in the array. Takes no argu‐
383 ments.
384
385 my $len = $db->length();
386
387 * push()
388 Adds one or more elements onto the end of the array. Accepts
389 scalars, hash refs or array refs. No return value.
390
391 $db->push("foo", "bar", {});
392
393 * pop()
394 Fetches the last element in the array, and deletes it. Takes
395 no arguments. Returns undef if array is empty. Returns the
396 element value.
397
398 my $elem = $db->pop();
399
400 * shift()
401 Fetches the first element in the array, deletes it, then shifts
402 all the remaining elements over to take up the space. Returns
403 the element value. This method is not recommended with large
404 arrays -- see "LARGE ARRAYS" below for details.
405
406 my $elem = $db->shift();
407
408 * unshift()
409 Inserts one or more elements onto the beginning of the array,
410 shifting all existing elements over to make room. Accepts
411 scalars, hash refs or array refs. No return value. This
412 method is not recommended with large arrays -- see <LARGE
413 ARRAYS> below for details.
414
415 $db->unshift("foo", "bar", {});
416
417 * splice()
418 Performs exactly like Perl's built-in function of the same
419 name. See "perldoc -f splice" for usage -- it is too compli‐
420 cated to document here. This method is not recommended with
421 large arrays -- see "LARGE ARRAYS" below for details.
422
423 Here are some examples of using arrays:
424
425 my $db = DBM::Deep->new(
426 file => "foo.db",
427 type => DBM::Deep->TYPE_ARRAY
428 );
429
430 $db->push("bar", "baz");
431 $db->unshift("foo");
432 $db->put(3, "buz");
433
434 my $len = $db->length();
435 print "length: $len\n"; # 4
436
437 for (my $k=0; $k<$len; $k++) {
438 print "$k: " . $db->get($k) . "\n";
439 }
440
441 $db->splice(1, 2, "biz", "baf");
442
443 while (my $elem = shift @$db) {
444 print "shifted: $elem\n";
445 }
446
448 Enable automatic file locking by passing a true value to the "locking"
449 parameter when constructing your DBM::Deep object (see SETUP above).
450
451 my $db = DBM::Deep->new(
452 file => "foo.db",
453 locking => 1
454 );
455
456 This causes DBM::Deep to "flock()" the underlying filehandle with
457 exclusive mode for writes, and shared mode for reads. This is required
458 if you have multiple processes accessing the same database file, to
459 avoid file corruption. Please note that "flock()" does NOT work for
460 files over NFS. See "DB OVER NFS" below for more.
461
462 EXPLICIT LOCKING
463
464 You can explicitly lock a database, so it remains locked for multiple
465 transactions. This is done by calling the "lock()" method, and passing
466 an optional lock mode argument (defaults to exclusive mode). This is
467 particularly useful for things like counters, where the current value
468 needs to be fetched, then incremented, then stored again.
469
470 $db->lock();
471 my $counter = $db->get("counter");
472 $counter++;
473 $db->put("counter", $counter);
474 $db->unlock();
475
476 # or...
477
478 $db->lock();
479 $db->{counter}++;
480 $db->unlock();
481
482 You can pass "lock()" an optional argument, which specifies which mode
483 to use (exclusive or shared). Use one of these two constants:
484 "DBM::Deep->LOCK_EX" or "DBM::Deep->LOCK_SH". These are passed
485 directly to "flock()", and are the same as the constants defined in
486 Perl's "Fcntl" module.
487
488 $db->lock( DBM::Deep->LOCK_SH );
489 # something here
490 $db->unlock();
491
493 You can import existing complex structures by calling the "import()"
494 method, and export an entire database into an in-memory structure using
495 the "export()" method. Both are examined here.
496
497 IMPORTING
498
499 Say you have an existing hash with nested hashes/arrays inside it.
500 Instead of walking the structure and adding keys/elements to the data‐
501 base as you go, simply pass a reference to the "import()" method. This
502 recursively adds everything to an existing DBM::Deep object for you.
503 Here is an example:
504
505 my $struct = {
506 key1 => "value1",
507 key2 => "value2",
508 array1 => [ "elem0", "elem1", "elem2" ],
509 hash1 => {
510 subkey1 => "subvalue1",
511 subkey2 => "subvalue2"
512 }
513 };
514
515 my $db = DBM::Deep->new( "foo.db" );
516 $db->import( $struct );
517
518 print $db->{key1} . "\n"; # prints "value1"
519
520 This recursively imports the entire $struct object into $db, including
521 all nested hashes and arrays. If the DBM::Deep object contains exsit‐
522 ing data, keys are merged with the existing ones, replacing if they
523 already exist. The "import()" method can be called on any database
524 level (not just the base level), and works with both hash and array DB
525 types.
526
527 Note: Make sure your existing structure has no circular references in
528 it. These will cause an infinite loop when importing.
529
530 EXPORTING
531
532 Calling the "export()" method on an existing DBM::Deep object will
533 return a reference to a new in-memory copy of the database. The export
534 is done recursively, so all nested hashes/arrays are all exported to
535 standard Perl objects. Here is an example:
536
537 my $db = DBM::Deep->new( "foo.db" );
538
539 $db->{key1} = "value1";
540 $db->{key2} = "value2";
541 $db->{hash1} = {};
542 $db->{hash1}->{subkey1} = "subvalue1";
543 $db->{hash1}->{subkey2} = "subvalue2";
544
545 my $struct = $db->export();
546
547 print $struct->{key1} . "\n"; # prints "value1"
548
549 This makes a complete copy of the database in memory, and returns a
550 reference to it. The "export()" method can be called on any database
551 level (not just the base level), and works with both hash and array DB
552 types. Be careful of large databases -- you can store a lot more data
553 in a DBM::Deep object than an in-memory Perl structure.
554
555 Note: Make sure your database has no circular references in it. These
556 will cause an infinite loop when exporting.
557
559 DBM::Deep has a number of hooks where you can specify your own Perl
560 function to perform filtering on incoming or outgoing data. This is a
561 perfect way to extend the engine, and implement things like real-time
562 compression or encryption. Filtering applies to the base DB level, and
563 all child hashes / arrays. Filter hooks can be specified when your
564 DBM::Deep object is first constructed, or by calling the "set_filter()"
565 method at any time. There are four available filter hooks, described
566 below:
567
568 * filter_store_key
569 This filter is called whenever a hash key is stored. It is passed
570 the incoming key, and expected to return a transformed key.
571
572 * filter_store_value
573 This filter is called whenever a hash key or array element is
574 stored. It is passed the incoming value, and expected to return a
575 transformed value.
576
577 * filter_fetch_key
578 This filter is called whenever a hash key is fetched (i.e. via
579 "first_key()" or "next_key()"). It is passed the transformed key,
580 and expected to return the plain key.
581
582 * filter_fetch_value
583 This filter is called whenever a hash key or array element is
584 fetched. It is passed the transformed value, and expected to
585 return the plain value.
586
587 Here are the two ways to setup a filter hook:
588
589 my $db = DBM::Deep->new(
590 file => "foo.db",
591 filter_store_value => \&my_filter_store,
592 filter_fetch_value => \&my_filter_fetch
593 );
594
595 # or...
596
597 $db->set_filter( "filter_store_value", \&my_filter_store );
598 $db->set_filter( "filter_fetch_value", \&my_filter_fetch );
599
600 Your filter function will be called only when dealing with SCALAR
601 keys or values. When nested hashes and arrays are being
602 stored/fetched, filtering is bypassed. Filters are called as
603 static functions, passed a single SCALAR argument, and expected to
604 return a single SCALAR value. If you want to remove a filter, set
605 the function reference to "undef":
606
607 $db->set_filter( "filter_store_value", undef );
608
609 REAL-TIME ENCRYPTION EXAMPLE
610
611 Here is a working example that uses the Crypt::Blowfish module to
612 do real-time encryption / decryption of keys & values with
613 DBM::Deep Filters. Please visit
614 <http://search.cpan.org/search?module=Crypt::Blowfish> for more on
615 Crypt::Blowfish. You'll also need the Crypt::CBC module.
616
617 use DBM::Deep;
618 use Crypt::Blowfish;
619 use Crypt::CBC;
620
621 my $cipher = Crypt::CBC->new({
622 'key' => 'my secret key',
623 'cipher' => 'Blowfish',
624 'iv' => '$KJh#(}q',
625 'regenerate_key' => 0,
626 'padding' => 'space',
627 'prepend_iv' => 0
628 });
629
630 my $db = DBM::Deep->new(
631 file => "foo-encrypt.db",
632 filter_store_key => \&my_encrypt,
633 filter_store_value => \&my_encrypt,
634 filter_fetch_key => \&my_decrypt,
635 filter_fetch_value => \&my_decrypt,
636 );
637
638 $db->{key1} = "value1";
639 $db->{key2} = "value2";
640 print "key1: " . $db->{key1} . "\n";
641 print "key2: " . $db->{key2} . "\n";
642
643 undef $db;
644 exit;
645
646 sub my_encrypt {
647 return $cipher->encrypt( $_[0] );
648 }
649 sub my_decrypt {
650 return $cipher->decrypt( $_[0] );
651 }
652
653 REAL-TIME COMPRESSION EXAMPLE
654
655 Here is a working example that uses the Compress::Zlib module to do
656 real-time compression / decompression of keys & values with
657 DBM::Deep Filters. Please visit
658 <http://search.cpan.org/search?module=Compress::Zlib> for more on
659 Compress::Zlib.
660
661 use DBM::Deep;
662 use Compress::Zlib;
663
664 my $db = DBM::Deep->new(
665 file => "foo-compress.db",
666 filter_store_key => \&my_compress,
667 filter_store_value => \&my_compress,
668 filter_fetch_key => \&my_decompress,
669 filter_fetch_value => \&my_decompress,
670 );
671
672 $db->{key1} = "value1";
673 $db->{key2} = "value2";
674 print "key1: " . $db->{key1} . "\n";
675 print "key2: " . $db->{key2} . "\n";
676
677 undef $db;
678 exit;
679
680 sub my_compress {
681 return Compress::Zlib::memGzip( $_[0] ) ;
682 }
683 sub my_decompress {
684 return Compress::Zlib::memGunzip( $_[0] ) ;
685 }
686
687 Note: Filtering of keys only applies to hashes. Array "keys" are
688 actually numerical index numbers, and are not filtered.
689
691 Most DBM::Deep methods return a true value for success, and call die()
692 on failure. You can wrap calls in an eval block to catch the die.
693 Also, the actual error message is stored in an internal scalar, which
694 can be fetched by calling the "error()" method.
695
696 my $db = DBM::Deep->new( "foo.db" ); # create hash
697 eval { $db->push("foo"); }; # ILLEGAL -- push is array-only call
698
699 print $@; # prints error message
700 print $db->error(); # prints error message
701
702 You can then call "clear_error()" to clear the current error state.
703
704 $db->clear_error();
705
706 If you set the "debug" option to true when creating your DBM::Deep
707 object, all errors are considered NON-FATAL, and dumped to STDERR.
708 This should only be used for debugging purposes and not production
709 work. DBM::Deep expects errors to be thrown, not propagated back up the
710 stack.
711
712 NOTE: error() and clear_error() are considered deprecated and will be
713 removed in 1.00. Please don't use them. Instead, wrap all your func‐
714 tions with in eval-blocks.
715
717 If you have a 64-bit system, and your Perl is compiled with both LARGE‐
718 FILE and 64-bit support, you may be able to create databases larger
719 than 2 GB. DBM::Deep by default uses 32-bit file offset tags, but
720 these can be changed by calling the static "set_pack()" method before
721 you do anything else.
722
723 DBM::Deep::set_pack(8, 'Q');
724
725 This tells DBM::Deep to pack all file offsets with 8-byte (64-bit) quad
726 words instead of 32-bit longs. After setting these values your DB
727 files have a theoretical maximum size of 16 XB (exabytes).
728
729 Note: Changing these values will NOT work for existing database files.
730 Only change this for new files, and make sure it stays set consistently
731 throughout the file's life. If you do set these values, you can no
732 longer access 32-bit DB files. You can, however, call "set_pack(4,
733 'N')" to change back to 32-bit mode.
734
735 Note: I have not personally tested files > 2 GB -- all my systems have
736 only a 32-bit Perl. However, I have received user reports that this
737 does indeed work!
738
740 If you require low-level access to the underlying filehandle that
741 DBM::Deep uses, you can call the "_fh()" method, which returns the han‐
742 dle:
743
744 my $fh = $db->_fh();
745
746 This method can be called on the root level of the datbase, or any
747 child hashes or arrays. All levels share a root structure, which con‐
748 tains things like the filehandle, a reference counter, and all the
749 options specified when you created the object. You can get access to
750 this root structure by calling the "root()" method.
751
752 my $root = $db->_root();
753
754 This is useful for changing options after the object has already been
755 created, such as enabling/disabling locking, or debug modes. You can
756 also store your own temporary user data in this structure (be wary of
757 name collision), which is then accessible from any child hash or array.
758
760 DBM::Deep by default uses the Message Digest 5 (MD5) algorithm for
761 hashing keys. However you can override this, and use another algorithm
762 (such as SHA-256) or even write your own. But please note that
763 DBM::Deep currently expects zero collisions, so your algorithm has to
764 be perfect, so to speak. Collision detection may be introduced in a
765 later version.
766
767 You can specify a custom digest algorithm by calling the static
768 "set_digest()" function, passing a reference to a subroutine, and the
769 length of the algorithm's hashes (in bytes). This is a global static
770 function, which affects ALL DBM::Deep objects. Here is a working exam‐
771 ple that uses a 256-bit hash from the Digest::SHA256 module. Please
772 see <http://search.cpan.org/search?module=Digest::SHA256> for more.
773
774 use DBM::Deep;
775 use Digest::SHA256;
776
777 my $context = Digest::SHA256::new(256);
778
779 DBM::Deep::set_digest( \&my_digest, 32 );
780
781 my $db = DBM::Deep->new( "foo-sha.db" );
782
783 $db->{key1} = "value1";
784 $db->{key2} = "value2";
785 print "key1: " . $db->{key1} . "\n";
786 print "key2: " . $db->{key2} . "\n";
787
788 undef $db;
789 exit;
790
791 sub my_digest {
792 return substr( $context->hash($_[0]), 0, 32 );
793 }
794
795 Note: Your returned digest strings must be EXACTLY the number of bytes
796 you specify in the "set_digest()" function (in this case 32).
797
799 DBM::Deep has experimental support for circular references. Meaning
800 you can have a nested hash key or array element that points to a parent
801 object. This relationship is stored in the DB file, and is preserved
802 between sessions. Here is an example:
803
804 my $db = DBM::Deep->new( "foo.db" );
805
806 $db->{foo} = "bar";
807 $db->{circle} = $db; # ref to self
808
809 print $db->{foo} . "\n"; # prints "foo"
810 print $db->{circle}->{foo} . "\n"; # prints "foo" again
811
812 One catch is, passing the object to a function that recursively walks
813 the object tree (such as Data::Dumper or even the built-in "optimize()"
814 or "export()" methods) will result in an infinite loop. The other
815 catch is, if you fetch the key of a circular reference (i.e. using the
816 "first_key()" or "next_key()" methods), you will get the target
817 object's key, not the ref's key. This gets even more interesting with
818 the above example, where the circle key points to the base DB object,
819 which technically doesn't have a key. So I made DBM::Deep return
820 "[base]" as the key name in that special case.
821
823 This section describes all the known issues with DBM::Deep. It you
824 have found something that is not listed here, please send e-mail to
825 jhuckaby@cpan.org.
826
827 UNUSED SPACE RECOVERY
828
829 One major caveat with DBM::Deep is that space occupied by existing keys
830 and values is not recovered when they are deleted. Meaning if you keep
831 deleting and adding new keys, your file will continuously grow. I am
832 working on this, but in the meantime you can call the built-in "opti‐
833 mize()" method from time to time (perhaps in a crontab or something) to
834 recover all your unused space.
835
836 $db->optimize(); # returns true on success
837
838 This rebuilds the ENTIRE database into a new file, then moves it on top
839 of the original. The new file will have no unused space, thus it will
840 take up as little disk space as possible. Please note that this opera‐
841 tion can take a long time for large files, and you need enough disk
842 space to temporarily hold 2 copies of your DB file. The temporary file
843 is created in the same directory as the original, named with a ".tmp"
844 extension, and is deleted when the operation completes. Oh, and if
845 locking is enabled, the DB is automatically locked for the entire dura‐
846 tion of the copy.
847
848 WARNING: Only call optimize() on the top-level node of the database,
849 and make sure there are no child references lying around. DBM::Deep
850 keeps a reference counter, and if it is greater than 1, optimize() will
851 abort and return undef.
852
853 FILE CORRUPTION
854
855 The current level of error handling in DBM::Deep is minimal. Files are
856 checked for a 32-bit signature when opened, but other corruption in
857 files can cause segmentation faults. DBM::Deep may try to seek() past
858 the end of a file, or get stuck in an infinite loop depending on the
859 level of corruption. File write operations are not checked for failure
860 (for speed), so if you happen to run out of disk space, DBM::Deep will
861 probably fail in a bad way. These things will be addressed in a later
862 version of DBM::Deep.
863
864 DB OVER NFS
865
866 Beware of using DB files over NFS. DBM::Deep uses flock(), which works
867 well on local filesystems, but will NOT protect you from file corrup‐
868 tion over NFS. I've heard about setting up your NFS server with a
869 locking daemon, then using lockf() to lock your files, but your mileage
870 may vary there as well. From what I understand, there is no real way
871 to do it. However, if you need access to the underlying filehandle in
872 DBM::Deep for using some other kind of locking scheme like lockf(), see
873 the "LOW-LEVEL ACCESS" section above.
874
875 COPYING OBJECTS
876
877 Beware of copying tied objects in Perl. Very strange things can hap‐
878 pen. Instead, use DBM::Deep's "clone()" method which safely copies the
879 object and returns a new, blessed, tied hash or array to the same level
880 in the DB.
881
882 my $copy = $db->clone();
883
884 Note: Since clone() here is cloning the object, not the database loca‐
885 tion, any modifications to either $db or $copy will be visible in both.
886
887 LARGE ARRAYS
888
889 Beware of using "shift()", "unshift()" or "splice()" with large arrays.
890 These functions cause every element in the array to move, which can be
891 murder on DBM::Deep, as every element has to be fetched from disk, then
892 stored again in a different location. This will be addressed in the
893 forthcoming version 1.00.
894
895 WRITEONLY FILES
896
897 If you pass in a filehandle to new(), you may have opened it in either
898 a readonly or writeonly mode. STORE will verify that the filehandle is
899 writable. However, there doesn't seem to be a good way to determine if
900 a filehandle is readable. And, if the filehandle isn't readable, it's
901 not clear what will happen. So, don't do that.
902
904 This section discusses DBM::Deep's speed and memory usage.
905
906 SPEED
907
908 Obviously, DBM::Deep isn't going to be as fast as some C-based DBMs,
909 such as the almighty BerkeleyDB. But it makes up for it in features
910 like true multi-level hash/array support, and cross-platform FTPable
911 files. Even so, DBM::Deep is still pretty fast, and the speed stays
912 fairly consistent, even with huge databases. Here is some test data:
913
914 Adding 1,000,000 keys to new DB file...
915
916 At 100 keys, avg. speed is 2,703 keys/sec
917 At 200 keys, avg. speed is 2,642 keys/sec
918 At 300 keys, avg. speed is 2,598 keys/sec
919 At 400 keys, avg. speed is 2,578 keys/sec
920 At 500 keys, avg. speed is 2,722 keys/sec
921 At 600 keys, avg. speed is 2,628 keys/sec
922 At 700 keys, avg. speed is 2,700 keys/sec
923 At 800 keys, avg. speed is 2,607 keys/sec
924 At 900 keys, avg. speed is 2,190 keys/sec
925 At 1,000 keys, avg. speed is 2,570 keys/sec
926 At 2,000 keys, avg. speed is 2,417 keys/sec
927 At 3,000 keys, avg. speed is 1,982 keys/sec
928 At 4,000 keys, avg. speed is 1,568 keys/sec
929 At 5,000 keys, avg. speed is 1,533 keys/sec
930 At 6,000 keys, avg. speed is 1,787 keys/sec
931 At 7,000 keys, avg. speed is 1,977 keys/sec
932 At 8,000 keys, avg. speed is 2,028 keys/sec
933 At 9,000 keys, avg. speed is 2,077 keys/sec
934 At 10,000 keys, avg. speed is 2,031 keys/sec
935 At 20,000 keys, avg. speed is 1,970 keys/sec
936 At 30,000 keys, avg. speed is 2,050 keys/sec
937 At 40,000 keys, avg. speed is 2,073 keys/sec
938 At 50,000 keys, avg. speed is 1,973 keys/sec
939 At 60,000 keys, avg. speed is 1,914 keys/sec
940 At 70,000 keys, avg. speed is 2,091 keys/sec
941 At 80,000 keys, avg. speed is 2,103 keys/sec
942 At 90,000 keys, avg. speed is 1,886 keys/sec
943 At 100,000 keys, avg. speed is 1,970 keys/sec
944 At 200,000 keys, avg. speed is 2,053 keys/sec
945 At 300,000 keys, avg. speed is 1,697 keys/sec
946 At 400,000 keys, avg. speed is 1,838 keys/sec
947 At 500,000 keys, avg. speed is 1,941 keys/sec
948 At 600,000 keys, avg. speed is 1,930 keys/sec
949 At 700,000 keys, avg. speed is 1,735 keys/sec
950 At 800,000 keys, avg. speed is 1,795 keys/sec
951 At 900,000 keys, avg. speed is 1,221 keys/sec
952 At 1,000,000 keys, avg. speed is 1,077 keys/sec
953
954 This test was performed on a PowerMac G4 1gHz running Mac OS X 10.3.2 &
955 Perl 5.8.1, with an 80GB Ultra ATA/100 HD spinning at 7200RPM. The
956 hash keys and values were between 6 - 12 chars in length. The DB file
957 ended up at 210MB. Run time was 12 min 3 sec.
958
959 MEMORY USAGE
960
961 One of the great things about DBM::Deep is that it uses very little
962 memory. Even with huge databases (1,000,000+ keys) you will not see
963 much increased memory on your process. DBM::Deep relies solely on the
964 filesystem for storing and fetching data. Here is output from
965 /usr/bin/top before even opening a database handle:
966
967 PID USER PRI NI SIZE RSS SHARE STAT %CPU %MEM TIME COMMAND
968 22831 root 11 0 2716 2716 1296 R 0.0 0.2 0:07 perl
969
970 Basically the process is taking 2,716K of memory. And here is the same
971 process after storing and fetching 1,000,000 keys:
972
973 PID USER PRI NI SIZE RSS SHARE STAT %CPU %MEM TIME COMMAND
974 22831 root 14 0 2772 2772 1328 R 0.0 0.2 13:32 perl
975
976 Notice the memory usage increased by only 56K. Test was performed on a
977 700mHz x86 box running Linux RedHat 7.2 & Perl 5.6.1.
978
980 In case you were interested in the underlying DB file format, it is
981 documented here in this section. You don't need to know this to use
982 the module, it's just included for reference.
983
984 SIGNATURE
985
986 DBM::Deep files always start with a 32-bit signature to identify the
987 file type. This is at offset 0. The signature is "DPDB" in network
988 byte order. This is checked for when the file is opened and an error
989 will be thrown if it's not found.
990
991 TAG
992
993 The DBM::Deep file is in a tagged format, meaning each section of the
994 file has a standard header containing the type of data, the length of
995 data, and then the data itself. The type is a single character (1
996 byte), the length is a 32-bit unsigned long in network byte order, and
997 the data is, well, the data. Here is how it unfolds:
998
999 MASTER INDEX
1000
1001 Immediately after the 32-bit file signature is the Master Index record.
1002 This is a standard tag header followed by 1024 bytes (in 32-bit mode)
1003 or 2048 bytes (in 64-bit mode) of data. The type is H for hash or A
1004 for array, depending on how the DBM::Deep object was constructed.
1005
1006 The index works by looking at a MD5 Hash of the hash key (or array
1007 index number). The first 8-bit char of the MD5 signature is the offset
1008 into the index, multipled by 4 in 32-bit mode, or 8 in 64-bit mode.
1009 The value of the index element is a file offset of the next tag for the
1010 key/element in question, which is usually a Bucket List tag (see
1011 below).
1012
1013 The next tag could be another index, depending on how many keys/ele‐
1014 ments exist. See RE-INDEXING below for details.
1015
1016 BUCKET LIST
1017
1018 A Bucket List is a collection of 16 MD5 hashes for keys/elements, plus
1019 file offsets to where the actual data is stored. It starts with a
1020 standard tag header, with type B, and a data size of 320 bytes in
1021 32-bit mode, or 384 bytes in 64-bit mode. Each MD5 hash is stored in
1022 full (16 bytes), plus the 32-bit or 64-bit file offset for the Bucket
1023 containing the actual data. When the list fills up, a Re-Index opera‐
1024 tion is performed (See RE-INDEXING below).
1025
1026 BUCKET
1027
1028 A Bucket is a tag containing a key/value pair (in hash mode), or a
1029 index/value pair (in array mode). It starts with a standard tag header
1030 with type D for scalar data (string, binary, etc.), or it could be a
1031 nested hash (type H) or array (type A). The value comes just after the
1032 tag header. The size reported in the tag header is only for the value,
1033 but then, just after the value is another size (32-bit unsigned long)
1034 and then the plain key itself. Since the value is likely to be fetched
1035 more often than the plain key, I figured it would be slightly faster to
1036 store the value first.
1037
1038 If the type is H (hash) or A (array), the value is another Master Index
1039 record for the nested structure, where the process begins all over
1040 again.
1041
1042 RE-INDEXING
1043
1044 After a Bucket List grows to 16 records, its allocated space in the
1045 file is exhausted. Then, when another key/element comes in, the list
1046 is converted to a new index record. However, this index will look at
1047 the next char in the MD5 hash, and arrange new Bucket List pointers
1048 accordingly. This process is called Re-Indexing. Basically, a new
1049 index tag is created at the file EOF, and all 17 (16 + new one)
1050 keys/elements are removed from the old Bucket List and inserted into
1051 the new index. Several new Bucket Lists are created in the process, as
1052 a new MD5 char from the key is being examined (it is unlikely that the
1053 keys will all share the same next char of their MD5s).
1054
1055 Because of the way the MD5 algorithm works, it is impossible to tell
1056 exactly when the Bucket Lists will turn into indexes, but the first
1057 round tends to happen right around 4,000 keys. You will see a slight
1058 decrease in performance here, but it picks back up pretty quick (see
1059 SPEED above). Then it takes a lot more keys to exhaust the next level
1060 of Bucket Lists. It's right around 900,000 keys. This process can
1061 continue nearly indefinitely -- right up until the point the MD5 signa‐
1062 tures start colliding with each other, and this is EXTREMELY rare --
1063 like winning the lottery 5 times in a row AND getting struck by light‐
1064 ning while you are walking to cash in your tickets. Theoretically,
1065 since MD5 hashes are 128-bit values, you could have up to
1066 340,282,366,921,000,000,000,000,000,000,000,000,000 keys/elements (I
1067 believe this is 340 unodecillion, but don't quote me).
1068
1069 STORING
1070
1071 When a new key/element is stored, the key (or index number) is first
1072 run through Digest::MD5 to get a 128-bit signature (example, in hex:
1073 b05783b0773d894396d475ced9d2f4f6). Then, the Master Index record is
1074 checked for the first char of the signature (in this case b0). If it
1075 does not exist, a new Bucket List is created for our key (and the next
1076 15 future keys that happen to also have b as their first MD5 char).
1077 The entire MD5 is written to the Bucket List along with the offset of
1078 the new Bucket record (EOF at this point, unless we are replacing an
1079 existing Bucket), where the actual data will be stored.
1080
1081 FETCHING
1082
1083 Fetching an existing key/element involves getting a Digest::MD5 of the
1084 key (or index number), then walking along the indexes. If there are
1085 enough keys/elements in this DB level, there might be nested indexes,
1086 each linked to a particular char of the MD5. Finally, a Bucket List is
1087 pointed to, which contains up to 16 full MD5 hashes. Each is checked
1088 for equality to the key in question. If we found a match, the Bucket
1089 tag is loaded, where the value and plain key are stored.
1090
1091 Fetching the plain key occurs when calling the first_key() and
1092 next_key() methods. In this process the indexes are walked systemati‐
1093 cally, and each key fetched in increasing MD5 order (which is why it
1094 appears random). Once the Bucket is found, the value is skipped and
1095 the plain key returned instead. Note: Do not count on keys being
1096 fetched as if the MD5 hashes were alphabetically sorted. This only
1097 happens on an index-level -- as soon as the Bucket Lists are hit, the
1098 keys will come out in the order they went in -- so it's pretty much
1099 undefined how the keys will come out -- just like Perl's built-in
1100 hashes.
1101
1103 We use Devel::Cover to test the code coverage of our tests, below is
1104 the Devel::Cover report on this module's test suite.
1105
1106 ---------------------------- ------ ------ ------ ------ ------ ------ ------
1107 File stmt bran cond sub pod time total
1108 ---------------------------- ------ ------ ------ ------ ------ ------ ------
1109 blib/lib/DBM/Deep.pm 95.4 84.6 69.1 98.2 100.0 60.3 91.0
1110 blib/lib/DBM/Deep/Array.pm 100.0 91.1 100.0 100.0 n/a 26.4 98.0
1111 blib/lib/DBM/Deep/Hash.pm 95.3 80.0 100.0 100.0 n/a 13.3 92.4
1112 Total 96.4 85.4 73.1 98.8 100.0 100.0 92.4
1113 ---------------------------- ------ ------ ------ ------ ------ ------ ------
1114
1116 Check out the DBM::Deep Google Group at
1117 <http://groups.google.com/group/DBM-Deep> or send email to
1118 DBM-Deep@googlegroups.com.
1119
1121 Joseph Huckaby, jhuckaby@cpan.org
1122
1123 Rob Kinyon, rkinyon@cpan.org
1124
1125 Special thanks to Adam Sah and Rich Gaushell! You know why :-)
1126
1128 perltie(1), Tie::Hash(3), Digest::MD5(3), Fcntl(3), flock(2), lockf(3),
1129 nfs(5), Digest::SHA256(3), Crypt::Blowfish(3), Compress::Zlib(3)
1130
1132 Copyright (c) 2002-2006 Joseph Huckaby. All Rights Reserved. This is
1133 free software, you may use it and distribute it under the same terms as
1134 Perl itself.
1135
1136
1137
1138perl v5.8.8 2006-09-08 DBM::Deep(3)