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