Added supports() and rewrote the tests so that Engine::DBI doesn't run the transactio...
[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
807f63a7 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.
2120a181 52
53=head1 SETUP
54
55Construction can be done OO-style (which is the recommended way), or using
56Perl's tie() function. Both are examined here.
57
58=head2 OO Construction
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
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
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
71locking, autoflush, etc. This is done by passing an inline hash (or hashref):
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
81constructor. This is required if any options are specified.
82See L<OPTIONS> below for the complete list.
83
84You can also start with an array instead of a hash. For this, you must
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
93a new DB file. If you create a DBM::Deep object with an existing file, the
94C<type> will be loaded from the file header, and an error will be thrown if
95the wrong type is passed in.
96
97=head2 Tie Construction
98
99Alternately, you can create a DBM::Deep handle by using Perl's built-in
100tie() function. The object returned from tie() can be used to call methods,
101such as lock() and unlock(). (That object can be retrieved from the tied
b8370759 102variable at any time using tied() - please see L<perltie> for more info.
2120a181 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
120=head2 Options
121
122There are a number of options that can be passed in when constructing your
123DBM::Deep objects. These apply to both the OO- and tie- based approaches.
124
125=over
126
127=item * file
128
129Filename of the DB file to link the handle to. You can pass a full absolute
130filesystem path, partial path, or a plain filename if the file is in the
131current working directory. This is a required parameter (though q.v. fh).
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
154This parameter specifies what type of object to create, a hash or array. Use
155one of these two constants:
156
157=over 4
158
2c70efe1 159=item * C<<DBM::Deep->TYPE_HASH>>
2120a181 160
2c70efe1 161=item * C<<DBM::Deep->TYPE_ARRAY>>
2120a181 162
163=back
164
165This only takes effect when beginning a new file. This is an optional
2c70efe1 166parameter, and defaults to C<<DBM::Deep->TYPE_HASH>>.
2120a181 167
168=item * locking
169
170Specifies whether locking is to be enabled. DBM::Deep uses Perl's flock()
171function to lock the database in exclusive mode for writes, and shared mode
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
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>).
182Pass any true value to enable. This is an optional parameter, and defaults to 1
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
e9b0b5f0 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.
2120a181 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
e9b0b5f0 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.
2120a181 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
e9b0b5f0 239This uses 2-byte offsets, allowing for a maximum file size of 65 KB.
2120a181 240
241=item * medium (default)
242
e9b0b5f0 243This uses 4-byte offsets, allowing for a maximum file size of 4 GB.
2120a181 244
245=item * large
246
e9b0b5f0 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.
2120a181 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
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
263using regular hashes and arrays, rather than calling functions like C<get()>
264and C<put()> (although those work too). It is entirely up to you how to want
265to access your databases.
266
267=head2 Hashes
268
269You can treat any DBM::Deep object like a normal Perl hash reference. Add keys,
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
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
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
297hash reference, not a lookup. Meaning, you should B<never> do this:
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
307=head2 Arrays
308
309As with hashes, you can treat any DBM::Deep object like a normal Perl array
310reference. This includes inserting, removing and manipulating elements,
311and the C<push()>, C<pop()>, C<shift()>, C<unshift()> and C<splice()> functions.
2c70efe1 312The object must have first been created using type C<<DBM::Deep->TYPE_ARRAY>>,
2120a181 313or simply be a nested array reference inside a hash. Example:
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
2c70efe1 324 my $last_elem = pop @$db; # baz
325 my $first_elem = shift @$db; # bah
326 my $second_elem = $db->[1]; # bar
2120a181 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
333to manipulate all aspects of DBM::Deep databases. Each type of object (hash or
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
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.
349
350 $db->put("foo", "bar"); # for hashes
351 $db->put(1, "bar"); # for arrays
352
353=item * get() / fetch()
354
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
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
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.
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
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,
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
376internal arrays work.
377
378 $db->delete("foo"); # for hashes
379 $db->delete(1); # for arrays
380
381=item * clear()
382
383Deletes B<all> hash keys or array elements. Takes no arguments. No return
384value.
385
386 $db->clear(); # hashes or arrays
387
9c87a079 388=item * lock() / unlock() / lock_exclusive() / lock_shared()
2120a181 389
e00d0eb3 390q.v. L</LOCKING> for more info.
2120a181 391
392=item * optimize()
393
e00d0eb3 394This will compress the datafile so that it takes up as little space as possible.
395There is a freespace manager so that when space is freed up, it is used before
396extending the size of the datafile. But, that freespace just sits in the datafile
397unless C<optimize()> is called.
2120a181 398
e00d0eb3 399=item * import()
2120a181 400
e00d0eb3 401Unlike simple assignment, C<import()> does not tie the right-hand side. Instead,
402a copy of your data is put into the DB. C<import()> takes either an arrayref (if
403your DB is an array) or a hashref (if your DB is a hash). C<import()> will die
404if anything else is passed in.
405
406=item * export()
407
408This returns a complete copy of the data structure at the point you do the export.
409This copy is in RAM, not on disk like the DB is.
2120a181 410
411=item * begin_work() / commit() / rollback()
412
413These are the transactional functions. L</TRANSACTIONS> for more information.
414
580e5ee2 415=item * supports( $option )
416
417This returns a boolean depending on if this instance of DBM::Dep supports
418that feature. C<$option> can be one of:
419
420=over 4
421
422=item * transactions
423
424=back
425
2120a181 426=back
427
428=head2 Hashes
429
430For hashes, DBM::Deep supports all the common methods described above, and the
431following additional methods: C<first_key()> and C<next_key()>.
432
433=over
434
435=item * first_key()
436
437Returns the "first" key in the hash. As with built-in Perl hashes, keys are
438fetched in an undefined order (which appears random). Takes no arguments,
439returns the key as a scalar value.
440
441 my $key = $db->first_key();
442
443=item * next_key()
444
445Returns the "next" key in the hash, given the previous one as the sole argument.
446Returns undef if there are no more keys to be fetched.
447
448 $key = $db->next_key($key);
449
450=back
451
452Here are some examples of using hashes:
453
454 my $db = DBM::Deep->new( "foo.db" );
455
456 $db->put("foo", "bar");
457 print "foo: " . $db->get("foo") . "\n";
458
459 $db->put("baz", {}); # new child hash ref
460 $db->get("baz")->put("buz", "biz");
461 print "buz: " . $db->get("baz")->get("buz") . "\n";
462
463 my $key = $db->first_key();
464 while ($key) {
465 print "$key: " . $db->get($key) . "\n";
466 $key = $db->next_key($key);
467 }
468
469 if ($db->exists("foo")) { $db->delete("foo"); }
470
471=head2 Arrays
472
473For arrays, DBM::Deep supports all the common methods described above, and the
474following additional methods: C<length()>, C<push()>, C<pop()>, C<shift()>,
475C<unshift()> and C<splice()>.
476
477=over
478
479=item * length()
480
481Returns the number of elements in the array. Takes no arguments.
482
483 my $len = $db->length();
484
485=item * push()
486
487Adds one or more elements onto the end of the array. Accepts scalars, hash
488refs or array refs. No return value.
489
490 $db->push("foo", "bar", {});
491
492=item * pop()
493
494Fetches the last element in the array, and deletes it. Takes no arguments.
495Returns undef if array is empty. Returns the element value.
496
497 my $elem = $db->pop();
498
499=item * shift()
500
501Fetches the first element in the array, deletes it, then shifts all the
502remaining elements over to take up the space. Returns the element value. This
503method is not recommended with large arrays -- see L<LARGE ARRAYS> below for
504details.
505
506 my $elem = $db->shift();
507
508=item * unshift()
509
510Inserts one or more elements onto the beginning of the array, shifting all
511existing elements over to make room. Accepts scalars, hash refs or array refs.
512No return value. This method is not recommended with large arrays -- see
513<LARGE ARRAYS> below for details.
514
515 $db->unshift("foo", "bar", {});
516
517=item * splice()
518
519Performs exactly like Perl's built-in function of the same name. See L<perldoc
520-f splice> for usage -- it is too complicated to document here. This method is
521not recommended with large arrays -- see L<LARGE ARRAYS> below for details.
522
523=back
524
525Here are some examples of using arrays:
526
527 my $db = DBM::Deep->new(
528 file => "foo.db",
529 type => DBM::Deep->TYPE_ARRAY
530 );
531
532 $db->push("bar", "baz");
533 $db->unshift("foo");
534 $db->put(3, "buz");
535
536 my $len = $db->length();
537 print "length: $len\n"; # 4
538
539 for (my $k=0; $k<$len; $k++) {
540 print "$k: " . $db->get($k) . "\n";
541 }
542
543 $db->splice(1, 2, "biz", "baf");
544
545 while (my $elem = shift @$db) {
546 print "shifted: $elem\n";
547 }
548
549=head1 LOCKING
550
551Enable or disable automatic file locking by passing a boolean value to the
552C<locking> parameter when constructing your DBM::Deep object (see L<SETUP>
1cff45d7 553above).
2120a181 554
555 my $db = DBM::Deep->new(
556 file => "foo.db",
557 locking => 1
558 );
559
560This causes DBM::Deep to C<flock()> the underlying filehandle with exclusive
561mode for writes, and shared mode for reads. This is required if you have
562multiple processes accessing the same database file, to avoid file corruption.
563Please note that C<flock()> does NOT work for files over NFS. See L<DB OVER
564NFS> below for more.
565
566=head2 Explicit Locking
567
568You can explicitly lock a database, so it remains locked for multiple
9c87a079 569actions. This is done by calling the C<lock_exclusive()> method (for when you
570want to write) or the C<lock_shared()> method (for when you want to read).
571This is particularly useful for things like counters, where the current value
572needs to be fetched, then incremented, then stored again.
2120a181 573
9c87a079 574 $db->lock_exclusive();
2120a181 575 my $counter = $db->get("counter");
576 $counter++;
577 $db->put("counter", $counter);
578 $db->unlock();
579
580 # or...
581
9c87a079 582 $db->lock_exclusive();
2120a181 583 $db->{counter}++;
584 $db->unlock();
585
45f047f8 586=head2 Win32/Cygwin
587
588Due to Win32 actually enforcing the read-only status of a shared lock, all
589locks on Win32 and cygwin are exclusive. This is because of how autovivification
590currently works. Hopefully, this will go away in a future release.
591
2120a181 592=head1 IMPORTING/EXPORTING
593
594You can import existing complex structures by calling the C<import()> method,
595and export an entire database into an in-memory structure using the C<export()>
596method. Both are examined here.
597
598=head2 Importing
599
600Say you have an existing hash with nested hashes/arrays inside it. Instead of
601walking the structure and adding keys/elements to the database as you go,
602simply pass a reference to the C<import()> method. This recursively adds
603everything to an existing DBM::Deep object for you. Here is an example:
604
605 my $struct = {
606 key1 => "value1",
607 key2 => "value2",
608 array1 => [ "elem0", "elem1", "elem2" ],
609 hash1 => {
610 subkey1 => "subvalue1",
611 subkey2 => "subvalue2"
612 }
613 };
614
615 my $db = DBM::Deep->new( "foo.db" );
616 $db->import( $struct );
617
618 print $db->{key1} . "\n"; # prints "value1"
619
620This recursively imports the entire C<$struct> object into C<$db>, including
621all nested hashes and arrays. If the DBM::Deep object contains exsiting data,
622keys are merged with the existing ones, replacing if they already exist.
623The C<import()> method can be called on any database level (not just the base
624level), and works with both hash and array DB types.
625
626B<Note:> Make sure your existing structure has no circular references in it.
627These will cause an infinite loop when importing. There are plans to fix this
628in a later release.
629
2120a181 630=head2 Exporting
631
632Calling the C<export()> method on an existing DBM::Deep object will return
633a reference to a new in-memory copy of the database. The export is done
634recursively, so all nested hashes/arrays are all exported to standard Perl
635objects. Here is an example:
636
637 my $db = DBM::Deep->new( "foo.db" );
638
639 $db->{key1} = "value1";
640 $db->{key2} = "value2";
641 $db->{hash1} = {};
642 $db->{hash1}->{subkey1} = "subvalue1";
643 $db->{hash1}->{subkey2} = "subvalue2";
644
645 my $struct = $db->export();
646
647 print $struct->{key1} . "\n"; # prints "value1"
648
649This makes a complete copy of the database in memory, and returns a reference
650to it. The C<export()> method can be called on any database level (not just
651the base level), and works with both hash and array DB types. Be careful of
652large databases -- you can store a lot more data in a DBM::Deep object than an
653in-memory Perl structure.
654
655B<Note:> Make sure your database has no circular references in it.
656These will cause an infinite loop when exporting. There are plans to fix this
657in a later release.
658
659=head1 FILTERS
660
661DBM::Deep has a number of hooks where you can specify your own Perl function
662to perform filtering on incoming or outgoing data. This is a perfect
663way to extend the engine, and implement things like real-time compression or
664encryption. Filtering applies to the base DB level, and all child hashes /
665arrays. Filter hooks can be specified when your DBM::Deep object is first
666constructed, or by calling the C<set_filter()> method at any time. There are
1cff45d7 667four available filter hooks.
668
669=head2 set_filter()
670
671This method takes two paramters - the filter type and the filter subreference.
672The four types are:
2120a181 673
674=over
675
676=item * filter_store_key
677
678This filter is called whenever a hash key is stored. It
679is passed the incoming key, and expected to return a transformed key.
680
681=item * filter_store_value
682
683This filter is called whenever a hash key or array element is stored. It
684is passed the incoming value, and expected to return a transformed value.
685
686=item * filter_fetch_key
687
688This filter is called whenever a hash key is fetched (i.e. via
689C<first_key()> or C<next_key()>). It is passed the transformed key,
690and expected to return the plain key.
691
692=item * filter_fetch_value
693
694This filter is called whenever a hash key or array element is fetched.
695It is passed the transformed value, and expected to return the plain value.
696
697=back
698
699Here are the two ways to setup a filter hook:
700
701 my $db = DBM::Deep->new(
702 file => "foo.db",
703 filter_store_value => \&my_filter_store,
704 filter_fetch_value => \&my_filter_fetch
705 );
706
707 # or...
708
709 $db->set_filter( "filter_store_value", \&my_filter_store );
710 $db->set_filter( "filter_fetch_value", \&my_filter_fetch );
711
712Your filter function will be called only when dealing with SCALAR keys or
713values. When nested hashes and arrays are being stored/fetched, filtering
714is bypassed. Filters are called as static functions, passed a single SCALAR
715argument, and expected to return a single SCALAR value. If you want to
716remove a filter, set the function reference to C<undef>:
717
718 $db->set_filter( "filter_store_value", undef );
719
1cff45d7 720=head2 Examples
2120a181 721
b8370759 722Please read L<DBM::Deep::Manual> for examples of filters.
2120a181 723
724=head1 ERROR HANDLING
725
726Most DBM::Deep methods return a true value for success, and call die() on
727failure. You can wrap calls in an eval block to catch the die.
728
729 my $db = DBM::Deep->new( "foo.db" ); # create hash
730 eval { $db->push("foo"); }; # ILLEGAL -- push is array-only call
731
732 print $@; # prints error message
733
734=head1 LARGEFILE SUPPORT
735
736If you have a 64-bit system, and your Perl is compiled with both LARGEFILE
e9b0b5f0 737and 64-bit support, you I<may> be able to create databases larger than 4 GB.
2120a181 738DBM::Deep by default uses 32-bit file offset tags, but these can be changed
739by specifying the 'pack_size' parameter when constructing the file.
740
741 DBM::Deep->new(
2c70efe1 742 file => $filename,
2120a181 743 pack_size => 'large',
744 );
745
746This tells DBM::Deep to pack all file offsets with 8-byte (64-bit) quad words
747instead of 32-bit longs. After setting these values your DB files have a
748theoretical maximum size of 16 XB (exabytes).
749
2c70efe1 750You can also use C<<pack_size => 'small'>> in order to use 16-bit file
2120a181 751offsets.
752
753B<Note:> Changing these values will B<NOT> work for existing database files.
754Only change this for new files. Once the value has been set, it is stored in
755the file's header and cannot be changed for the life of the file. These
756parameters are per-file, meaning you can access 32-bit and 64-bit files, as
757you choose.
758
1cff45d7 759B<Note:> We have not personally tested files larger than 4 GB -- all our
760systems have only a 32-bit Perl. However, we have received user reports that
e9b0b5f0 761this does indeed work.
2120a181 762
763=head1 LOW-LEVEL ACCESS
764
765If you require low-level access to the underlying filehandle that DBM::Deep uses,
766you can call the C<_fh()> method, which returns the handle:
767
768 my $fh = $db->_fh();
769
770This method can be called on the root level of the datbase, or any child
771hashes or arrays. All levels share a I<root> structure, which contains things
772like the filehandle, a reference counter, and all the options specified
773when you created the object. You can get access to this file object by
774calling the C<_storage()> method.
775
776 my $file_obj = $db->_storage();
777
778This is useful for changing options after the object has already been created,
779such as enabling/disabling locking. You can also store your own temporary user
780data in this structure (be wary of name collision), which is then accessible from
781any child hash or array.
782
2120a181 783=head1 CIRCULAR REFERENCES
784
1cff45d7 785DBM::Deep has full support for circular references. Meaning you
2120a181 786can have a nested hash key or array element that points to a parent object.
787This relationship is stored in the DB file, and is preserved between sessions.
788Here is an example:
789
790 my $db = DBM::Deep->new( "foo.db" );
791
792 $db->{foo} = "bar";
793 $db->{circle} = $db; # ref to self
794
795 print $db->{foo} . "\n"; # prints "bar"
796 print $db->{circle}->{foo} . "\n"; # prints "bar" again
797
1cff45d7 798This also works as expected with array and hash references. So, the following
799works as expected:
800
801 $db->{foo} = [ 1 .. 3 ];
802 $db->{bar} = $db->{foo};
803
804 push @{$db->{foo}}, 42;
805 is( $db->{bar}[-1], 42 ); # Passes
806
807This, however, does I<not> extend to assignments from one DB file to another.
808So, the following will throw an error:
809
810 my $db1 = DBM::Deep->new( "foo.db" );
811 my $db2 = DBM::Deep->new( "bar.db" );
812
813 $db1->{foo} = [];
814 $db2->{foo} = $db1->{foo}; # dies
815
2120a181 816B<Note>: Passing the object to a function that recursively walks the
817object tree (such as I<Data::Dumper> or even the built-in C<optimize()> or
818C<export()> methods) will result in an infinite loop. This will be fixed in
1cff45d7 819a future release by adding singleton support.
2120a181 820
821=head1 TRANSACTIONS
822
1cff45d7 823As of 1.0000, DBM::Deep hass ACID transactions. Every DBM::Deep object is completely
2120a181 824transaction-ready - it is not an option you have to turn on. You do have to
825specify how many transactions may run simultaneously (q.v. L</num_txns>).
826
827Three new methods have been added to support them. They are:
828
829=over 4
830
831=item * begin_work()
832
833This starts a transaction.
834
835=item * commit()
836
837This applies the changes done within the transaction to the mainline and ends
838the transaction.
839
840=item * rollback()
841
842This discards the changes done within the transaction to the mainline and ends
843the transaction.
844
845=back
846
847Transactions in DBM::Deep are done using a variant of the MVCC method, the
848same method used by the InnoDB MySQL engine.
849
e9b0b5f0 850=head1 MIGRATION
851
852As of 1.0000, the file format has changed. Furthermore, DBM::Deep is now
853designed to potentially change file format between point-releases, if needed to
854support a requested feature. To aid in this, a migration script is provided
855within the CPAN distribution called C<utils/upgrade_db.pl>.
856
857B<NOTE:> This script is not installed onto your system because it carries a copy
858of every version prior to the current version.
859
2120a181 860=head1 TODO
861
862The following are items that are planned to be added in future releases. These
863are separate from the L<CAVEATS, ISSUES & BUGS> below.
864
865=head2 Sub-Transactions
866
867Right now, you cannot run a transaction within a transaction. Removing this
868restriction is technically straightforward, but the combinatorial explosion of
869possible usecases hurts my head. If this is something you want to see
870immediately, please submit many testcases.
871
872=head2 Caching
873
08164b50 874If a client is willing to assert upon opening the file that this process will be
2120a181 875the only consumer of that datafile, then there are a number of caching
876possibilities that can be taken advantage of. This does, however, mean that
877DBM::Deep is more vulnerable to losing data due to unflushed changes. It also
878means a much larger in-memory footprint. As such, it's not clear exactly how
879this should be done. Suggestions are welcome.
880
881=head2 Ram-only
882
883The techniques used in DBM::Deep simply require a seekable contiguous
884datastore. This could just as easily be a large string as a file. By using
885substr, the STM capabilities of DBM::Deep could be used within a
886single-process. I have no idea how I'd specify this, though. Suggestions are
887welcome.
888
2120a181 889=head2 Different contention resolution mechanisms
890
891Currently, the only contention resolution mechanism is last-write-wins. This
892is the mechanism used by most RDBMSes and should be good enough for most uses.
893For advanced uses of STM, other contention mechanisms will be needed. If you
894have an idea of how you'd like to see contention resolution in DBM::Deep,
895please let me know.
896
897=head1 CAVEATS, ISSUES & BUGS
898
899This section describes all the known issues with DBM::Deep. These are issues
900that are either intractable or depend on some feature within Perl working
901exactly right. It you have found something that is not listed below, please
902send an e-mail to L<rkinyon@cpan.org>. Likewise, if you think you know of a
903way around one of these issues, please let me know.
904
905=head2 References
906
907(The following assumes a high level of Perl understanding, specifically of
908references. Most users can safely skip this section.)
909
910Currently, the only references supported are HASH and ARRAY. The other reference
911types (SCALAR, CODE, GLOB, and REF) cannot be supported for various reasons.
912
913=over 4
914
915=item * GLOB
916
917These are things like filehandles and other sockets. They can't be supported
918because it's completely unclear how DBM::Deep should serialize them.
919
920=item * SCALAR / REF
921
922The discussion here refers to the following type of example:
923
924 my $x = 25;
925 $db->{key1} = \$x;
926
927 $x = 50;
928
929 # In some other process ...
930
931 my $val = ${ $db->{key1} };
932
933 is( $val, 50, "What actually gets stored in the DB file?" );
934
935The problem is one of synchronization. When the variable being referred to
936changes value, the reference isn't notified, which is kind of the point of
937references. This means that the new value won't be stored in the datafile for
938other processes to read. There is no TIEREF.
939
940It is theoretically possible to store references to values already within a
941DBM::Deep object because everything already is synchronized, but the change to
942the internals would be quite large. Specifically, DBM::Deep would have to tie
943every single value that is stored. This would bloat the RAM footprint of
944DBM::Deep at least twofold (if not more) and be a significant performance drain,
945all to support a feature that has never been requested.
946
947=item * CODE
948
b8370759 949L<Data::Dump::Streamer> provides a mechanism for serializing coderefs,
2120a181 950including saving off all closure state. This would allow for DBM::Deep to
951store the code for a subroutine. Then, whenever the subroutine is read, the
952code could be C<eval()>'ed into being. However, just as for SCALAR and REF,
953that closure state may change without notifying the DBM::Deep object storing
954the reference. Again, this would generally be considered a feature.
955
956=back
957
c57b19c6 958=head2 External references and transactions
1cff45d7 959
2c70efe1 960If you do C<<my $x = $db->{foo};>>, then start a transaction, $x will be
c57b19c6 961referencing the database from outside the transaction. A fix for this (and other
962issues with how external references into the database) is being looked into. This
963is the skipped set of tests in t/39_singletons.t and a related issue is the focus
964of t/37_delete_edge_cases.t
1cff45d7 965
2120a181 966=head2 File corruption
967
968The current level of error handling in DBM::Deep is minimal. Files I<are> checked
969for a 32-bit signature when opened, but any other form of corruption in the
970datafile can cause segmentation faults. DBM::Deep may try to C<seek()> past
971the end of a file, or get stuck in an infinite loop depending on the level and
972type of corruption. File write operations are not checked for failure (for
973speed), so if you happen to run out of disk space, DBM::Deep will probably fail in
974a bad way. These things will be addressed in a later version of DBM::Deep.
975
976=head2 DB over NFS
977
978Beware of using DBM::Deep files over NFS. DBM::Deep uses flock(), which works
979well on local filesystems, but will NOT protect you from file corruption over
980NFS. I've heard about setting up your NFS server with a locking daemon, then
981using C<lockf()> to lock your files, but your mileage may vary there as well.
982From what I understand, there is no real way to do it. However, if you need
983access to the underlying filehandle in DBM::Deep for using some other kind of
984locking scheme like C<lockf()>, see the L<LOW-LEVEL ACCESS> section above.
985
986=head2 Copying Objects
987
988Beware of copying tied objects in Perl. Very strange things can happen.
989Instead, use DBM::Deep's C<clone()> method which safely copies the object and
990returns a new, blessed and tied hash or array to the same level in the DB.
991
992 my $copy = $db->clone();
993
994B<Note>: Since clone() here is cloning the object, not the database location, any
995modifications to either $db or $copy will be visible to both.
996
997=head2 Large Arrays
998
999Beware of using C<shift()>, C<unshift()> or C<splice()> with large arrays.
1000These functions cause every element in the array to move, which can be murder
1001on DBM::Deep, as every element has to be fetched from disk, then stored again in
1002a different location. This will be addressed in a future version.
1003
08164b50 1004This has been somewhat addressed so that the cost is constant, regardless of
1005what is stored at those locations. So, small arrays with huge data structures in
1006them are faster. But, large arrays are still large.
1007
2120a181 1008=head2 Writeonly Files
1009
08164b50 1010If you pass in a filehandle to new(), you may have opened it in either a
1011readonly or writeonly mode. STORE will verify that the filehandle is writable.
1012However, there doesn't seem to be a good way to determine if a filehandle is
1013readable. And, if the filehandle isn't readable, it's not clear what will
1014happen. So, don't do that.
2120a181 1015
1016=head2 Assignments Within Transactions
1017
1018The following will I<not> work as one might expect:
1019
1020 my $x = { a => 1 };
1021
1022 $db->begin_work;
1023 $db->{foo} = $x;
1024 $db->rollback;
1025
1026 is( $x->{a}, 1 ); # This will fail!
1027
1028The problem is that the moment a reference used as the rvalue to a DBM::Deep
1029object's lvalue, it becomes tied itself. This is so that future changes to
1030C<$x> can be tracked within the DBM::Deep file and is considered to be a
1031feature. By the time the rollback occurs, there is no knowledge that there had
1032been an C<$x> or what memory location to assign an C<export()> to.
1033
1034B<NOTE:> This does not affect importing because imports do a walk over the
1035reference to be imported in order to explicitly leave it untied.
1036
1037=head1 CODE COVERAGE
1038
b8370759 1039L<Devel::Cover> is used to test the code coverage of the tests. Below is the
1040L<Devel::Cover> report on this distribution's test suite.
2120a181 1041
888453b9 1042 ------------------------------------------ ------ ------ ------ ------ ------
1043 File stmt bran cond sub total
1044 ------------------------------------------ ------ ------ ------ ------ ------
e00d0eb3 1045 blib/lib/DBM/Deep.pm 97.2 90.9 83.3 100.0 95.4
c57b19c6 1046 blib/lib/DBM/Deep/Array.pm 100.0 95.7 100.0 100.0 99.0
e00d0eb3 1047 blib/lib/DBM/Deep/Engine.pm 95.6 84.7 81.6 98.4 92.5
888453b9 1048 blib/lib/DBM/Deep/File.pm 97.2 81.6 66.7 100.0 91.9
1049 blib/lib/DBM/Deep/Hash.pm 100.0 100.0 100.0 100.0 100.0
e00d0eb3 1050 Total 96.7 87.5 82.2 99.2 94.1
888453b9 1051 ------------------------------------------ ------ ------ ------ ------ ------
2120a181 1052
1053=head1 MORE INFORMATION
1054
1055Check out the DBM::Deep Google Group at L<http://groups.google.com/group/DBM-Deep>
1056or send email to L<DBM-Deep@googlegroups.com>. You can also visit #dbm-deep on
1057irc.perl.org
1058
64a531e5 1059The source code repository is at L<http://github.com/robkinyon/dbm-deep>
2120a181 1060
e9b0b5f0 1061=head1 MAINTAINERS
2120a181 1062
1063Rob Kinyon, L<rkinyon@cpan.org>
1064
1065Originally written by Joseph Huckaby, L<jhuckaby@cpan.org>
1066
e9b0b5f0 1067=head1 SPONSORS
1068
1069Stonehenge Consulting (L<http://www.stonehenge.com/>) sponsored the
1070developement of transactions and freespace management, leading to the 1.0000
1071release. A great debt of gratitude goes out to them for their continuing
1072leadership in and support of the Perl community.
1073
2120a181 1074=head1 CONTRIBUTORS
1075
1076The following have contributed greatly to make DBM::Deep what it is today:
1077
1078=over 4
1079
e9b0b5f0 1080=item * Adam Sah and Rich Gaushell for innumerable contributions early on.
2120a181 1081
1082=item * Dan Golden and others at YAPC::NA 2006 for helping me design through transactions.
1083
1084=back
1085
1086=head1 SEE ALSO
1087
1088perltie(1), Tie::Hash(3), Digest::MD5(3), Fcntl(3), flock(2), lockf(3), nfs(5),
1089Digest::SHA256(3), Crypt::Blowfish(3), Compress::Zlib(3)
1090
1091=head1 LICENSE
1092
1093Copyright (c) 2007 Rob Kinyon. All Rights Reserved.
e9b0b5f0 1094This is free software, you may use it and distribute it under the same terms
1095as Perl itself.
2120a181 1096
1097=cut