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