r14213@rob-kinyons-computer (orig r8080): rkinyon | 2006-11-17 20:47:50 -0500
[dbsrgits/DBM-Deep.git] / lib / DBM / Deep.pod
CommitLineData
2120a181 1=head1 NAME
2
3DBM::Deep - A pure perl multi-level hash/array DBM that supports transactions
4
5=head1 SYNOPSIS
6
7 use DBM::Deep;
8 my $db = DBM::Deep->new( "foo.db" );
9
10 $db->{key} = 'value';
11 print $db->{key};
12
13 $db->put('key' => 'value');
14 print $db->get('key');
15
16 # true multi-level support
17 $db->{my_complex} = [
18 'hello', { perl => 'rules' },
19 42, 99,
20 ];
21
22 $db->begin_work;
23
24 # Do stuff here
25
26 $db->rollback;
27 $db->commit;
28
29 tie my %db, 'DBM::Deep', 'foo.db';
30 $db{key} = 'value';
31 print $db{key};
32
33 tied(%db)->put('key' => 'value');
34 print tied(%db)->get('key');
35
36=head1 DESCRIPTION
37
38A unique flat-file database module, written in pure perl. True multi-level
39hash/array support (unlike MLDBM, which is faked), hybrid OO / tie()
40interface, cross-platform FTPable files, ACID transactions, and is quite fast.
41Can handle millions of keys and unlimited levels without significant
42slow-down. Written from the ground-up in pure perl -- this is NOT a wrapper
43around a C-based DBM. Out-of-the-box compatibility with Unix, Mac OS X and
44Windows.
45
46=head1 VERSION DIFFERENCES
47
48B<NOTE>: 0.99_03 has significant file format differences from prior versions.
49THere will be a backwards-compatibility layer in 1.00, but that is slated for
50a later 0.99_x release. This version is B<NOT> backwards compatible with any
51other release of DBM::Deep.
52
53B<NOTE>: 0.99_01 and above have significant file format differences from 0.983 and
54before. There will be a backwards-compatibility layer in 1.00, but that is
55slated for a later 0.99_x release. This version is B<NOT> backwards compatible
56with 0.983 and before.
57
58=head1 SETUP
59
60Construction can be done OO-style (which is the recommended way), or using
61Perl's tie() function. Both are examined here.
62
63=head2 OO Construction
64
65The recommended way to construct a DBM::Deep object is to use the new()
66method, which gets you a blessed I<and> tied hash (or array) reference.
67
68 my $db = DBM::Deep->new( "foo.db" );
69
70This opens a new database handle, mapped to the file "foo.db". If this
71file does not exist, it will automatically be created. DB files are
72opened in "r+" (read/write) mode, and the type of object returned is a
73hash, unless otherwise specified (see L<OPTIONS> below).
74
75You can pass a number of options to the constructor to specify things like
76locking, autoflush, etc. This is done by passing an inline hash (or hashref):
77
78 my $db = DBM::Deep->new(
79 file => "foo.db",
80 locking => 1,
81 autoflush => 1
82 );
83
84Notice that the filename is now specified I<inside> the hash with
85the "file" parameter, as opposed to being the sole argument to the
86constructor. This is required if any options are specified.
87See L<OPTIONS> below for the complete list.
88
89You can also start with an array instead of a hash. For this, you must
90specify the C<type> parameter:
91
92 my $db = DBM::Deep->new(
93 file => "foo.db",
94 type => DBM::Deep->TYPE_ARRAY
95 );
96
97B<Note:> Specifing the C<type> parameter only takes effect when beginning
98a new DB file. If you create a DBM::Deep object with an existing file, the
99C<type> will be loaded from the file header, and an error will be thrown if
100the wrong type is passed in.
101
102=head2 Tie Construction
103
104Alternately, you can create a DBM::Deep handle by using Perl's built-in
105tie() function. The object returned from tie() can be used to call methods,
106such as lock() and unlock(). (That object can be retrieved from the tied
107variable at any time using tied() - please see L<perltie/> for more info.
108
109 my %hash;
110 my $db = tie %hash, "DBM::Deep", "foo.db";
111
112 my @array;
113 my $db = tie @array, "DBM::Deep", "bar.db";
114
115As with the OO constructor, you can replace the DB filename parameter with
116a hash containing one or more options (see L<OPTIONS> just below for the
117complete list).
118
119 tie %hash, "DBM::Deep", {
120 file => "foo.db",
121 locking => 1,
122 autoflush => 1
123 };
124
125=head2 Options
126
127There are a number of options that can be passed in when constructing your
128DBM::Deep objects. These apply to both the OO- and tie- based approaches.
129
130=over
131
132=item * file
133
134Filename of the DB file to link the handle to. You can pass a full absolute
135filesystem path, partial path, or a plain filename if the file is in the
136current working directory. This is a required parameter (though q.v. fh).
137
138=item * fh
139
140If you want, you can pass in the fh instead of the file. This is most useful for doing
141something like:
142
143 my $db = DBM::Deep->new( { fh => \*DATA } );
144
145You are responsible for making sure that the fh has been opened appropriately for your
146needs. If you open it read-only and attempt to write, an exception will be thrown. If you
147open it write-only or append-only, an exception will be thrown immediately as DBM::Deep
148needs to read from the fh.
149
150=item * file_offset
151
152This is the offset within the file that the DBM::Deep db starts. Most of the time, you will
153not need to set this. However, it's there if you want it.
154
155If you pass in fh and do not set this, it will be set appropriately.
156
157=item * type
158
159This parameter specifies what type of object to create, a hash or array. Use
160one of these two constants:
161
162=over 4
163
164=item * C<DBM::Deep-E<gt>TYPE_HASH>
165
166=item * C<DBM::Deep-E<gt>TYPE_ARRAY>.
167
168=back
169
170This only takes effect when beginning a new file. This is an optional
171parameter, and defaults to C<DBM::Deep-E<gt>TYPE_HASH>.
172
173=item * locking
174
175Specifies whether locking is to be enabled. DBM::Deep uses Perl's flock()
176function to lock the database in exclusive mode for writes, and shared mode
177for reads. Pass any true value to enable. This affects the base DB handle
178I<and any child hashes or arrays> that use the same DB file. This is an
179optional parameter, and defaults to 1 (enabled). See L<LOCKING> below for
180more.
181
182=item * autoflush
183
184Specifies whether autoflush is to be enabled on the underlying filehandle.
185This obviously slows down write operations, but is required if you may have
186multiple processes accessing the same DB file (also consider enable I<locking>).
187Pass any true value to enable. This is an optional parameter, and defaults to 1
188(enabled).
189
190=item * filter_*
191
192See L</FILTERS> below.
193
194=back
195
196The following parameters may be specified in the constructor the first time the
197datafile is created. However, they will be stored in the header of the file and
198cannot be overridden by subsequent openings of the file - the values will be set
199from the values stored in the datafile's header.
200
201=over 4
202
203=item * num_txns
204
205This is the maximum number of transactions that can be running at one time. The
206default is two - the HEAD and one for imports. The minimum is two and the
207maximum is 255. The more transactions, the larger and quicker the datafile grows.
208
209See L</TRANSACTIONS> below.
210
211=item * max_buckets
212
213This is the number of entries that can be added before a reindexing. The larger
214this number is made, the larger a file gets, but the better performance you will
215have. The default and minimum number this can be is 16. There is no maximum, but
216more than 32 isn't recommended.
217
218=item * pack_size
219
220This is the size of the file pointer used throughout the file. The valid values
221are:
222
223=over 4
224
225=item * small
226
227This uses 2-byte offsets, allowing for a maximum file size of 65K
228
229=item * medium (default)
230
231This uses 4-byte offsets, allowing for a maximum file size of 2G.
232
233=item * large
234
235This uses 8-byte offsets, allowing for a maximum file size of 16XB (exabytes).
236
237=back
238
239See L</LARGEFILE SUPPORT> for more information.
240
241=back
242
243=head1 TIE INTERFACE
244
245With DBM::Deep you can access your databases using Perl's standard hash/array
246syntax. Because all DBM::Deep objects are I<tied> to hashes or arrays, you can
247treat them as such. DBM::Deep will intercept all reads/writes and direct them
248to the right place -- the DB file. This has nothing to do with the
249L<TIE CONSTRUCTION> section above. This simply tells you how to use DBM::Deep
250using regular hashes and arrays, rather than calling functions like C<get()>
251and C<put()> (although those work too). It is entirely up to you how to want
252to access your databases.
253
254=head2 Hashes
255
256You can treat any DBM::Deep object like a normal Perl hash reference. Add keys,
257or even nested hashes (or arrays) using standard Perl syntax:
258
259 my $db = DBM::Deep->new( "foo.db" );
260
261 $db->{mykey} = "myvalue";
262 $db->{myhash} = {};
263 $db->{myhash}->{subkey} = "subvalue";
264
265 print $db->{myhash}->{subkey} . "\n";
266
267You can even step through hash keys using the normal Perl C<keys()> function:
268
269 foreach my $key (keys %$db) {
270 print "$key: " . $db->{$key} . "\n";
271 }
272
273Remember that Perl's C<keys()> function extracts I<every> key from the hash and
274pushes them onto an array, all before the loop even begins. If you have an
275extremely large hash, this may exhaust Perl's memory. Instead, consider using
276Perl's C<each()> function, which pulls keys/values one at a time, using very
277little memory:
278
279 while (my ($key, $value) = each %$db) {
280 print "$key: $value\n";
281 }
282
283Please note that when using C<each()>, you should always pass a direct
284hash reference, not a lookup. Meaning, you should B<never> do this:
285
286 # NEVER DO THIS
287 while (my ($key, $value) = each %{$db->{foo}}) { # BAD
288
289This causes an infinite loop, because for each iteration, Perl is calling
290FETCH() on the $db handle, resulting in a "new" hash for foo every time, so
291it effectively keeps returning the first key over and over again. Instead,
292assign a temporary variable to C<$db->{foo}>, then pass that to each().
293
294=head2 Arrays
295
296As with hashes, you can treat any DBM::Deep object like a normal Perl array
297reference. This includes inserting, removing and manipulating elements,
298and the C<push()>, C<pop()>, C<shift()>, C<unshift()> and C<splice()> functions.
299The object must have first been created using type C<DBM::Deep-E<gt>TYPE_ARRAY>,
300or simply be a nested array reference inside a hash. Example:
301
302 my $db = DBM::Deep->new(
303 file => "foo-array.db",
304 type => DBM::Deep->TYPE_ARRAY
305 );
306
307 $db->[0] = "foo";
308 push @$db, "bar", "baz";
309 unshift @$db, "bah";
310
311 my $last_elem = pop @$db; # baz
312 my $first_elem = shift @$db; # bah
313 my $second_elem = $db->[1]; # bar
314
315 my $num_elements = scalar @$db;
316
317=head1 OO INTERFACE
318
319In addition to the I<tie()> interface, you can also use a standard OO interface
320to manipulate all aspects of DBM::Deep databases. Each type of object (hash or
321array) has its own methods, but both types share the following common methods:
322C<put()>, C<get()>, C<exists()>, C<delete()> and C<clear()>. C<fetch()> and
323C<store(> are aliases to C<put()> and C<get()>, respectively.
324
325=over
326
327=item * new() / clone()
328
329These are the constructor and copy-functions.
330
331=item * put() / store()
332
333Stores a new hash key/value pair, or sets an array element value. Takes two
334arguments, the hash key or array index, and the new value. The value can be
335a scalar, hash ref or array ref. Returns true on success, false on failure.
336
337 $db->put("foo", "bar"); # for hashes
338 $db->put(1, "bar"); # for arrays
339
340=item * get() / fetch()
341
342Fetches the value of a hash key or array element. Takes one argument: the hash
343key or array index. Returns a scalar, hash ref or array ref, depending on the
344data type stored.
345
346 my $value = $db->get("foo"); # for hashes
347 my $value = $db->get(1); # for arrays
348
349=item * exists()
350
351Checks if a hash key or array index exists. Takes one argument: the hash key
352or array index. Returns true if it exists, false if not.
353
354 if ($db->exists("foo")) { print "yay!\n"; } # for hashes
355 if ($db->exists(1)) { print "yay!\n"; } # for arrays
356
357=item * delete()
358
359Deletes one hash key/value pair or array element. Takes one argument: the hash
360key or array index. Returns true on success, false if not found. For arrays,
361the remaining elements located after the deleted element are NOT moved over.
362The deleted element is essentially just undefined, which is exactly how Perl's
363internal arrays work.
364
365 $db->delete("foo"); # for hashes
366 $db->delete(1); # for arrays
367
368=item * clear()
369
370Deletes B<all> hash keys or array elements. Takes no arguments. No return
371value.
372
373 $db->clear(); # hashes or arrays
374
375=item * lock() / unlock()
376
377q.v. Locking.
378
379=item * optimize()
380
381Recover lost disk space. This is important to do, especially if you use
382transactions.
383
384=item * import() / export()
385
386Data going in and out.
387
388=item * begin_work() / commit() / rollback()
389
390These are the transactional functions. L</TRANSACTIONS> for more information.
391
392=back
393
394=head2 Hashes
395
396For hashes, DBM::Deep supports all the common methods described above, and the
397following additional methods: C<first_key()> and C<next_key()>.
398
399=over
400
401=item * first_key()
402
403Returns the "first" key in the hash. As with built-in Perl hashes, keys are
404fetched in an undefined order (which appears random). Takes no arguments,
405returns the key as a scalar value.
406
407 my $key = $db->first_key();
408
409=item * next_key()
410
411Returns the "next" key in the hash, given the previous one as the sole argument.
412Returns undef if there are no more keys to be fetched.
413
414 $key = $db->next_key($key);
415
416=back
417
418Here are some examples of using hashes:
419
420 my $db = DBM::Deep->new( "foo.db" );
421
422 $db->put("foo", "bar");
423 print "foo: " . $db->get("foo") . "\n";
424
425 $db->put("baz", {}); # new child hash ref
426 $db->get("baz")->put("buz", "biz");
427 print "buz: " . $db->get("baz")->get("buz") . "\n";
428
429 my $key = $db->first_key();
430 while ($key) {
431 print "$key: " . $db->get($key) . "\n";
432 $key = $db->next_key($key);
433 }
434
435 if ($db->exists("foo")) { $db->delete("foo"); }
436
437=head2 Arrays
438
439For arrays, DBM::Deep supports all the common methods described above, and the
440following additional methods: C<length()>, C<push()>, C<pop()>, C<shift()>,
441C<unshift()> and C<splice()>.
442
443=over
444
445=item * length()
446
447Returns the number of elements in the array. Takes no arguments.
448
449 my $len = $db->length();
450
451=item * push()
452
453Adds one or more elements onto the end of the array. Accepts scalars, hash
454refs or array refs. No return value.
455
456 $db->push("foo", "bar", {});
457
458=item * pop()
459
460Fetches the last element in the array, and deletes it. Takes no arguments.
461Returns undef if array is empty. Returns the element value.
462
463 my $elem = $db->pop();
464
465=item * shift()
466
467Fetches the first element in the array, deletes it, then shifts all the
468remaining elements over to take up the space. Returns the element value. This
469method is not recommended with large arrays -- see L<LARGE ARRAYS> below for
470details.
471
472 my $elem = $db->shift();
473
474=item * unshift()
475
476Inserts one or more elements onto the beginning of the array, shifting all
477existing elements over to make room. Accepts scalars, hash refs or array refs.
478No return value. This method is not recommended with large arrays -- see
479<LARGE ARRAYS> below for details.
480
481 $db->unshift("foo", "bar", {});
482
483=item * splice()
484
485Performs exactly like Perl's built-in function of the same name. See L<perldoc
486-f splice> for usage -- it is too complicated to document here. This method is
487not recommended with large arrays -- see L<LARGE ARRAYS> below for details.
488
489=back
490
491Here are some examples of using arrays:
492
493 my $db = DBM::Deep->new(
494 file => "foo.db",
495 type => DBM::Deep->TYPE_ARRAY
496 );
497
498 $db->push("bar", "baz");
499 $db->unshift("foo");
500 $db->put(3, "buz");
501
502 my $len = $db->length();
503 print "length: $len\n"; # 4
504
505 for (my $k=0; $k<$len; $k++) {
506 print "$k: " . $db->get($k) . "\n";
507 }
508
509 $db->splice(1, 2, "biz", "baf");
510
511 while (my $elem = shift @$db) {
512 print "shifted: $elem\n";
513 }
514
515=head1 LOCKING
516
517Enable or disable automatic file locking by passing a boolean value to the
518C<locking> parameter when constructing your DBM::Deep object (see L<SETUP>
519 above).
520
521 my $db = DBM::Deep->new(
522 file => "foo.db",
523 locking => 1
524 );
525
526This causes DBM::Deep to C<flock()> the underlying filehandle with exclusive
527mode for writes, and shared mode for reads. This is required if you have
528multiple processes accessing the same database file, to avoid file corruption.
529Please note that C<flock()> does NOT work for files over NFS. See L<DB OVER
530NFS> below for more.
531
532=head2 Explicit Locking
533
534You can explicitly lock a database, so it remains locked for multiple
535actions. This is done by calling the C<lock()> method, and passing an
536optional lock mode argument (defaults to exclusive mode). This is particularly
537useful for things like counters, where the current value needs to be fetched,
538then incremented, then stored again.
539
540 $db->lock();
541 my $counter = $db->get("counter");
542 $counter++;
543 $db->put("counter", $counter);
544 $db->unlock();
545
546 # or...
547
548 $db->lock();
549 $db->{counter}++;
550 $db->unlock();
551
552You can pass C<lock()> an optional argument, which specifies which mode to use
553(exclusive or shared). Use one of these two constants:
554C<DBM::Deep-E<gt>LOCK_EX> or C<DBM::Deep-E<gt>LOCK_SH>. These are passed
555directly to C<flock()>, and are the same as the constants defined in Perl's
556L<Fcntl/> module.
557
558 $db->lock( $db->LOCK_SH );
559 # something here
560 $db->unlock();
561
562=head1 IMPORTING/EXPORTING
563
564You can import existing complex structures by calling the C<import()> method,
565and export an entire database into an in-memory structure using the C<export()>
566method. Both are examined here.
567
568=head2 Importing
569
570Say you have an existing hash with nested hashes/arrays inside it. Instead of
571walking the structure and adding keys/elements to the database as you go,
572simply pass a reference to the C<import()> method. This recursively adds
573everything to an existing DBM::Deep object for you. Here is an example:
574
575 my $struct = {
576 key1 => "value1",
577 key2 => "value2",
578 array1 => [ "elem0", "elem1", "elem2" ],
579 hash1 => {
580 subkey1 => "subvalue1",
581 subkey2 => "subvalue2"
582 }
583 };
584
585 my $db = DBM::Deep->new( "foo.db" );
586 $db->import( $struct );
587
588 print $db->{key1} . "\n"; # prints "value1"
589
590This recursively imports the entire C<$struct> object into C<$db>, including
591all nested hashes and arrays. If the DBM::Deep object contains exsiting data,
592keys are merged with the existing ones, replacing if they already exist.
593The C<import()> method can be called on any database level (not just the base
594level), and works with both hash and array DB types.
595
596B<Note:> Make sure your existing structure has no circular references in it.
597These will cause an infinite loop when importing. There are plans to fix this
598in a later release.
599
600B<Note:> With the addition of transactions, importing is performed within a
601transaction, then immediately committed upon success (and rolled back upon
602failre). As a result, you cannot call C<import()> from within a transaction.
603This restriction will be lifted when subtransactions are added in a future
604release.
605
606=head2 Exporting
607
608Calling the C<export()> method on an existing DBM::Deep object will return
609a reference to a new in-memory copy of the database. The export is done
610recursively, so all nested hashes/arrays are all exported to standard Perl
611objects. Here is an example:
612
613 my $db = DBM::Deep->new( "foo.db" );
614
615 $db->{key1} = "value1";
616 $db->{key2} = "value2";
617 $db->{hash1} = {};
618 $db->{hash1}->{subkey1} = "subvalue1";
619 $db->{hash1}->{subkey2} = "subvalue2";
620
621 my $struct = $db->export();
622
623 print $struct->{key1} . "\n"; # prints "value1"
624
625This makes a complete copy of the database in memory, and returns a reference
626to it. The C<export()> method can be called on any database level (not just
627the base level), and works with both hash and array DB types. Be careful of
628large databases -- you can store a lot more data in a DBM::Deep object than an
629in-memory Perl structure.
630
631B<Note:> Make sure your database has no circular references in it.
632These will cause an infinite loop when exporting. There are plans to fix this
633in a later release.
634
635=head1 FILTERS
636
637DBM::Deep has a number of hooks where you can specify your own Perl function
638to perform filtering on incoming or outgoing data. This is a perfect
639way to extend the engine, and implement things like real-time compression or
640encryption. Filtering applies to the base DB level, and all child hashes /
641arrays. Filter hooks can be specified when your DBM::Deep object is first
642constructed, or by calling the C<set_filter()> method at any time. There are
643four available filter hooks, described below:
644
645=over
646
647=item * filter_store_key
648
649This filter is called whenever a hash key is stored. It
650is passed the incoming key, and expected to return a transformed key.
651
652=item * filter_store_value
653
654This filter is called whenever a hash key or array element is stored. It
655is passed the incoming value, and expected to return a transformed value.
656
657=item * filter_fetch_key
658
659This filter is called whenever a hash key is fetched (i.e. via
660C<first_key()> or C<next_key()>). It is passed the transformed key,
661and expected to return the plain key.
662
663=item * filter_fetch_value
664
665This filter is called whenever a hash key or array element is fetched.
666It is passed the transformed value, and expected to return the plain value.
667
668=back
669
670Here are the two ways to setup a filter hook:
671
672 my $db = DBM::Deep->new(
673 file => "foo.db",
674 filter_store_value => \&my_filter_store,
675 filter_fetch_value => \&my_filter_fetch
676 );
677
678 # or...
679
680 $db->set_filter( "filter_store_value", \&my_filter_store );
681 $db->set_filter( "filter_fetch_value", \&my_filter_fetch );
682
683Your filter function will be called only when dealing with SCALAR keys or
684values. When nested hashes and arrays are being stored/fetched, filtering
685is bypassed. Filters are called as static functions, passed a single SCALAR
686argument, and expected to return a single SCALAR value. If you want to
687remove a filter, set the function reference to C<undef>:
688
689 $db->set_filter( "filter_store_value", undef );
690
691=head2 Real-time Encryption Example
692
693Here is a working example that uses the I<Crypt::Blowfish> module to
694do real-time encryption / decryption of keys & values with DBM::Deep Filters.
695Please visit L<http://search.cpan.org/search?module=Crypt::Blowfish> for more
696on I<Crypt::Blowfish>. You'll also need the I<Crypt::CBC> module.
697
698 use DBM::Deep;
699 use Crypt::Blowfish;
700 use Crypt::CBC;
701
702 my $cipher = Crypt::CBC->new({
703 'key' => 'my secret key',
704 'cipher' => 'Blowfish',
705 'iv' => '$KJh#(}q',
706 'regenerate_key' => 0,
707 'padding' => 'space',
708 'prepend_iv' => 0
709 });
710
711 my $db = DBM::Deep->new(
712 file => "foo-encrypt.db",
713 filter_store_key => \&my_encrypt,
714 filter_store_value => \&my_encrypt,
715 filter_fetch_key => \&my_decrypt,
716 filter_fetch_value => \&my_decrypt,
717 );
718
719 $db->{key1} = "value1";
720 $db->{key2} = "value2";
721 print "key1: " . $db->{key1} . "\n";
722 print "key2: " . $db->{key2} . "\n";
723
724 undef $db;
725 exit;
726
727 sub my_encrypt {
728 return $cipher->encrypt( $_[0] );
729 }
730 sub my_decrypt {
731 return $cipher->decrypt( $_[0] );
732 }
733
734=head2 Real-time Compression Example
735
736Here is a working example that uses the I<Compress::Zlib> module to do real-time
737compression / decompression of keys & values with DBM::Deep Filters.
738Please visit L<http://search.cpan.org/search?module=Compress::Zlib> for
739more on I<Compress::Zlib>.
740
741 use DBM::Deep;
742 use Compress::Zlib;
743
744 my $db = DBM::Deep->new(
745 file => "foo-compress.db",
746 filter_store_key => \&my_compress,
747 filter_store_value => \&my_compress,
748 filter_fetch_key => \&my_decompress,
749 filter_fetch_value => \&my_decompress,
750 );
751
752 $db->{key1} = "value1";
753 $db->{key2} = "value2";
754 print "key1: " . $db->{key1} . "\n";
755 print "key2: " . $db->{key2} . "\n";
756
757 undef $db;
758 exit;
759
760 sub my_compress {
761 return Compress::Zlib::memGzip( $_[0] ) ;
762 }
763 sub my_decompress {
764 return Compress::Zlib::memGunzip( $_[0] ) ;
765 }
766
767B<Note:> Filtering of keys only applies to hashes. Array "keys" are
768actually numerical index numbers, and are not filtered.
769
770=head1 ERROR HANDLING
771
772Most DBM::Deep methods return a true value for success, and call die() on
773failure. You can wrap calls in an eval block to catch the die.
774
775 my $db = DBM::Deep->new( "foo.db" ); # create hash
776 eval { $db->push("foo"); }; # ILLEGAL -- push is array-only call
777
778 print $@; # prints error message
779
780=head1 LARGEFILE SUPPORT
781
782If you have a 64-bit system, and your Perl is compiled with both LARGEFILE
783and 64-bit support, you I<may> be able to create databases larger than 2 GB.
784DBM::Deep by default uses 32-bit file offset tags, but these can be changed
785by specifying the 'pack_size' parameter when constructing the file.
786
787 DBM::Deep->new(
788 filename => $filename,
789 pack_size => 'large',
790 );
791
792This tells DBM::Deep to pack all file offsets with 8-byte (64-bit) quad words
793instead of 32-bit longs. After setting these values your DB files have a
794theoretical maximum size of 16 XB (exabytes).
795
796You can also use C<pack_size =E<gt> 'small'> in order to use 16-bit file
797offsets.
798
799B<Note:> Changing these values will B<NOT> work for existing database files.
800Only change this for new files. Once the value has been set, it is stored in
801the file's header and cannot be changed for the life of the file. These
802parameters are per-file, meaning you can access 32-bit and 64-bit files, as
803you choose.
804
805B<Note:> We have not personally tested files larger than 2 GB -- all my
806systems have only a 32-bit Perl. However, I have received user reports that
807this does indeed work!
808
809=head1 LOW-LEVEL ACCESS
810
811If you require low-level access to the underlying filehandle that DBM::Deep uses,
812you can call the C<_fh()> method, which returns the handle:
813
814 my $fh = $db->_fh();
815
816This method can be called on the root level of the datbase, or any child
817hashes or arrays. All levels share a I<root> structure, which contains things
818like the filehandle, a reference counter, and all the options specified
819when you created the object. You can get access to this file object by
820calling the C<_storage()> method.
821
822 my $file_obj = $db->_storage();
823
824This is useful for changing options after the object has already been created,
825such as enabling/disabling locking. You can also store your own temporary user
826data in this structure (be wary of name collision), which is then accessible from
827any child hash or array.
828
829=head1 CUSTOM DIGEST ALGORITHM
830
831DBM::Deep by default uses the I<Message Digest 5> (MD5) algorithm for hashing
832keys. However you can override this, and use another algorithm (such as SHA-256)
833or even write your own. But please note that DBM::Deep currently expects zero
834collisions, so your algorithm has to be I<perfect>, so to speak. Collision
835detection may be introduced in a later version.
836
837You can specify a custom digest algorithm by passing it into the parameter
838list for new(), passing a reference to a subroutine as the 'digest' parameter,
839and the length of the algorithm's hashes (in bytes) as the 'hash_size'
840parameter. Here is a working example that uses a 256-bit hash from the
841I<Digest::SHA256> module. Please see
842L<http://search.cpan.org/search?module=Digest::SHA256> for more information.
843
844 use DBM::Deep;
845 use Digest::SHA256;
846
847 my $context = Digest::SHA256::new(256);
848
849 my $db = DBM::Deep->new(
850 filename => "foo-sha.db",
851 digest => \&my_digest,
852 hash_size => 32,
853 );
854
855 $db->{key1} = "value1";
856 $db->{key2} = "value2";
857 print "key1: " . $db->{key1} . "\n";
858 print "key2: " . $db->{key2} . "\n";
859
860 undef $db;
861 exit;
862
863 sub my_digest {
864 return substr( $context->hash($_[0]), 0, 32 );
865 }
866
867B<Note:> Your returned digest strings must be B<EXACTLY> the number
868of bytes you specify in the hash_size parameter (in this case 32).
869
870B<Note:> If you do choose to use a custom digest algorithm, you must set it
871every time you access this file. Otherwise, the default (MD5) will be used.
872
873=head1 CIRCULAR REFERENCES
874
875B<NOTE>: DBM::Deep 0.99_03 has turned off circular references pending
876evaluation of some edge cases. I hope to be able to re-enable circular
877references in a future version after 1.00. This means that circular references
878are B<NO LONGER> available.
879
880DBM::Deep has B<experimental> support for circular references. Meaning you
881can have a nested hash key or array element that points to a parent object.
882This relationship is stored in the DB file, and is preserved between sessions.
883Here is an example:
884
885 my $db = DBM::Deep->new( "foo.db" );
886
887 $db->{foo} = "bar";
888 $db->{circle} = $db; # ref to self
889
890 print $db->{foo} . "\n"; # prints "bar"
891 print $db->{circle}->{foo} . "\n"; # prints "bar" again
892
893B<Note>: Passing the object to a function that recursively walks the
894object tree (such as I<Data::Dumper> or even the built-in C<optimize()> or
895C<export()> methods) will result in an infinite loop. This will be fixed in
896a future release.
897
898=head1 TRANSACTIONS
899
900New in 0.99_01 is ACID transactions. Every DBM::Deep object is completely
901transaction-ready - it is not an option you have to turn on. You do have to
902specify how many transactions may run simultaneously (q.v. L</num_txns>).
903
904Three new methods have been added to support them. They are:
905
906=over 4
907
908=item * begin_work()
909
910This starts a transaction.
911
912=item * commit()
913
914This applies the changes done within the transaction to the mainline and ends
915the transaction.
916
917=item * rollback()
918
919This discards the changes done within the transaction to the mainline and ends
920the transaction.
921
922=back
923
924Transactions in DBM::Deep are done using a variant of the MVCC method, the
925same method used by the InnoDB MySQL engine.
926
927=head2 Software-Transactional Memory
928
929The addition of transactions to this module provides the basis for STM within
930Perl 5. Contention is resolved using a default last-write-wins. Currently,
931this default cannot be changed, but it will be addressed in a future version.
932
933=head1 PERFORMANCE
934
935Because DBM::Deep is a conncurrent datastore, every change is flushed to disk
936immediately and every read goes to disk. This means that DBM::Deep functions
937at the speed of disk (generally 10-20ms) vs. the speed of RAM (generally
93850-70ns), or at least 150-200x slower than the comparable in-memory
939datastructure in Perl.
940
941There are several techniques you can use to speed up how DBM::Deep functions.
942
943=over 4
944
945=item * Put it on a ramdisk
946
947The easiest and quickest mechanism to making DBM::Deep run faster is to create
948a ramdisk and locate the DBM::Deep file there. Doing this as an option may
949become a feature of DBM::Deep, assuming there is a good ramdisk wrapper on CPAN.
950
951=item * Work at the tightest level possible
952
953It is much faster to assign the level of your db that you are working with to
954an intermediate variable than to re-look it up every time. Thus
955
956 # BAD
957 while ( my ($k, $v) = each %{$db->{foo}{bar}{baz}} ) {
958 ...
959 }
960
961 # GOOD
962 my $x = $db->{foo}{bar}{baz};
963 while ( my ($k, $v) = each %$x ) {
964 ...
965 }
966
967=item * Make your file as tight as possible
968
969If you know that you are not going to use more than 65K in your database,
970consider using the C<pack_size =E<gt> 'small'> option. This will instruct
971DBM::Deep to use 16bit addresses, meaning that the seek times will be less.
972
973=back
974
975=head1 TODO
976
977The following are items that are planned to be added in future releases. These
978are separate from the L<CAVEATS, ISSUES & BUGS> below.
979
980=head2 Sub-Transactions
981
982Right now, you cannot run a transaction within a transaction. Removing this
983restriction is technically straightforward, but the combinatorial explosion of
984possible usecases hurts my head. If this is something you want to see
985immediately, please submit many testcases.
986
987=head2 Caching
988
989If a user is willing to assert upon opening the file that this process will be
990the only consumer of that datafile, then there are a number of caching
991possibilities that can be taken advantage of. This does, however, mean that
992DBM::Deep is more vulnerable to losing data due to unflushed changes. It also
993means a much larger in-memory footprint. As such, it's not clear exactly how
994this should be done. Suggestions are welcome.
995
996=head2 Ram-only
997
998The techniques used in DBM::Deep simply require a seekable contiguous
999datastore. This could just as easily be a large string as a file. By using
1000substr, the STM capabilities of DBM::Deep could be used within a
1001single-process. I have no idea how I'd specify this, though. Suggestions are
1002welcome.
1003
1004=head2 Importing using Data::Walker
1005
1006Right now, importing is done using C<Clone::clone()> to make a complete copy
1007in memory, then tying that copy. It would be much better to use
1008L<Data::Walker/> to walk the data structure instead, particularly in the case
1009of large datastructures.
1010
1011=head2 Different contention resolution mechanisms
1012
1013Currently, the only contention resolution mechanism is last-write-wins. This
1014is the mechanism used by most RDBMSes and should be good enough for most uses.
1015For advanced uses of STM, other contention mechanisms will be needed. If you
1016have an idea of how you'd like to see contention resolution in DBM::Deep,
1017please let me know.
1018
1019=head1 CAVEATS, ISSUES & BUGS
1020
1021This section describes all the known issues with DBM::Deep. These are issues
1022that are either intractable or depend on some feature within Perl working
1023exactly right. It you have found something that is not listed below, please
1024send an e-mail to L<rkinyon@cpan.org>. Likewise, if you think you know of a
1025way around one of these issues, please let me know.
1026
1027=head2 References
1028
1029(The following assumes a high level of Perl understanding, specifically of
1030references. Most users can safely skip this section.)
1031
1032Currently, the only references supported are HASH and ARRAY. The other reference
1033types (SCALAR, CODE, GLOB, and REF) cannot be supported for various reasons.
1034
1035=over 4
1036
1037=item * GLOB
1038
1039These are things like filehandles and other sockets. They can't be supported
1040because it's completely unclear how DBM::Deep should serialize them.
1041
1042=item * SCALAR / REF
1043
1044The discussion here refers to the following type of example:
1045
1046 my $x = 25;
1047 $db->{key1} = \$x;
1048
1049 $x = 50;
1050
1051 # In some other process ...
1052
1053 my $val = ${ $db->{key1} };
1054
1055 is( $val, 50, "What actually gets stored in the DB file?" );
1056
1057The problem is one of synchronization. When the variable being referred to
1058changes value, the reference isn't notified, which is kind of the point of
1059references. This means that the new value won't be stored in the datafile for
1060other processes to read. There is no TIEREF.
1061
1062It is theoretically possible to store references to values already within a
1063DBM::Deep object because everything already is synchronized, but the change to
1064the internals would be quite large. Specifically, DBM::Deep would have to tie
1065every single value that is stored. This would bloat the RAM footprint of
1066DBM::Deep at least twofold (if not more) and be a significant performance drain,
1067all to support a feature that has never been requested.
1068
1069=item * CODE
1070
1071L<Data::Dump::Streamer/> provides a mechanism for serializing coderefs,
1072including saving off all closure state. This would allow for DBM::Deep to
1073store the code for a subroutine. Then, whenever the subroutine is read, the
1074code could be C<eval()>'ed into being. However, just as for SCALAR and REF,
1075that closure state may change without notifying the DBM::Deep object storing
1076the reference. Again, this would generally be considered a feature.
1077
1078=back
1079
1080=head2 File corruption
1081
1082The current level of error handling in DBM::Deep is minimal. Files I<are> checked
1083for a 32-bit signature when opened, but any other form of corruption in the
1084datafile can cause segmentation faults. DBM::Deep may try to C<seek()> past
1085the end of a file, or get stuck in an infinite loop depending on the level and
1086type of corruption. File write operations are not checked for failure (for
1087speed), so if you happen to run out of disk space, DBM::Deep will probably fail in
1088a bad way. These things will be addressed in a later version of DBM::Deep.
1089
1090=head2 DB over NFS
1091
1092Beware of using DBM::Deep files over NFS. DBM::Deep uses flock(), which works
1093well on local filesystems, but will NOT protect you from file corruption over
1094NFS. I've heard about setting up your NFS server with a locking daemon, then
1095using C<lockf()> to lock your files, but your mileage may vary there as well.
1096From what I understand, there is no real way to do it. However, if you need
1097access to the underlying filehandle in DBM::Deep for using some other kind of
1098locking scheme like C<lockf()>, see the L<LOW-LEVEL ACCESS> section above.
1099
1100=head2 Copying Objects
1101
1102Beware of copying tied objects in Perl. Very strange things can happen.
1103Instead, use DBM::Deep's C<clone()> method which safely copies the object and
1104returns a new, blessed and tied hash or array to the same level in the DB.
1105
1106 my $copy = $db->clone();
1107
1108B<Note>: Since clone() here is cloning the object, not the database location, any
1109modifications to either $db or $copy will be visible to both.
1110
1111=head2 Large Arrays
1112
1113Beware of using C<shift()>, C<unshift()> or C<splice()> with large arrays.
1114These functions cause every element in the array to move, which can be murder
1115on DBM::Deep, as every element has to be fetched from disk, then stored again in
1116a different location. This will be addressed in a future version.
1117
1118=head2 Writeonly Files
1119
1120If you pass in a filehandle to new(), you may have opened it in either a readonly or
1121writeonly mode. STORE will verify that the filehandle is writable. However, there
1122doesn't seem to be a good way to determine if a filehandle is readable. And, if the
1123filehandle isn't readable, it's not clear what will happen. So, don't do that.
1124
1125=head2 Assignments Within Transactions
1126
1127The following will I<not> work as one might expect:
1128
1129 my $x = { a => 1 };
1130
1131 $db->begin_work;
1132 $db->{foo} = $x;
1133 $db->rollback;
1134
1135 is( $x->{a}, 1 ); # This will fail!
1136
1137The problem is that the moment a reference used as the rvalue to a DBM::Deep
1138object's lvalue, it becomes tied itself. This is so that future changes to
1139C<$x> can be tracked within the DBM::Deep file and is considered to be a
1140feature. By the time the rollback occurs, there is no knowledge that there had
1141been an C<$x> or what memory location to assign an C<export()> to.
1142
1143B<NOTE:> This does not affect importing because imports do a walk over the
1144reference to be imported in order to explicitly leave it untied.
1145
1146=head1 CODE COVERAGE
1147
1148B<Devel::Cover> is used to test the code coverage of the tests. Below is the
1149B<Devel::Cover> report on this distribution's test suite.
1150
1151 ---------------------------- ------ ------ ------ ------ ------ ------ ------
1152 File stmt bran cond sub pod time total
1153 ---------------------------- ------ ------ ------ ------ ------ ------ ------
1154 blib/lib/DBM/Deep.pm 96.8 87.9 90.5 100.0 89.5 4.5 95.2
1155 blib/lib/DBM/Deep/Array.pm 100.0 94.3 100.0 100.0 100.0 4.9 98.7
1156 blib/lib/DBM/Deep/Engine.pm 96.9 85.2 79.7 100.0 0.0 58.2 90.3
1157 blib/lib/DBM/Deep/File.pm 99.0 88.9 77.8 100.0 0.0 30.0 90.3
1158 blib/lib/DBM/Deep/Hash.pm 100.0 100.0 100.0 100.0 100.0 2.4 100.0
1159 Total 97.6 87.9 84.0 100.0 32.1 100.0 92.8
1160 ---------------------------- ------ ------ ------ ------ ------ ------ ------
1161
1162=head1 MORE INFORMATION
1163
1164Check out the DBM::Deep Google Group at L<http://groups.google.com/group/DBM-Deep>
1165or send email to L<DBM-Deep@googlegroups.com>. You can also visit #dbm-deep on
1166irc.perl.org
1167
1168The source code repository is at L<http://svn.perl.org/modules/DBM-Deep>
1169
1170=head1 MAINTAINER(S)
1171
1172Rob Kinyon, L<rkinyon@cpan.org>
1173
1174Originally written by Joseph Huckaby, L<jhuckaby@cpan.org>
1175
1176=head1 CONTRIBUTORS
1177
1178The following have contributed greatly to make DBM::Deep what it is today:
1179
1180=over 4
1181
1182=item * Adam Sah and Rich Gaushell
1183
1184=item * Stonehenge for sponsoring the 1.00 release
1185
1186=item * Dan Golden and others at YAPC::NA 2006 for helping me design through transactions.
1187
1188=back
1189
1190=head1 SEE ALSO
1191
1192perltie(1), Tie::Hash(3), Digest::MD5(3), Fcntl(3), flock(2), lockf(3), nfs(5),
1193Digest::SHA256(3), Crypt::Blowfish(3), Compress::Zlib(3)
1194
1195=head1 LICENSE
1196
1197Copyright (c) 2007 Rob Kinyon. All Rights Reserved.
1198This is free software, you may use it and distribute it under the
1199same terms as Perl itself.
1200
1201=cut