Integrate change #12820 from macperl to maint and blead;
[p5sagit/p5-mst-13.2.git] / ext / DB_File / DB_File.pm
CommitLineData
a0d0e21e 1# DB_File.pm -- Perl 5 interface to Berkeley DB
2#
6ca2e664 3# written by Paul Marquess (Paul.Marquess@btinternet.com)
e5021521 4# last modified 22nc Oct 2001
5# version 1.79
36477c24 6#
c5da4faf 7# Copyright (c) 1995-2001 Paul Marquess. All rights reserved.
36477c24 8# This program is free software; you can redistribute it and/or
9# modify it under the same terms as Perl itself.
10
8e07c86e 11
12package DB_File::HASHINFO ;
785da04d 13
e5021521 14require 5.00404;
610ab055 15
3245f058 16use warnings;
785da04d 17use strict;
8e07c86e 18use Carp;
88108326 19require Tie::Hash;
20@DB_File::HASHINFO::ISA = qw(Tie::Hash);
8e07c86e 21
88108326 22sub new
8e07c86e 23{
88108326 24 my $pkg = shift ;
25 my %x ;
26 tie %x, $pkg ;
27 bless \%x, $pkg ;
8e07c86e 28}
29
610ab055 30
88108326 31sub TIEHASH
32{
33 my $pkg = shift ;
34
36477c24 35 bless { VALID => { map {$_, 1}
36 qw( bsize ffactor nelem cachesize hash lorder)
37 },
38 GOT => {}
39 }, $pkg ;
88108326 40}
8e07c86e 41
610ab055 42
8e07c86e 43sub FETCH
44{
88108326 45 my $self = shift ;
46 my $key = shift ;
8e07c86e 47
36477c24 48 return $self->{GOT}{$key} if exists $self->{VALID}{$key} ;
88108326 49
50 my $pkg = ref $self ;
51 croak "${pkg}::FETCH - Unknown element '$key'" ;
8e07c86e 52}
53
54
55sub STORE
56{
88108326 57 my $self = shift ;
58 my $key = shift ;
59 my $value = shift ;
60
36477c24 61 if ( exists $self->{VALID}{$key} )
8e07c86e 62 {
36477c24 63 $self->{GOT}{$key} = $value ;
8e07c86e 64 return ;
65 }
66
88108326 67 my $pkg = ref $self ;
68 croak "${pkg}::STORE - Unknown element '$key'" ;
8e07c86e 69}
70
71sub DELETE
72{
88108326 73 my $self = shift ;
74 my $key = shift ;
75
36477c24 76 if ( exists $self->{VALID}{$key} )
8e07c86e 77 {
36477c24 78 delete $self->{GOT}{$key} ;
8e07c86e 79 return ;
80 }
81
88108326 82 my $pkg = ref $self ;
83 croak "DB_File::HASHINFO::DELETE - Unknown element '$key'" ;
8e07c86e 84}
85
88108326 86sub EXISTS
8e07c86e 87{
88108326 88 my $self = shift ;
89 my $key = shift ;
8e07c86e 90
36477c24 91 exists $self->{VALID}{$key} ;
8e07c86e 92}
93
88108326 94sub NotHere
8e07c86e 95{
18d2dc8c 96 my $self = shift ;
88108326 97 my $method = shift ;
8e07c86e 98
18d2dc8c 99 croak ref($self) . " does not define the method ${method}" ;
8e07c86e 100}
101
18d2dc8c 102sub FIRSTKEY { my $self = shift ; $self->NotHere("FIRSTKEY") }
103sub NEXTKEY { my $self = shift ; $self->NotHere("NEXTKEY") }
104sub CLEAR { my $self = shift ; $self->NotHere("CLEAR") }
8e07c86e 105
106package DB_File::RECNOINFO ;
785da04d 107
3245f058 108use warnings;
88108326 109use strict ;
110
045291aa 111@DB_File::RECNOINFO::ISA = qw(DB_File::HASHINFO) ;
8e07c86e 112
113sub TIEHASH
114{
88108326 115 my $pkg = shift ;
116
36477c24 117 bless { VALID => { map {$_, 1}
118 qw( bval cachesize psize flags lorder reclen bfname )
119 },
120 GOT => {},
121 }, $pkg ;
8e07c86e 122}
123
88108326 124package DB_File::BTREEINFO ;
8e07c86e 125
3245f058 126use warnings;
88108326 127use strict ;
8e07c86e 128
88108326 129@DB_File::BTREEINFO::ISA = qw(DB_File::HASHINFO) ;
8e07c86e 130
88108326 131sub TIEHASH
8e07c86e 132{
88108326 133 my $pkg = shift ;
134
36477c24 135 bless { VALID => { map {$_, 1}
136 qw( flags cachesize maxkeypage minkeypage psize
137 compare prefix lorder )
138 },
139 GOT => {},
140 }, $pkg ;
8e07c86e 141}
142
143
8e07c86e 144package DB_File ;
785da04d 145
3245f058 146use warnings;
785da04d 147use strict;
b90e71be 148use vars qw($VERSION @ISA @EXPORT $AUTOLOAD $DB_BTREE $DB_HASH $DB_RECNO
149 $db_version $use_XSLoader
150 ) ;
8e07c86e 151use Carp;
152
785da04d 153
e5021521 154$VERSION = "1.79" ;
8e07c86e 155
156#typedef enum { DB_BTREE, DB_HASH, DB_RECNO } DBTYPE;
88108326 157$DB_BTREE = new DB_File::BTREEINFO ;
158$DB_HASH = new DB_File::HASHINFO ;
159$DB_RECNO = new DB_File::RECNOINFO ;
8e07c86e 160
785da04d 161require Tie::Hash;
8e07c86e 162require Exporter;
163use AutoLoader;
b90e71be 164BEGIN {
165 $use_XSLoader = 1 ;
e5021521 166 { local $SIG{__DIE__} ; eval { require XSLoader } ; }
b90e71be 167
168 if ($@) {
169 $use_XSLoader = 0 ;
170 require DynaLoader;
171 @ISA = qw(DynaLoader);
172 }
173}
174
175push @ISA, qw(Tie::Hash Exporter);
8e07c86e 176@EXPORT = qw(
177 $DB_BTREE $DB_HASH $DB_RECNO
88108326 178
8e07c86e 179 BTREEMAGIC
180 BTREEVERSION
181 DB_LOCK
182 DB_SHMEM
183 DB_TXN
184 HASHMAGIC
185 HASHVERSION
186 MAX_PAGE_NUMBER
187 MAX_PAGE_OFFSET
188 MAX_REC_NUMBER
189 RET_ERROR
190 RET_SPECIAL
191 RET_SUCCESS
192 R_CURSOR
193 R_DUP
194 R_FIRST
195 R_FIXEDLEN
196 R_IAFTER
197 R_IBEFORE
198 R_LAST
199 R_NEXT
200 R_NOKEY
201 R_NOOVERWRITE
202 R_PREV
203 R_RECNOSYNC
204 R_SETCURSOR
205 R_SNAPSHOT
206 __R_UNUSED
88108326 207
045291aa 208);
8e07c86e 209
210sub AUTOLOAD {
785da04d 211 my($constname);
8e07c86e 212 ($constname = $AUTOLOAD) =~ s/.*:://;
785da04d 213 my $val = constant($constname, @_ ? $_[0] : 0);
8e07c86e 214 if ($! != 0) {
265f5c4a 215 if ($! =~ /Invalid/ || $!{EINVAL}) {
8e07c86e 216 $AutoLoader::AUTOLOAD = $AUTOLOAD;
217 goto &AutoLoader::AUTOLOAD;
218 }
219 else {
785da04d 220 my($pack,$file,$line) = caller;
8e07c86e 221 croak "Your vendor has not defined DB macro $constname, used at $file line $line.
222";
223 }
224 }
57c77851 225 no strict 'refs';
226 *{$AUTOLOAD} = sub { $val };
227 goto &{$AUTOLOAD};
8e07c86e 228}
229
f6b705ef 230
a6ed719b 231eval {
1f70e1ea 232 # Make all Fcntl O_XXX constants available for importing
233 require Fcntl;
234 my @O = grep /^O_/, @Fcntl::EXPORT;
235 Fcntl->import(@O); # first we import what we want to export
236 push(@EXPORT, @O);
a6ed719b 237};
f6b705ef 238
b90e71be 239if ($use_XSLoader)
240 { XSLoader::load("DB_File", $VERSION)}
241else
242 { bootstrap DB_File $VERSION }
8e07c86e 243
244# Preloaded methods go here. Autoload methods go after __END__, and are
245# processed by the autosplit program.
246
05475680 247sub tie_hash_or_array
610ab055 248{
249 my (@arg) = @_ ;
05475680 250 my $tieHASH = ( (caller(1))[3] =~ /TIEHASH/ ) ;
610ab055 251
252 $arg[4] = tied %{ $arg[4] }
253 if @arg >= 5 && ref $arg[4] && $arg[4] =~ /=HASH/ && tied %{ $arg[4] } ;
254
1f70e1ea 255 # make recno in Berkeley DB version 2 work like recno in version 1.
256 if ($db_version > 1 and defined $arg[4] and $arg[4] =~ /RECNO/ and
257 $arg[1] and ! -e $arg[1]) {
258 open(FH, ">$arg[1]") or return undef ;
259 close FH ;
260 chmod $arg[3] ? $arg[3] : 0666 , $arg[1] ;
261 }
262
05475680 263 DoTie_($tieHASH, @arg) ;
610ab055 264}
265
05475680 266sub TIEHASH
267{
268 tie_hash_or_array(@_) ;
269}
270
271sub TIEARRAY
272{
273 tie_hash_or_array(@_) ;
274}
88108326 275
045291aa 276sub CLEAR
277{
1f70e1ea 278 my $self = shift;
3245f058 279 my $key = 0 ;
1f70e1ea 280 my $value = "" ;
281 my $status = $self->seq($key, $value, R_FIRST());
282 my @keys;
283
284 while ($status == 0) {
285 push @keys, $key;
286 $status = $self->seq($key, $value, R_NEXT());
287 }
288 foreach $key (reverse @keys) {
289 my $s = $self->del($key);
290 }
291}
292
045291aa 293sub EXTEND { }
294
295sub STORESIZE
296{
297 my $self = shift;
298 my $length = shift ;
299 my $current_length = $self->length() ;
300
301 if ($length < $current_length) {
302 my $key ;
303 for ($key = $current_length - 1 ; $key >= $length ; -- $key)
304 { $self->del($key) }
305 }
a9fd575d 306 elsif ($length > $current_length) {
307 $self->put($length-1, "") ;
308 }
045291aa 309}
310
c5da4faf 311
312sub SPLICE
313{
314 my $self = shift;
315 my $offset = shift;
316 if (not defined $offset) {
317 carp 'Use of uninitialized value in splice';
318 $offset = 0;
319 }
320
321 my $length = @_ ? shift : 0;
322 # Carping about definedness comes _after_ the OFFSET sanity check.
323 # This is so we get the same error messages as Perl's splice().
324 #
325
326 my @list = @_;
327
328 my $size = $self->FETCHSIZE();
329
330 # 'If OFFSET is negative then it start that far from the end of
331 # the array.'
332 #
333 if ($offset < 0) {
334 my $new_offset = $size + $offset;
335 if ($new_offset < 0) {
336 die "Modification of non-creatable array value attempted, "
337 . "subscript $offset";
338 }
339 $offset = $new_offset;
340 }
341
342 if ($offset > $size) {
343 $offset = $size;
344 }
345
346 if (not defined $length) {
347 carp 'Use of uninitialized value in splice';
348 $length = 0;
349 }
350
351 # 'If LENGTH is omitted, removes everything from OFFSET onward.'
352 if (not defined $length) {
353 $length = $size - $offset;
354 }
355
356 # 'If LENGTH is negative, leave that many elements off the end of
357 # the array.'
358 #
359 if ($length < 0) {
360 $length = $size - $offset + $length;
361
362 if ($length < 0) {
363 # The user must have specified a length bigger than the
364 # length of the array passed in. But perl's splice()
365 # doesn't catch this, it just behaves as for length=0.
366 #
367 $length = 0;
368 }
369 }
370
371 if ($length > $size - $offset) {
372 $length = $size - $offset;
373 }
374
375 # $num_elems holds the current number of elements in the database.
376 my $num_elems = $size;
377
378 # 'Removes the elements designated by OFFSET and LENGTH from an
379 # array,'...
380 #
381 my @removed = ();
382 foreach (0 .. $length - 1) {
383 my $old;
384 my $status = $self->get($offset, $old);
385 if ($status != 0) {
386 my $msg = "error from Berkeley DB on get($offset, \$old)";
387 if ($status == 1) {
388 $msg .= ' (no such element?)';
389 }
390 else {
391 $msg .= ": error status $status";
392 if (defined $! and $! ne '') {
393 $msg .= ", message $!";
394 }
395 }
396 die $msg;
397 }
398 push @removed, $old;
399
400 $status = $self->del($offset);
401 if ($status != 0) {
402 my $msg = "error from Berkeley DB on del($offset)";
403 if ($status == 1) {
404 $msg .= ' (no such element?)';
405 }
406 else {
407 $msg .= ": error status $status";
408 if (defined $! and $! ne '') {
409 $msg .= ", message $!";
410 }
411 }
412 die $msg;
413 }
414
415 -- $num_elems;
416 }
417
418 # ...'and replaces them with the elements of LIST, if any.'
419 my $pos = $offset;
420 while (defined (my $elem = shift @list)) {
421 my $old_pos = $pos;
422 my $status;
423 if ($pos >= $num_elems) {
424 $status = $self->put($pos, $elem);
425 }
426 else {
427 $status = $self->put($pos, $elem, $self->R_IBEFORE);
428 }
429
430 if ($status != 0) {
431 my $msg = "error from Berkeley DB on put($pos, $elem, ...)";
432 if ($status == 1) {
433 $msg .= ' (no such element?)';
434 }
435 else {
436 $msg .= ", error status $status";
437 if (defined $! and $! ne '') {
438 $msg .= ", message $!";
439 }
440 }
441 die $msg;
442 }
443
444 die "pos unexpectedly changed from $old_pos to $pos with R_IBEFORE"
445 if $old_pos != $pos;
446
447 ++ $pos;
448 ++ $num_elems;
449 }
450
451 if (wantarray) {
452 # 'In list context, returns the elements removed from the
453 # array.'
454 #
455 return @removed;
456 }
457 elsif (defined wantarray and not wantarray) {
458 # 'In scalar context, returns the last element removed, or
459 # undef if no elements are removed.'
460 #
461 if (@removed) {
462 my $last = pop @removed;
463 return "$last";
464 }
465 else {
466 return undef;
467 }
468 }
469 elsif (not defined wantarray) {
470 # Void context
471 }
472 else { die }
473}
474sub ::DB_File::splice { &SPLICE }
475
6ca2e664 476sub find_dup
477{
478 croak "Usage: \$db->find_dup(key,value)\n"
479 unless @_ == 3 ;
480
481 my $db = shift ;
482 my ($origkey, $value_wanted) = @_ ;
483 my ($key, $value) = ($origkey, 0);
484 my ($status) = 0 ;
485
486 for ($status = $db->seq($key, $value, R_CURSOR() ) ;
487 $status == 0 ;
488 $status = $db->seq($key, $value, R_NEXT() ) ) {
489
490 return 0 if $key eq $origkey and $value eq $value_wanted ;
491 }
492
493 return $status ;
494}
495
496sub del_dup
497{
498 croak "Usage: \$db->del_dup(key,value)\n"
499 unless @_ == 3 ;
500
501 my $db = shift ;
502 my ($key, $value) = @_ ;
503 my ($status) = $db->find_dup($key, $value) ;
504 return $status if $status != 0 ;
505
506 $status = $db->del($key, R_CURSOR() ) ;
507 return $status ;
508}
509
88108326 510sub get_dup
511{
512 croak "Usage: \$db->get_dup(key [,flag])\n"
513 unless @_ == 2 or @_ == 3 ;
514
515 my $db = shift ;
516 my $key = shift ;
517 my $flag = shift ;
f6b705ef 518 my $value = 0 ;
88108326 519 my $origkey = $key ;
520 my $wantarray = wantarray ;
f6b705ef 521 my %values = () ;
88108326 522 my @values = () ;
523 my $counter = 0 ;
f6b705ef 524 my $status = 0 ;
88108326 525
f6b705ef 526 # iterate through the database until either EOF ($status == 0)
527 # or a different key is encountered ($key ne $origkey).
528 for ($status = $db->seq($key, $value, R_CURSOR()) ;
529 $status == 0 and $key eq $origkey ;
530 $status = $db->seq($key, $value, R_NEXT()) ) {
88108326 531
f6b705ef 532 # save the value or count number of matches
533 if ($wantarray) {
534 if ($flag)
535 { ++ $values{$value} }
536 else
537 { push (@values, $value) }
538 }
539 else
540 { ++ $counter }
88108326 541
88108326 542 }
543
f6b705ef 544 return ($wantarray ? ($flag ? %values : @values) : $counter) ;
88108326 545}
546
547
8e07c86e 5481;
549__END__
550
3b35bae3 551=head1 NAME
552
1f70e1ea 553DB_File - Perl5 access to Berkeley DB version 1.x
3b35bae3 554
555=head1 SYNOPSIS
556
bbc7dcd2 557 use DB_File;
558
88108326 559 [$X =] tie %hash, 'DB_File', [$filename, $flags, $mode, $DB_HASH] ;
560 [$X =] tie %hash, 'DB_File', $filename, $flags, $mode, $DB_BTREE ;
561 [$X =] tie @array, 'DB_File', $filename, $flags, $mode, $DB_RECNO ;
760ac839 562
3b35bae3 563 $status = $X->del($key [, $flags]) ;
564 $status = $X->put($key, $value [, $flags]) ;
565 $status = $X->get($key, $value [, $flags]) ;
760ac839 566 $status = $X->seq($key, $value, $flags) ;
3b35bae3 567 $status = $X->sync([$flags]) ;
568 $status = $X->fd ;
760ac839 569
f6b705ef 570 # BTREE only
88108326 571 $count = $X->get_dup($key) ;
572 @list = $X->get_dup($key) ;
573 %list = $X->get_dup($key, 1) ;
6ca2e664 574 $status = $X->find_dup($key, $value) ;
575 $status = $X->del_dup($key, $value) ;
88108326 576
f6b705ef 577 # RECNO only
578 $a = $X->length;
579 $a = $X->pop ;
580 $X->push(list);
581 $a = $X->shift;
582 $X->unshift(list);
c5da4faf 583 @r = $X->splice(offset, length, elements);
f6b705ef 584
cad2e5aa 585 # DBM Filters
586 $old_filter = $db->filter_store_key ( sub { ... } ) ;
587 $old_filter = $db->filter_store_value( sub { ... } ) ;
588 $old_filter = $db->filter_fetch_key ( sub { ... } ) ;
589 $old_filter = $db->filter_fetch_value( sub { ... } ) ;
590
3b35bae3 591 untie %hash ;
592 untie @array ;
593
594=head1 DESCRIPTION
595
8e07c86e 596B<DB_File> is a module which allows Perl programs to make use of the
1f70e1ea 597facilities provided by Berkeley DB version 1.x (if you have a newer
e5021521 598version of DB, see L<Using DB_File with Berkeley DB version 2 or greater).
039d031f 599It is assumed that you have a copy of the Berkeley DB manual pages at
600hand when reading this documentation. The interface defined here
601mirrors the Berkeley DB interface closely.
68dc0745 602
8e07c86e 603Berkeley DB is a C library which provides a consistent interface to a
604number of database formats. B<DB_File> provides an interface to all
605three of the database types currently supported by Berkeley DB.
3b35bae3 606
607The file types are:
608
609=over 5
610
88108326 611=item B<DB_HASH>
3b35bae3 612
88108326 613This database type allows arbitrary key/value pairs to be stored in data
8e07c86e 614files. This is equivalent to the functionality provided by other
615hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though,
616the files created using DB_HASH are not compatible with any of the
617other packages mentioned.
3b35bae3 618
8e07c86e 619A default hashing algorithm, which will be adequate for most
620applications, is built into Berkeley DB. If you do need to use your own
621hashing algorithm it is possible to write your own in Perl and have
622B<DB_File> use it instead.
3b35bae3 623
88108326 624=item B<DB_BTREE>
625
626The btree format allows arbitrary key/value pairs to be stored in a
8e07c86e 627sorted, balanced binary tree.
3b35bae3 628
8e07c86e 629As with the DB_HASH format, it is possible to provide a user defined
630Perl routine to perform the comparison of keys. By default, though, the
631keys are stored in lexical order.
3b35bae3 632
88108326 633=item B<DB_RECNO>
3b35bae3 634
8e07c86e 635DB_RECNO allows both fixed-length and variable-length flat text files
636to be manipulated using the same key/value pair interface as in DB_HASH
637and DB_BTREE. In this case the key will consist of a record (line)
638number.
3b35bae3 639
640=back
641
e5021521 642=head2 Using DB_File with Berkeley DB version 2 or greater
1f70e1ea 643
644Although B<DB_File> is intended to be used with Berkeley DB version 1,
e5021521 645it can also be used with version 2, 3 or 4. In this case the interface is
1f70e1ea 646limited to the functionality provided by Berkeley DB 1.x. Anywhere the
e5021521 647version 2 or greater interface differs, B<DB_File> arranges for it to work
039d031f 648like version 1. This feature allows B<DB_File> scripts that were built
e5021521 649with version 1 to be migrated to version 2 or greater without any changes.
1f70e1ea 650
651If you want to make use of the new features available in Berkeley DB
b90e71be 6522.x or greater, use the Perl module B<BerkeleyDB> instead.
1f70e1ea 653
e5021521 654B<Note:> The database file format has changed multiple times in Berkeley
655DB version 2, 3 and 4. If you cannot recreate your databases, you
656must dump any existing databases with either the C<db_dump> or the
657C<db_dump185> utility that comes with Berkeley DB.
658Once you have rebuilt DB_File to use Berkeley DB version 2 or greater,
659your databases can be recreated using C<db_load>. Refer to the Berkeley DB
1f70e1ea 660documentation for further details.
661
e5021521 662Please read L<"COPYRIGHT"> before using version 2.x or greater of Berkeley
039d031f 663DB with DB_File.
1f70e1ea 664
68dc0745 665=head2 Interface to Berkeley DB
3b35bae3 666
667B<DB_File> allows access to Berkeley DB files using the tie() mechanism
8e07c86e 668in Perl 5 (for full details, see L<perlfunc/tie()>). This facility
669allows B<DB_File> to access Berkeley DB files using either an
670associative array (for DB_HASH & DB_BTREE file types) or an ordinary
671array (for the DB_RECNO file type).
3b35bae3 672
88108326 673In addition to the tie() interface, it is also possible to access most
674of the functions provided in the Berkeley DB API directly.
f6b705ef 675See L<THE API INTERFACE>.
3b35bae3 676
88108326 677=head2 Opening a Berkeley DB Database File
3b35bae3 678
8e07c86e 679Berkeley DB uses the function dbopen() to open or create a database.
f6b705ef 680Here is the C prototype for dbopen():
3b35bae3 681
682 DB*
683 dbopen (const char * file, int flags, int mode,
684 DBTYPE type, const void * openinfo)
685
686The parameter C<type> is an enumeration which specifies which of the 3
687interface methods (DB_HASH, DB_BTREE or DB_RECNO) is to be used.
688Depending on which of these is actually chosen, the final parameter,
689I<openinfo> points to a data structure which allows tailoring of the
690specific interface method.
691
8e07c86e 692This interface is handled slightly differently in B<DB_File>. Here is
88108326 693an equivalent call using B<DB_File>:
3b35bae3 694
88108326 695 tie %array, 'DB_File', $filename, $flags, $mode, $DB_HASH ;
3b35bae3 696
8e07c86e 697The C<filename>, C<flags> and C<mode> parameters are the direct
698equivalent of their dbopen() counterparts. The final parameter $DB_HASH
699performs the function of both the C<type> and C<openinfo> parameters in
700dbopen().
3b35bae3 701
88108326 702In the example above $DB_HASH is actually a pre-defined reference to a
703hash object. B<DB_File> has three of these pre-defined references.
704Apart from $DB_HASH, there is also $DB_BTREE and $DB_RECNO.
3b35bae3 705
8e07c86e 706The keys allowed in each of these pre-defined references is limited to
707the names used in the equivalent C structure. So, for example, the
708$DB_HASH reference will only allow keys called C<bsize>, C<cachesize>,
88108326 709C<ffactor>, C<hash>, C<lorder> and C<nelem>.
710
711To change one of these elements, just assign to it like this:
712
713 $DB_HASH->{'cachesize'} = 10000 ;
714
715The three predefined variables $DB_HASH, $DB_BTREE and $DB_RECNO are
716usually adequate for most applications. If you do need to create extra
717instances of these objects, constructors are available for each file
718type.
719
720Here are examples of the constructors and the valid options available
721for DB_HASH, DB_BTREE and DB_RECNO respectively.
722
723 $a = new DB_File::HASHINFO ;
724 $a->{'bsize'} ;
725 $a->{'cachesize'} ;
726 $a->{'ffactor'};
727 $a->{'hash'} ;
728 $a->{'lorder'} ;
729 $a->{'nelem'} ;
730
731 $b = new DB_File::BTREEINFO ;
732 $b->{'flags'} ;
733 $b->{'cachesize'} ;
734 $b->{'maxkeypage'} ;
735 $b->{'minkeypage'} ;
736 $b->{'psize'} ;
737 $b->{'compare'} ;
738 $b->{'prefix'} ;
739 $b->{'lorder'} ;
740
741 $c = new DB_File::RECNOINFO ;
742 $c->{'bval'} ;
743 $c->{'cachesize'} ;
744 $c->{'psize'} ;
745 $c->{'flags'} ;
746 $c->{'lorder'} ;
747 $c->{'reclen'} ;
748 $c->{'bfname'} ;
749
750The values stored in the hashes above are mostly the direct equivalent
751of their C counterpart. Like their C counterparts, all are set to a
f6b705ef 752default values - that means you don't have to set I<all> of the
88108326 753values when you only want to change one. Here is an example:
754
755 $a = new DB_File::HASHINFO ;
756 $a->{'cachesize'} = 12345 ;
757 tie %y, 'DB_File', "filename", $flags, 0777, $a ;
758
36477c24 759A few of the options need extra discussion here. When used, the C
88108326 760equivalent of the keys C<hash>, C<compare> and C<prefix> store pointers
761to C functions. In B<DB_File> these keys are used to store references
762to Perl subs. Below are templates for each of the subs:
763
764 sub hash
765 {
766 my ($data) = @_ ;
767 ...
768 # return the hash value for $data
769 return $hash ;
770 }
3b35bae3 771
88108326 772 sub compare
773 {
774 my ($key, $key2) = @_ ;
775 ...
776 # return 0 if $key1 eq $key2
777 # -1 if $key1 lt $key2
778 # 1 if $key1 gt $key2
779 return (-1 , 0 or 1) ;
780 }
3b35bae3 781
88108326 782 sub prefix
783 {
784 my ($key, $key2) = @_ ;
785 ...
786 # return number of bytes of $key2 which are
787 # necessary to determine that it is greater than $key1
788 return $bytes ;
789 }
3b35bae3 790
f6b705ef 791See L<Changing the BTREE sort order> for an example of using the
792C<compare> template.
88108326 793
36477c24 794If you are using the DB_RECNO interface and you intend making use of
9a2c4ce3 795C<bval>, you should check out L<The 'bval' Option>.
36477c24 796
88108326 797=head2 Default Parameters
798
799It is possible to omit some or all of the final 4 parameters in the
800call to C<tie> and let them take default values. As DB_HASH is the most
801common file format used, the call:
802
803 tie %A, "DB_File", "filename" ;
804
805is equivalent to:
806
18d2dc8c 807 tie %A, "DB_File", "filename", O_CREAT|O_RDWR, 0666, $DB_HASH ;
88108326 808
809It is also possible to omit the filename parameter as well, so the
810call:
811
812 tie %A, "DB_File" ;
813
814is equivalent to:
815
18d2dc8c 816 tie %A, "DB_File", undef, O_CREAT|O_RDWR, 0666, $DB_HASH ;
88108326 817
f6b705ef 818See L<In Memory Databases> for a discussion on the use of C<undef>
88108326 819in place of a filename.
820
f6b705ef 821=head2 In Memory Databases
822
823Berkeley DB allows the creation of in-memory databases by using NULL
824(that is, a C<(char *)0> in C) in place of the filename. B<DB_File>
825uses C<undef> instead of NULL to provide this functionality.
826
827=head1 DB_HASH
828
829The DB_HASH file format is probably the most commonly used of the three
830file formats that B<DB_File> supports. It is also very straightforward
831to use.
832
68dc0745 833=head2 A Simple Example
f6b705ef 834
835This example shows how to create a database, add key/value pairs to the
836database, delete keys/value pairs and finally how to enumerate the
837contents of the database.
838
3245f058 839 use warnings ;
610ab055 840 use strict ;
f6b705ef 841 use DB_File ;
610ab055 842 use vars qw( %h $k $v ) ;
f6b705ef 843
2c2d71f5 844 unlink "fruit" ;
45a340cb 845 tie %h, "DB_File", "fruit", O_RDWR|O_CREAT, 0666, $DB_HASH
f6b705ef 846 or die "Cannot open file 'fruit': $!\n";
847
848 # Add a few key/value pairs to the file
849 $h{"apple"} = "red" ;
850 $h{"orange"} = "orange" ;
851 $h{"banana"} = "yellow" ;
852 $h{"tomato"} = "red" ;
853
854 # Check for existence of a key
855 print "Banana Exists\n\n" if $h{"banana"} ;
856
857 # Delete a key/value pair.
858 delete $h{"apple"} ;
859
860 # print the contents of the file
861 while (($k, $v) = each %h)
862 { print "$k -> $v\n" }
863
864 untie %h ;
865
866here is the output:
867
868 Banana Exists
bbc7dcd2 869
f6b705ef 870 orange -> orange
871 tomato -> red
872 banana -> yellow
873
874Note that the like ordinary associative arrays, the order of the keys
875retrieved is in an apparently random order.
876
877=head1 DB_BTREE
878
879The DB_BTREE format is useful when you want to store data in a given
880order. By default the keys will be stored in lexical order, but as you
881will see from the example shown in the next section, it is very easy to
882define your own sorting function.
883
884=head2 Changing the BTREE sort order
885
886This script shows how to override the default sorting algorithm that
887BTREE uses. Instead of using the normal lexical ordering, a case
888insensitive compare function will be used.
88108326 889
3245f058 890 use warnings ;
610ab055 891 use strict ;
f6b705ef 892 use DB_File ;
610ab055 893
894 my %h ;
f6b705ef 895
896 sub Compare
897 {
898 my ($key1, $key2) = @_ ;
899 "\L$key1" cmp "\L$key2" ;
900 }
901
902 # specify the Perl sub that will do the comparison
903 $DB_BTREE->{'compare'} = \&Compare ;
904
2c2d71f5 905 unlink "tree" ;
45a340cb 906 tie %h, "DB_File", "tree", O_RDWR|O_CREAT, 0666, $DB_BTREE
f6b705ef 907 or die "Cannot open file 'tree': $!\n" ;
908
909 # Add a key/value pair to the file
910 $h{'Wall'} = 'Larry' ;
911 $h{'Smith'} = 'John' ;
912 $h{'mouse'} = 'mickey' ;
913 $h{'duck'} = 'donald' ;
914
915 # Delete
916 delete $h{"duck"} ;
917
918 # Cycle through the keys printing them in order.
919 # Note it is not necessary to sort the keys as
920 # the btree will have kept them in order automatically.
921 foreach (keys %h)
922 { print "$_\n" }
923
924 untie %h ;
925
926Here is the output from the code above.
927
928 mouse
929 Smith
930 Wall
931
932There are a few point to bear in mind if you want to change the
933ordering in a BTREE database:
934
935=over 5
936
937=item 1.
938
939The new compare function must be specified when you create the database.
940
941=item 2.
942
943You cannot change the ordering once the database has been created. Thus
944you must use the same compare function every time you access the
88108326 945database.
946
39793c41 947=item 3
948
949Duplicate keys are entirely defined by the comparison function.
950In the case-insensitive example above, the keys: 'KEY' and 'key'
951would be considered duplicates, and assigning to the second one
52ffee89 952would overwrite the first. If duplicates are allowed for (with the
39793c41 953R_DUPS flag discussed below), only a single copy of duplicate keys
954is stored in the database --- so (again with example above) assigning
955three values to the keys: 'KEY', 'Key', and 'key' would leave just
956the first key: 'KEY' in the database with three values. For some
957situations this results in information loss, so care should be taken
958to provide fully qualified comparison functions when necessary.
959For example, the above comparison routine could be modified to
960additionally compare case-sensitively if two keys are equal in the
961case insensitive comparison:
962
963 sub compare {
964 my($key1, $key2) = @_;
965 lc $key1 cmp lc $key2 ||
966 $key1 cmp $key2;
967 }
968
969And now you will only have duplicates when the keys themselves
970are truly the same. (note: in versions of the db library prior to
971about November 1996, such duplicate keys were retained so it was
972possible to recover the original keys in sets of keys that
973compared as equal).
974
975
f6b705ef 976=back
977
68dc0745 978=head2 Handling Duplicate Keys
f6b705ef 979
980The BTREE file type optionally allows a single key to be associated
981with an arbitrary number of values. This option is enabled by setting
982the flags element of C<$DB_BTREE> to R_DUP when creating the database.
983
88108326 984There are some difficulties in using the tied hash interface if you
985want to manipulate a BTREE database with duplicate keys. Consider this
986code:
987
3245f058 988 use warnings ;
610ab055 989 use strict ;
88108326 990 use DB_File ;
610ab055 991
992 use vars qw($filename %h ) ;
993
88108326 994 $filename = "tree" ;
995 unlink $filename ;
bbc7dcd2 996
88108326 997 # Enable duplicate records
998 $DB_BTREE->{'flags'} = R_DUP ;
bbc7dcd2 999
45a340cb 1000 tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
88108326 1001 or die "Cannot open $filename: $!\n";
bbc7dcd2 1002
88108326 1003 # Add some key/value pairs to the file
1004 $h{'Wall'} = 'Larry' ;
1005 $h{'Wall'} = 'Brick' ; # Note the duplicate key
f6b705ef 1006 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
88108326 1007 $h{'Smith'} = 'John' ;
1008 $h{'mouse'} = 'mickey' ;
1009
1010 # iterate through the associative array
1011 # and print each key/value pair.
2c2d71f5 1012 foreach (sort keys %h)
88108326 1013 { print "$_ -> $h{$_}\n" }
1014
f6b705ef 1015 untie %h ;
1016
88108326 1017Here is the output:
1018
1019 Smith -> John
1020 Wall -> Larry
1021 Wall -> Larry
f6b705ef 1022 Wall -> Larry
88108326 1023 mouse -> mickey
1024
f6b705ef 1025As you can see 3 records have been successfully created with key C<Wall>
88108326 1026- the only thing is, when they are retrieved from the database they
f6b705ef 1027I<seem> to have the same value, namely C<Larry>. The problem is caused
1028by the way that the associative array interface works. Basically, when
1029the associative array interface is used to fetch the value associated
1030with a given key, it will only ever retrieve the first value.
88108326 1031
1032Although it may not be immediately obvious from the code above, the
1033associative array interface can be used to write values with duplicate
1034keys, but it cannot be used to read them back from the database.
1035
1036The way to get around this problem is to use the Berkeley DB API method
1037called C<seq>. This method allows sequential access to key/value
f6b705ef 1038pairs. See L<THE API INTERFACE> for details of both the C<seq> method
1039and the API in general.
88108326 1040
1041Here is the script above rewritten using the C<seq> API method.
1042
3245f058 1043 use warnings ;
610ab055 1044 use strict ;
88108326 1045 use DB_File ;
bbc7dcd2 1046
610ab055 1047 use vars qw($filename $x %h $status $key $value) ;
1048
88108326 1049 $filename = "tree" ;
1050 unlink $filename ;
bbc7dcd2 1051
88108326 1052 # Enable duplicate records
1053 $DB_BTREE->{'flags'} = R_DUP ;
bbc7dcd2 1054
45a340cb 1055 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
88108326 1056 or die "Cannot open $filename: $!\n";
bbc7dcd2 1057
88108326 1058 # Add some key/value pairs to the file
1059 $h{'Wall'} = 'Larry' ;
1060 $h{'Wall'} = 'Brick' ; # Note the duplicate key
f6b705ef 1061 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
88108326 1062 $h{'Smith'} = 'John' ;
1063 $h{'mouse'} = 'mickey' ;
bbc7dcd2 1064
f6b705ef 1065 # iterate through the btree using seq
88108326 1066 # and print each key/value pair.
610ab055 1067 $key = $value = 0 ;
f6b705ef 1068 for ($status = $x->seq($key, $value, R_FIRST) ;
1069 $status == 0 ;
1070 $status = $x->seq($key, $value, R_NEXT) )
88108326 1071 { print "$key -> $value\n" }
bbc7dcd2 1072
88108326 1073 undef $x ;
1074 untie %h ;
1075
1076that prints:
1077
1078 Smith -> John
1079 Wall -> Brick
f6b705ef 1080 Wall -> Brick
88108326 1081 Wall -> Larry
1082 mouse -> mickey
1083
f6b705ef 1084This time we have got all the key/value pairs, including the multiple
88108326 1085values associated with the key C<Wall>.
1086
6ca2e664 1087To make life easier when dealing with duplicate keys, B<DB_File> comes with
1088a few utility methods.
1089
68dc0745 1090=head2 The get_dup() Method
f6b705ef 1091
6ca2e664 1092The C<get_dup> method assists in
88108326 1093reading duplicate values from BTREE databases. The method can take the
1094following forms:
1095
1096 $count = $x->get_dup($key) ;
1097 @list = $x->get_dup($key) ;
1098 %list = $x->get_dup($key, 1) ;
1099
1100In a scalar context the method returns the number of values associated
1101with the key, C<$key>.
1102
1103In list context, it returns all the values which match C<$key>. Note
f6b705ef 1104that the values will be returned in an apparently random order.
88108326 1105
7a2e2cd6 1106In list context, if the second parameter is present and evaluates
1107TRUE, the method returns an associative array. The keys of the
1108associative array correspond to the values that matched in the BTREE
1109and the values of the array are a count of the number of times that
1110particular value occurred in the BTREE.
88108326 1111
f6b705ef 1112So assuming the database created above, we can use C<get_dup> like
88108326 1113this:
1114
3245f058 1115 use warnings ;
2c2d71f5 1116 use strict ;
1117 use DB_File ;
bbc7dcd2 1118
2c2d71f5 1119 use vars qw($filename $x %h ) ;
1120
1121 $filename = "tree" ;
bbc7dcd2 1122
2c2d71f5 1123 # Enable duplicate records
1124 $DB_BTREE->{'flags'} = R_DUP ;
bbc7dcd2 1125
45a340cb 1126 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
2c2d71f5 1127 or die "Cannot open $filename: $!\n";
1128
610ab055 1129 my $cnt = $x->get_dup("Wall") ;
88108326 1130 print "Wall occurred $cnt times\n" ;
1131
610ab055 1132 my %hash = $x->get_dup("Wall", 1) ;
88108326 1133 print "Larry is there\n" if $hash{'Larry'} ;
f6b705ef 1134 print "There are $hash{'Brick'} Brick Walls\n" ;
88108326 1135
2c2d71f5 1136 my @list = sort $x->get_dup("Wall") ;
88108326 1137 print "Wall => [@list]\n" ;
1138
f6b705ef 1139 @list = $x->get_dup("Smith") ;
88108326 1140 print "Smith => [@list]\n" ;
bbc7dcd2 1141
f6b705ef 1142 @list = $x->get_dup("Dog") ;
88108326 1143 print "Dog => [@list]\n" ;
1144
1145
1146and it will print:
1147
f6b705ef 1148 Wall occurred 3 times
88108326 1149 Larry is there
f6b705ef 1150 There are 2 Brick Walls
1151 Wall => [Brick Brick Larry]
88108326 1152 Smith => [John]
1153 Dog => []
3b35bae3 1154
6ca2e664 1155=head2 The find_dup() Method
1156
1157 $status = $X->find_dup($key, $value) ;
1158
b90e71be 1159This method checks for the existence of a specific key/value pair. If the
6ca2e664 1160pair exists, the cursor is left pointing to the pair and the method
1161returns 0. Otherwise the method returns a non-zero value.
1162
1163Assuming the database from the previous example:
1164
3245f058 1165 use warnings ;
6ca2e664 1166 use strict ;
1167 use DB_File ;
bbc7dcd2 1168
6ca2e664 1169 use vars qw($filename $x %h $found) ;
1170
1171 my $filename = "tree" ;
bbc7dcd2 1172
6ca2e664 1173 # Enable duplicate records
1174 $DB_BTREE->{'flags'} = R_DUP ;
bbc7dcd2 1175
45a340cb 1176 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
6ca2e664 1177 or die "Cannot open $filename: $!\n";
1178
1179 $found = ( $x->find_dup("Wall", "Larry") == 0 ? "" : "not") ;
1180 print "Larry Wall is $found there\n" ;
bbc7dcd2 1181
6ca2e664 1182 $found = ( $x->find_dup("Wall", "Harry") == 0 ? "" : "not") ;
1183 print "Harry Wall is $found there\n" ;
bbc7dcd2 1184
6ca2e664 1185 undef $x ;
1186 untie %h ;
1187
1188prints this
1189
2c2d71f5 1190 Larry Wall is there
6ca2e664 1191 Harry Wall is not there
1192
1193
1194=head2 The del_dup() Method
1195
1196 $status = $X->del_dup($key, $value) ;
1197
1198This method deletes a specific key/value pair. It returns
11990 if they exist and have been deleted successfully.
1200Otherwise the method returns a non-zero value.
1201
b90e71be 1202Again assuming the existence of the C<tree> database
6ca2e664 1203
3245f058 1204 use warnings ;
6ca2e664 1205 use strict ;
1206 use DB_File ;
bbc7dcd2 1207
6ca2e664 1208 use vars qw($filename $x %h $found) ;
1209
1210 my $filename = "tree" ;
bbc7dcd2 1211
6ca2e664 1212 # Enable duplicate records
1213 $DB_BTREE->{'flags'} = R_DUP ;
bbc7dcd2 1214
45a340cb 1215 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
6ca2e664 1216 or die "Cannot open $filename: $!\n";
1217
1218 $x->del_dup("Wall", "Larry") ;
1219
1220 $found = ( $x->find_dup("Wall", "Larry") == 0 ? "" : "not") ;
1221 print "Larry Wall is $found there\n" ;
bbc7dcd2 1222
6ca2e664 1223 undef $x ;
1224 untie %h ;
1225
1226prints this
1227
1228 Larry Wall is not there
1229
f6b705ef 1230=head2 Matching Partial Keys
1231
1232The BTREE interface has a feature which allows partial keys to be
1233matched. This functionality is I<only> available when the C<seq> method
1234is used along with the R_CURSOR flag.
1235
1236 $x->seq($key, $value, R_CURSOR) ;
1237
1238Here is the relevant quote from the dbopen man page where it defines
1239the use of the R_CURSOR flag with seq:
1240
f6b705ef 1241 Note, for the DB_BTREE access method, the returned key is not
1242 necessarily an exact match for the specified key. The returned key
1243 is the smallest key greater than or equal to the specified key,
1244 permitting partial key matches and range searches.
1245
f6b705ef 1246In the example script below, the C<match> sub uses this feature to find
1247and print the first matching key/value pair given a partial key.
1248
3245f058 1249 use warnings ;
610ab055 1250 use strict ;
f6b705ef 1251 use DB_File ;
1252 use Fcntl ;
610ab055 1253
1254 use vars qw($filename $x %h $st $key $value) ;
f6b705ef 1255
1256 sub match
1257 {
1258 my $key = shift ;
610ab055 1259 my $value = 0;
f6b705ef 1260 my $orig_key = $key ;
1261 $x->seq($key, $value, R_CURSOR) ;
1262 print "$orig_key\t-> $key\t-> $value\n" ;
1263 }
1264
1265 $filename = "tree" ;
1266 unlink $filename ;
1267
45a340cb 1268 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
f6b705ef 1269 or die "Cannot open $filename: $!\n";
bbc7dcd2 1270
f6b705ef 1271 # Add some key/value pairs to the file
1272 $h{'mouse'} = 'mickey' ;
1273 $h{'Wall'} = 'Larry' ;
1274 $h{'Walls'} = 'Brick' ;
1275 $h{'Smith'} = 'John' ;
bbc7dcd2 1276
f6b705ef 1277
610ab055 1278 $key = $value = 0 ;
f6b705ef 1279 print "IN ORDER\n" ;
1280 for ($st = $x->seq($key, $value, R_FIRST) ;
1281 $st == 0 ;
1282 $st = $x->seq($key, $value, R_NEXT) )
bbc7dcd2 1283
2c2d71f5 1284 { print "$key -> $value\n" }
bbc7dcd2 1285
f6b705ef 1286 print "\nPARTIAL MATCH\n" ;
1287
1288 match "Wa" ;
1289 match "A" ;
1290 match "a" ;
1291
1292 undef $x ;
1293 untie %h ;
1294
1295Here is the output:
1296
1297 IN ORDER
1298 Smith -> John
1299 Wall -> Larry
1300 Walls -> Brick
1301 mouse -> mickey
1302
1303 PARTIAL MATCH
1304 Wa -> Wall -> Larry
1305 A -> Smith -> John
1306 a -> mouse -> mickey
1307
1308=head1 DB_RECNO
1309
1310DB_RECNO provides an interface to flat text files. Both variable and
1311fixed length records are supported.
3b35bae3 1312
6ca2e664 1313In order to make RECNO more compatible with Perl, the array offset for
88108326 1314all RECNO arrays begins at 0 rather than 1 as in Berkeley DB.
3b35bae3 1315
88108326 1316As with normal Perl arrays, a RECNO array can be accessed using
1317negative indexes. The index -1 refers to the last element of the array,
1318-2 the second last, and so on. Attempting to access an element before
1319the start of the array will raise a fatal run-time error.
3b35bae3 1320
68dc0745 1321=head2 The 'bval' Option
36477c24 1322
1323The operation of the bval option warrants some discussion. Here is the
1324definition of bval from the Berkeley DB 1.85 recno manual page:
1325
1326 The delimiting byte to be used to mark the end of a
1327 record for variable-length records, and the pad charac-
1328 ter for fixed-length records. If no value is speci-
1329 fied, newlines (``\n'') are used to mark the end of
1330 variable-length records and fixed-length records are
1331 padded with spaces.
1332
1333The second sentence is wrong. In actual fact bval will only default to
1334C<"\n"> when the openinfo parameter in dbopen is NULL. If a non-NULL
1335openinfo parameter is used at all, the value that happens to be in bval
1336will be used. That means you always have to specify bval when making
1337use of any of the options in the openinfo parameter. This documentation
1338error will be fixed in the next release of Berkeley DB.
1339
1340That clarifies the situation with regards Berkeley DB itself. What
1341about B<DB_File>? Well, the behavior defined in the quote above is
6ca2e664 1342quite useful, so B<DB_File> conforms to it.
36477c24 1343
1344That means that you can specify other options (e.g. cachesize) and
1345still have bval default to C<"\n"> for variable length records, and
1346space for fixed length records.
1347
c5da4faf 1348Also note that the bval option only allows you to specify a single byte
1349as a delimeter.
1350
f6b705ef 1351=head2 A Simple Example
3b35bae3 1352
6ca2e664 1353Here is a simple example that uses RECNO (if you are using a version
1354of Perl earlier than 5.004_57 this example won't work -- see
1355L<Extra RECNO Methods> for a workaround).
f6b705ef 1356
3245f058 1357 use warnings ;
610ab055 1358 use strict ;
f6b705ef 1359 use DB_File ;
f6b705ef 1360
2c2d71f5 1361 my $filename = "text" ;
1362 unlink $filename ;
1363
610ab055 1364 my @h ;
45a340cb 1365 tie @h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_RECNO
f6b705ef 1366 or die "Cannot open file 'text': $!\n" ;
1367
1368 # Add a few key/value pairs to the file
1369 $h[0] = "orange" ;
1370 $h[1] = "blue" ;
1371 $h[2] = "yellow" ;
1372
6ca2e664 1373 push @h, "green", "black" ;
1374
1375 my $elements = scalar @h ;
1376 print "The array contains $elements entries\n" ;
1377
1378 my $last = pop @h ;
1379 print "popped $last\n" ;
1380
1381 unshift @h, "white" ;
1382 my $first = shift @h ;
1383 print "shifted $first\n" ;
1384
f6b705ef 1385 # Check for existence of a key
1386 print "Element 1 Exists with value $h[1]\n" if $h[1] ;
1387
1388 # use a negative index
1389 print "The last element is $h[-1]\n" ;
1390 print "The 2nd last element is $h[-2]\n" ;
1391
1392 untie @h ;
3b35bae3 1393
f6b705ef 1394Here is the output from the script:
1395
6ca2e664 1396 The array contains 5 entries
1397 popped black
2c2d71f5 1398 shifted white
f6b705ef 1399 Element 1 Exists with value blue
6ca2e664 1400 The last element is green
1401 The 2nd last element is yellow
f6b705ef 1402
6ca2e664 1403=head2 Extra RECNO Methods
f6b705ef 1404
045291aa 1405If you are using a version of Perl earlier than 5.004_57, the tied
6ca2e664 1406array interface is quite limited. In the example script above
1407C<push>, C<pop>, C<shift>, C<unshift>
1408or determining the array length will not work with a tied array.
045291aa 1409
1410To make the interface more useful for older versions of Perl, a number
1411of methods are supplied with B<DB_File> to simulate the missing array
1412operations. All these methods are accessed via the object returned from
1413the tie call.
f6b705ef 1414
1415Here are the methods:
1416
1417=over 5
3b35bae3 1418
f6b705ef 1419=item B<$X-E<gt>push(list) ;>
1420
1421Pushes the elements of C<list> to the end of the array.
1422
1423=item B<$value = $X-E<gt>pop ;>
1424
1425Removes and returns the last element of the array.
1426
1427=item B<$X-E<gt>shift>
1428
1429Removes and returns the first element of the array.
1430
1431=item B<$X-E<gt>unshift(list) ;>
1432
1433Pushes the elements of C<list> to the start of the array.
1434
1435=item B<$X-E<gt>length>
1436
1437Returns the number of elements in the array.
1438
c5da4faf 1439=item B<$X-E<gt>splice(offset, length, elements);>
1440
1441Returns a splice of the the array.
1442
f6b705ef 1443=back
1444
1445=head2 Another Example
1446
1447Here is a more complete example that makes use of some of the methods
1448described above. It also makes use of the API interface directly (see
1449L<THE API INTERFACE>).
1450
3245f058 1451 use warnings ;
f6b705ef 1452 use strict ;
1453 use vars qw(@h $H $file $i) ;
1454 use DB_File ;
1455 use Fcntl ;
bbc7dcd2 1456
f6b705ef 1457 $file = "text" ;
1458
1459 unlink $file ;
1460
45a340cb 1461 $H = tie @h, "DB_File", $file, O_RDWR|O_CREAT, 0666, $DB_RECNO
f6b705ef 1462 or die "Cannot open file $file: $!\n" ;
bbc7dcd2 1463
f6b705ef 1464 # first create a text file to play with
1465 $h[0] = "zero" ;
1466 $h[1] = "one" ;
1467 $h[2] = "two" ;
1468 $h[3] = "three" ;
1469 $h[4] = "four" ;
1470
bbc7dcd2 1471
f6b705ef 1472 # Print the records in order.
1473 #
1474 # The length method is needed here because evaluating a tied
1475 # array in a scalar context does not return the number of
1476 # elements in the array.
1477
1478 print "\nORIGINAL\n" ;
1479 foreach $i (0 .. $H->length - 1) {
1480 print "$i: $h[$i]\n" ;
1481 }
1482
1483 # use the push & pop methods
1484 $a = $H->pop ;
1485 $H->push("last") ;
1486 print "\nThe last record was [$a]\n" ;
1487
1488 # and the shift & unshift methods
1489 $a = $H->shift ;
1490 $H->unshift("first") ;
1491 print "The first record was [$a]\n" ;
1492
1493 # Use the API to add a new record after record 2.
1494 $i = 2 ;
1495 $H->put($i, "Newbie", R_IAFTER) ;
1496
1497 # and a new record before record 1.
1498 $i = 1 ;
1499 $H->put($i, "New One", R_IBEFORE) ;
1500
1501 # delete record 3
1502 $H->del(3) ;
1503
1504 # now print the records in reverse order
1505 print "\nREVERSE\n" ;
1506 for ($i = $H->length - 1 ; $i >= 0 ; -- $i)
1507 { print "$i: $h[$i]\n" }
1508
1509 # same again, but use the API functions instead
1510 print "\nREVERSE again\n" ;
610ab055 1511 my ($s, $k, $v) = (0, 0, 0) ;
f6b705ef 1512 for ($s = $H->seq($k, $v, R_LAST) ;
1513 $s == 0 ;
1514 $s = $H->seq($k, $v, R_PREV))
1515 { print "$k: $v\n" }
1516
1517 undef $H ;
1518 untie @h ;
1519
1520and this is what it outputs:
1521
1522 ORIGINAL
1523 0: zero
1524 1: one
1525 2: two
1526 3: three
1527 4: four
1528
1529 The last record was [four]
1530 The first record was [zero]
1531
1532 REVERSE
1533 5: last
1534 4: three
1535 3: Newbie
1536 2: one
1537 1: New One
1538 0: first
1539
1540 REVERSE again
1541 5: last
1542 4: three
1543 3: Newbie
1544 2: one
1545 1: New One
1546 0: first
1547
1548Notes:
1549
1550=over 5
1551
1552=item 1.
1553
1554Rather than iterating through the array, C<@h> like this:
1555
1556 foreach $i (@h)
1557
1558it is necessary to use either this:
1559
1560 foreach $i (0 .. $H->length - 1)
1561
1562or this:
1563
1564 for ($a = $H->get($k, $v, R_FIRST) ;
1565 $a == 0 ;
1566 $a = $H->get($k, $v, R_NEXT) )
1567
1568=item 2.
1569
1570Notice that both times the C<put> method was used the record index was
1571specified using a variable, C<$i>, rather than the literal value
1572itself. This is because C<put> will return the record number of the
1573inserted line via that parameter.
1574
1575=back
1576
1577=head1 THE API INTERFACE
3b35bae3 1578
1579As well as accessing Berkeley DB using a tied hash or array, it is also
88108326 1580possible to make direct use of most of the API functions defined in the
8e07c86e 1581Berkeley DB documentation.
3b35bae3 1582
88108326 1583To do this you need to store a copy of the object returned from the tie.
3b35bae3 1584
88108326 1585 $db = tie %hash, "DB_File", "filename" ;
3b35bae3 1586
8e07c86e 1587Once you have done that, you can access the Berkeley DB API functions
88108326 1588as B<DB_File> methods directly like this:
3b35bae3 1589
1590 $db->put($key, $value, R_NOOVERWRITE) ;
1591
88108326 1592B<Important:> If you have saved a copy of the object returned from
1593C<tie>, the underlying database file will I<not> be closed until both
1594the tied variable is untied and all copies of the saved object are
610ab055 1595destroyed.
88108326 1596
1597 use DB_File ;
1598 $db = tie %hash, "DB_File", "filename"
1599 or die "Cannot tie filename: $!" ;
1600 ...
1601 undef $db ;
1602 untie %hash ;
1603
9a2c4ce3 1604See L<The untie() Gotcha> for more details.
778183f3 1605
88108326 1606All the functions defined in L<dbopen> are available except for
1607close() and dbopen() itself. The B<DB_File> method interface to the
1608supported functions have been implemented to mirror the way Berkeley DB
1609works whenever possible. In particular note that:
1610
1611=over 5
1612
1613=item *
1614
1615The methods return a status value. All return 0 on success.
1616All return -1 to signify an error and set C<$!> to the exact
1617error code. The return code 1 generally (but not always) means that the
1618key specified did not exist in the database.
1619
1620Other return codes are defined. See below and in the Berkeley DB
1621documentation for details. The Berkeley DB documentation should be used
1622as the definitive source.
1623
1624=item *
3b35bae3 1625
88108326 1626Whenever a Berkeley DB function returns data via one of its parameters,
1627the equivalent B<DB_File> method does exactly the same.
3b35bae3 1628
88108326 1629=item *
1630
1631If you are careful, it is possible to mix API calls with the tied
1632hash/array interface in the same piece of code. Although only a few of
1633the methods used to implement the tied interface currently make use of
1634the cursor, you should always assume that the cursor has been changed
1635any time the tied hash/array interface is used. As an example, this
1636code will probably not do what you expect:
1637
1638 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1639 or die "Cannot tie $filename: $!" ;
1640
1641 # Get the first key/value pair and set the cursor
1642 $X->seq($key, $value, R_FIRST) ;
1643
1644 # this line will modify the cursor
1645 $count = scalar keys %x ;
1646
1647 # Get the second key/value pair.
1648 # oops, it didn't, it got the last key/value pair!
1649 $X->seq($key, $value, R_NEXT) ;
1650
1651The code above can be rearranged to get around the problem, like this:
1652
1653 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1654 or die "Cannot tie $filename: $!" ;
1655
1656 # this line will modify the cursor
1657 $count = scalar keys %x ;
1658
1659 # Get the first key/value pair and set the cursor
1660 $X->seq($key, $value, R_FIRST) ;
1661
1662 # Get the second key/value pair.
1663 # worked this time.
1664 $X->seq($key, $value, R_NEXT) ;
1665
1666=back
1667
1668All the constants defined in L<dbopen> for use in the flags parameters
1669in the methods defined below are also available. Refer to the Berkeley
1670DB documentation for the precise meaning of the flags values.
1671
1672Below is a list of the methods available.
3b35bae3 1673
1674=over 5
1675
f6b705ef 1676=item B<$status = $X-E<gt>get($key, $value [, $flags]) ;>
88108326 1677
1678Given a key (C<$key>) this method reads the value associated with it
1679from the database. The value read from the database is returned in the
1680C<$value> parameter.
3b35bae3 1681
88108326 1682If the key does not exist the method returns 1.
3b35bae3 1683
88108326 1684No flags are currently defined for this method.
3b35bae3 1685
f6b705ef 1686=item B<$status = $X-E<gt>put($key, $value [, $flags]) ;>
3b35bae3 1687
88108326 1688Stores the key/value pair in the database.
1689
1690If you use either the R_IAFTER or R_IBEFORE flags, the C<$key> parameter
8e07c86e 1691will have the record number of the inserted key/value pair set.
3b35bae3 1692
88108326 1693Valid flags are R_CURSOR, R_IAFTER, R_IBEFORE, R_NOOVERWRITE and
1694R_SETCURSOR.
1695
f6b705ef 1696=item B<$status = $X-E<gt>del($key [, $flags]) ;>
3b35bae3 1697
88108326 1698Removes all key/value pairs with key C<$key> from the database.
3b35bae3 1699
88108326 1700A return code of 1 means that the requested key was not in the
1701database.
3b35bae3 1702
88108326 1703R_CURSOR is the only valid flag at present.
3b35bae3 1704
f6b705ef 1705=item B<$status = $X-E<gt>fd ;>
3b35bae3 1706
88108326 1707Returns the file descriptor for the underlying database.
3b35bae3 1708
b90e71be 1709See L<Locking: The Trouble with fd> for an explanation for why you should
1710not use C<fd> to lock your database.
3b35bae3 1711
f6b705ef 1712=item B<$status = $X-E<gt>seq($key, $value, $flags) ;>
3b35bae3 1713
88108326 1714This interface allows sequential retrieval from the database. See
1715L<dbopen> for full details.
1716
1717Both the C<$key> and C<$value> parameters will be set to the key/value
1718pair read from the database.
1719
1720The flags parameter is mandatory. The valid flag values are R_CURSOR,
1721R_FIRST, R_LAST, R_NEXT and R_PREV.
1722
f6b705ef 1723=item B<$status = $X-E<gt>sync([$flags]) ;>
88108326 1724
1725Flushes any cached buffers to disk.
1726
1727R_RECNOSYNC is the only valid flag at present.
3b35bae3 1728
1729=back
1730
cad2e5aa 1731=head1 DBM FILTERS
1732
1733A DBM Filter is a piece of code that is be used when you I<always>
1734want to make the same transformation to all keys and/or values in a
1735DBM database.
1736
1737There are four methods associated with DBM Filters. All work identically,
1738and each is used to install (or uninstall) a single DBM Filter. Each
1739expects a single parameter, namely a reference to a sub. The only
1740difference between them is the place that the filter is installed.
1741
1742To summarise:
1743
1744=over 5
1745
1746=item B<filter_store_key>
1747
1748If a filter has been installed with this method, it will be invoked
1749every time you write a key to a DBM database.
1750
1751=item B<filter_store_value>
1752
1753If a filter has been installed with this method, it will be invoked
1754every time you write a value to a DBM database.
1755
1756
1757=item B<filter_fetch_key>
1758
1759If a filter has been installed with this method, it will be invoked
1760every time you read a key from a DBM database.
1761
1762=item B<filter_fetch_value>
1763
1764If a filter has been installed with this method, it will be invoked
1765every time you read a value from a DBM database.
1766
1767=back
1768
1769You can use any combination of the methods, from none, to all four.
1770
1771All filter methods return the existing filter, if present, or C<undef>
1772in not.
1773
1774To delete a filter pass C<undef> to it.
1775
1776=head2 The Filter
1777
1778When each filter is called by Perl, a local copy of C<$_> will contain
1779the key or value to be filtered. Filtering is achieved by modifying
1780the contents of C<$_>. The return code from the filter is ignored.
1781
1782=head2 An Example -- the NULL termination problem.
1783
1784Consider the following scenario. You have a DBM database
1785that you need to share with a third-party C application. The C application
1786assumes that I<all> keys and values are NULL terminated. Unfortunately
1787when Perl writes to DBM databases it doesn't use NULL termination, so
1788your Perl application will have to manage NULL termination itself. When
1789you write to the database you will have to use something like this:
1790
1791 $hash{"$key\0"} = "$value\0" ;
1792
1793Similarly the NULL needs to be taken into account when you are considering
1794the length of existing keys/values.
1795
1796It would be much better if you could ignore the NULL terminations issue
1797in the main application code and have a mechanism that automatically
1798added the terminating NULL to all keys and values whenever you write to
1799the database and have them removed when you read from the database. As I'm
1800sure you have already guessed, this is a problem that DBM Filters can
1801fix very easily.
1802
3245f058 1803 use warnings ;
cad2e5aa 1804 use strict ;
1805 use DB_File ;
1806
1807 my %hash ;
1808 my $filename = "/tmp/filt" ;
1809 unlink $filename ;
1810
1811 my $db = tie %hash, 'DB_File', $filename, O_CREAT|O_RDWR, 0666, $DB_HASH
1812 or die "Cannot open $filename: $!\n" ;
1813
1814 # Install DBM Filters
1815 $db->filter_fetch_key ( sub { s/\0$// } ) ;
1816 $db->filter_store_key ( sub { $_ .= "\0" } ) ;
1817 $db->filter_fetch_value( sub { s/\0$// } ) ;
1818 $db->filter_store_value( sub { $_ .= "\0" } ) ;
1819
1820 $hash{"abc"} = "def" ;
1821 my $a = $hash{"ABC"} ;
1822 # ...
1823 undef $db ;
1824 untie %hash ;
1825
1826Hopefully the contents of each of the filters should be
1827self-explanatory. Both "fetch" filters remove the terminating NULL,
1828and both "store" filters add a terminating NULL.
1829
1830
1831=head2 Another Example -- Key is a C int.
1832
1833Here is another real-life example. By default, whenever Perl writes to
1834a DBM database it always writes the key and value as strings. So when
1835you use this:
1836
1837 $hash{12345} = "soemthing" ;
1838
1839the key 12345 will get stored in the DBM database as the 5 byte string
1840"12345". If you actually want the key to be stored in the DBM database
1841as a C int, you will have to use C<pack> when writing, and C<unpack>
1842when reading.
1843
1844Here is a DBM Filter that does it:
1845
3245f058 1846 use warnings ;
cad2e5aa 1847 use strict ;
1848 use DB_File ;
1849 my %hash ;
1850 my $filename = "/tmp/filt" ;
1851 unlink $filename ;
1852
1853
1854 my $db = tie %hash, 'DB_File', $filename, O_CREAT|O_RDWR, 0666, $DB_HASH
1855 or die "Cannot open $filename: $!\n" ;
1856
1857 $db->filter_fetch_key ( sub { $_ = unpack("i", $_) } ) ;
1858 $db->filter_store_key ( sub { $_ = pack ("i", $_) } ) ;
1859 $hash{123} = "def" ;
1860 # ...
1861 undef $db ;
1862 untie %hash ;
1863
1864This time only two filters have been used -- we only need to manipulate
1865the contents of the key, so it wasn't necessary to install any value
1866filters.
1867
f6b705ef 1868=head1 HINTS AND TIPS
3b35bae3 1869
3b35bae3 1870
b90e71be 1871=head2 Locking: The Trouble with fd
3b35bae3 1872
b90e71be 1873Until version 1.72 of this module, the recommended technique for locking
1874B<DB_File> databases was to flock the filehandle returned from the "fd"
1875function. Unfortunately this technique has been shown to be fundamentally
1876flawed (Kudos to David Harris for tracking this down). Use it at your own
1877peril!
3b35bae3 1878
b90e71be 1879The locking technique went like this.
cb1a09d0 1880
45a340cb 1881 $db = tie(%db, 'DB_File', '/tmp/foo.db', O_CREAT|O_RDWR, 0666)
b90e71be 1882 || die "dbcreat /tmp/foo.db $!";
1883 $fd = $db->fd;
1884 open(DB_FH, "+<&=$fd") || die "dup $!";
1885 flock (DB_FH, LOCK_EX) || die "flock: $!";
1886 ...
1887 $db{"Tom"} = "Jerry" ;
1888 ...
1889 flock(DB_FH, LOCK_UN);
1890 undef $db;
1891 untie %db;
1892 close(DB_FH);
cb1a09d0 1893
b90e71be 1894In simple terms, this is what happens:
cb1a09d0 1895
b90e71be 1896=over 5
cb1a09d0 1897
b90e71be 1898=item 1.
cb1a09d0 1899
b90e71be 1900Use "tie" to open the database.
cb1a09d0 1901
b90e71be 1902=item 2.
cb1a09d0 1903
b90e71be 1904Lock the database with fd & flock.
cb1a09d0 1905
b90e71be 1906=item 3.
cb1a09d0 1907
b90e71be 1908Read & Write to the database.
cb1a09d0 1909
b90e71be 1910=item 4.
cb1a09d0 1911
b90e71be 1912Unlock and close the database.
cb1a09d0 1913
b90e71be 1914=back
1915
1916Here is the crux of the problem. A side-effect of opening the B<DB_File>
1917database in step 2 is that an initial block from the database will get
1918read from disk and cached in memory.
1919
1920To see why this is a problem, consider what can happen when two processes,
1921say "A" and "B", both want to update the same B<DB_File> database
1922using the locking steps outlined above. Assume process "A" has already
1923opened the database and has a write lock, but it hasn't actually updated
1924the database yet (it has finished step 2, but not started step 3 yet). Now
1925process "B" tries to open the same database - step 1 will succeed,
1926but it will block on step 2 until process "A" releases the lock. The
1927important thing to notice here is that at this point in time both
1928processes will have cached identical initial blocks from the database.
1929
1930Now process "A" updates the database and happens to change some of the
1931data held in the initial buffer. Process "A" terminates, flushing
1932all cached data to disk and releasing the database lock. At this point
1933the database on disk will correctly reflect the changes made by process
1934"A".
1935
1936With the lock released, process "B" can now continue. It also updates the
1937database and unfortunately it too modifies the data that was in its
1938initial buffer. Once that data gets flushed to disk it will overwrite
1939some/all of the changes process "A" made to the database.
1940
1941The result of this scenario is at best a database that doesn't contain
1942what you expect. At worst the database will corrupt.
1943
1944The above won't happen every time competing process update the same
1945B<DB_File> database, but it does illustrate why the technique should
1946not be used.
1947
1948=head2 Safe ways to lock a database
1949
1950Starting with version 2.x, Berkeley DB has internal support for locking.
1951The companion module to this one, B<BerkeleyDB>, provides an interface
1952to this locking functionality. If you are serious about locking
1953Berkeley DB databases, I strongly recommend using B<BerkeleyDB>.
1954
1955If using B<BerkeleyDB> isn't an option, there are a number of modules
1956available on CPAN that can be used to implement locking. Each one
1957implements locking differently and has different goals in mind. It is
1958therefore worth knowing the difference, so that you can pick the right
1959one for your application. Here are the three locking wrappers:
1960
1961=over 5
1962
1963=item B<Tie::DB_Lock>
1964
1965A B<DB_File> wrapper which creates copies of the database file for
1966read access, so that you have a kind of a multiversioning concurrent read
1967system. However, updates are still serial. Use for databases where reads
1968may be lengthy and consistency problems may occur.
1969
1970=item B<Tie::DB_LockFile>
1971
1972A B<DB_File> wrapper that has the ability to lock and unlock the database
1973while it is being used. Avoids the tie-before-flock problem by simply
1974re-tie-ing the database when you get or drop a lock. Because of the
1975flexibility in dropping and re-acquiring the lock in the middle of a
1976session, this can be massaged into a system that will work with long
1977updates and/or reads if the application follows the hints in the POD
1978documentation.
1979
1980=item B<DB_File::Lock>
1981
1982An extremely lightweight B<DB_File> wrapper that simply flocks a lockfile
1983before tie-ing the database and drops the lock after the untie. Allows
1984one to use the same lockfile for multiple databases to avoid deadlock
1985problems, if desired. Use for databases where updates are reads are
1986quick and simple flock locking semantics are enough.
1987
1988=back
cb1a09d0 1989
68dc0745 1990=head2 Sharing Databases With C Applications
f6b705ef 1991
1992There is no technical reason why a Berkeley DB database cannot be
1993shared by both a Perl and a C application.
1994
1995The vast majority of problems that are reported in this area boil down
1996to the fact that C strings are NULL terminated, whilst Perl strings are
cad2e5aa 1997not. See L<DBM FILTERS> for a generic way to work around this problem.
f6b705ef 1998
1999Here is a real example. Netscape 2.0 keeps a record of the locations you
2000visit along with the time you last visited them in a DB_HASH database.
2001This is usually stored in the file F<~/.netscape/history.db>. The key
2002field in the database is the location string and the value field is the
2003time the location was last visited stored as a 4 byte binary value.
2004
2005If you haven't already guessed, the location string is stored with a
2006terminating NULL. This means you need to be careful when accessing the
2007database.
2008
2009Here is a snippet of code that is loosely based on Tom Christiansen's
2010I<ggh> script (available from your nearest CPAN archive in
2011F<authors/id/TOMC/scripts/nshist.gz>).
2012
3245f058 2013 use warnings ;
610ab055 2014 use strict ;
f6b705ef 2015 use DB_File ;
2016 use Fcntl ;
f6b705ef 2017
610ab055 2018 use vars qw( $dotdir $HISTORY %hist_db $href $binary_time $date ) ;
f6b705ef 2019 $dotdir = $ENV{HOME} || $ENV{LOGNAME};
2020
2021 $HISTORY = "$dotdir/.netscape/history.db";
2022
2023 tie %hist_db, 'DB_File', $HISTORY
2024 or die "Cannot open $HISTORY: $!\n" ;;
2025
2026 # Dump the complete database
2027 while ( ($href, $binary_time) = each %hist_db ) {
2028
2029 # remove the terminating NULL
2030 $href =~ s/\x00$// ;
2031
2032 # convert the binary time into a user friendly string
2033 $date = localtime unpack("V", $binary_time);
2034 print "$date $href\n" ;
2035 }
2036
2037 # check for the existence of a specific key
2038 # remember to add the NULL
2039 if ( $binary_time = $hist_db{"http://mox.perl.com/\x00"} ) {
2040 $date = localtime unpack("V", $binary_time) ;
2041 print "Last visited mox.perl.com on $date\n" ;
2042 }
2043 else {
2044 print "Never visited mox.perl.com\n"
2045 }
2046
2047 untie %hist_db ;
2048
68dc0745 2049=head2 The untie() Gotcha
778183f3 2050
7a2e2cd6 2051If you make use of the Berkeley DB API, it is I<very> strongly
68dc0745 2052recommended that you read L<perltie/The untie Gotcha>.
778183f3 2053
2054Even if you don't currently make use of the API interface, it is still
2055worth reading it.
2056
2057Here is an example which illustrates the problem from a B<DB_File>
2058perspective:
2059
2060 use DB_File ;
2061 use Fcntl ;
2062
2063 my %x ;
2064 my $X ;
2065
2066 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_TRUNC
2067 or die "Cannot tie first time: $!" ;
2068
2069 $x{123} = 456 ;
2070
2071 untie %x ;
2072
2073 tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
2074 or die "Cannot tie second time: $!" ;
2075
2076 untie %x ;
2077
2078When run, the script will produce this error message:
2079
2080 Cannot tie second time: Invalid argument at bad.file line 14.
2081
2082Although the error message above refers to the second tie() statement
2083in the script, the source of the problem is really with the untie()
2084statement that precedes it.
2085
2086Having read L<perltie> you will probably have already guessed that the
2087error is caused by the extra copy of the tied object stored in C<$X>.
2088If you haven't, then the problem boils down to the fact that the
2089B<DB_File> destructor, DESTROY, will not be called until I<all>
2090references to the tied object are destroyed. Both the tied variable,
2091C<%x>, and C<$X> above hold a reference to the object. The call to
2092untie() will destroy the first, but C<$X> still holds a valid
2093reference, so the destructor will not get called and the database file
2094F<tst.fil> will remain open. The fact that Berkeley DB then reports the
b90e71be 2095attempt to open a database that is already open via the catch-all
778183f3 2096"Invalid argument" doesn't help.
2097
2098If you run the script with the C<-w> flag the error message becomes:
2099
2100 untie attempted while 1 inner references still exist at bad.file line 12.
2101 Cannot tie second time: Invalid argument at bad.file line 14.
2102
2103which pinpoints the real problem. Finally the script can now be
2104modified to fix the original problem by destroying the API object
2105before the untie:
2106
2107 ...
2108 $x{123} = 456 ;
2109
2110 undef $X ;
2111 untie %x ;
2112
2113 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
2114 ...
2115
f6b705ef 2116
2117=head1 COMMON QUESTIONS
2118
2119=head2 Why is there Perl source in my database?
2120
2121If you look at the contents of a database file created by DB_File,
2122there can sometimes be part of a Perl script included in it.
2123
2124This happens because Berkeley DB uses dynamic memory to allocate
2125buffers which will subsequently be written to the database file. Being
2126dynamic, the memory could have been used for anything before DB
2127malloced it. As Berkeley DB doesn't clear the memory once it has been
2128allocated, the unused portions will contain random junk. In the case
2129where a Perl script gets written to the database, the random junk will
2130correspond to an area of dynamic memory that happened to be used during
2131the compilation of the script.
2132
2133Unless you don't like the possibility of there being part of your Perl
2134scripts embedded in a database file, this is nothing to worry about.
2135
2136=head2 How do I store complex data structures with DB_File?
2137
2138Although B<DB_File> cannot do this directly, there is a module which
2139can layer transparently over B<DB_File> to accomplish this feat.
2140
2141Check out the MLDBM module, available on CPAN in the directory
2142F<modules/by-module/MLDBM>.
2143
2144=head2 What does "Invalid Argument" mean?
2145
2146You will get this error message when one of the parameters in the
2147C<tie> call is wrong. Unfortunately there are quite a few parameters to
2148get wrong, so it can be difficult to figure out which one it is.
2149
2150Here are a couple of possibilities:
2151
2152=over 5
2153
2154=item 1.
2155
610ab055 2156Attempting to reopen a database without closing it.
f6b705ef 2157
2158=item 2.
2159
2160Using the O_WRONLY flag.
2161
2162=back
2163
2164=head2 What does "Bareword 'DB_File' not allowed" mean?
2165
2166You will encounter this particular error message when you have the
2167C<strict 'subs'> pragma (or the full strict pragma) in your script.
2168Consider this script:
2169
3245f058 2170 use warnings ;
f6b705ef 2171 use strict ;
2172 use DB_File ;
2173 use vars qw(%x) ;
2174 tie %x, DB_File, "filename" ;
2175
2176Running it produces the error in question:
2177
2178 Bareword "DB_File" not allowed while "strict subs" in use
2179
2180To get around the error, place the word C<DB_File> in either single or
2181double quotes, like this:
2182
2183 tie %x, "DB_File", "filename" ;
2184
2185Although it might seem like a real pain, it is really worth the effort
2186of having a C<use strict> in all your scripts.
2187
cad2e5aa 2188=head1 REFERENCES
2189
2190Articles that are either about B<DB_File> or make use of it.
2191
2192=over 5
2193
2194=item 1.
2195
2196I<Full-Text Searching in Perl>, Tim Kientzle (tkientzle@ddj.com),
2197Dr. Dobb's Journal, Issue 295, January 1999, pp 34-41
2198
2199=back
2200
cb1a09d0 2201=head1 HISTORY
2202
1f70e1ea 2203Moved to the Changes file.
610ab055 2204
1f70e1ea 2205=head1 BUGS
05475680 2206
1f70e1ea 2207Some older versions of Berkeley DB had problems with fixed length
2208records using the RECNO file format. This problem has been fixed since
2209version 1.85 of Berkeley DB.
e858de61 2210
1f70e1ea 2211I am sure there are bugs in the code. If you do find any, or can
2212suggest any enhancements, I would welcome your comments.
a6ed719b 2213
1f70e1ea 2214=head1 AVAILABILITY
a6ed719b 2215
1f70e1ea 2216B<DB_File> comes with the standard Perl source distribution. Look in
2217the directory F<ext/DB_File>. Given the amount of time between releases
2218of Perl the version that ships with Perl is quite likely to be out of
2219date, so the most recent version can always be found on CPAN (see
2220L<perlmod/CPAN> for details), in the directory
2221F<modules/by-module/DB_File>.
a6ed719b 2222
039d031f 2223This version of B<DB_File> will work with either version 1.x, 2.x or
22243.x of Berkeley DB, but is limited to the functionality provided by
2225version 1.
a6ed719b 2226
cad2e5aa 2227The official web site for Berkeley DB is F<http://www.sleepycat.com>.
039d031f 2228All versions of Berkeley DB are available there.
93af7a87 2229
1f70e1ea 2230Alternatively, Berkeley DB version 1 is available at your nearest CPAN
2231archive in F<src/misc/db.1.85.tar.gz>.
e858de61 2232
1f70e1ea 2233If you are running IRIX, then get Berkeley DB version 1 from
2234F<http://reality.sgi.com/ariel>. It has the patches necessary to
2235compile properly on IRIX 5.3.
610ab055 2236
1f70e1ea 2237=head1 COPYRIGHT
3b35bae3 2238
c5da4faf 2239Copyright (c) 1995-2001 Paul Marquess. All rights reserved. This program
a9fd575d 2240is free software; you can redistribute it and/or modify it under the
2241same terms as Perl itself.
3b35bae3 2242
1f70e1ea 2243Although B<DB_File> is covered by the Perl license, the library it
2244makes use of, namely Berkeley DB, is not. Berkeley DB has its own
2245copyright and its own license. Please take the time to read it.
3b35bae3 2246
a9fd575d 2247Here are are few words taken from the Berkeley DB FAQ (at
b90e71be 2248F<http://www.sleepycat.com>) regarding the license:
68dc0745 2249
a9fd575d 2250 Do I have to license DB to use it in Perl scripts?
3b35bae3 2251
a9fd575d 2252 No. The Berkeley DB license requires that software that uses
2253 Berkeley DB be freely redistributable. In the case of Perl, that
2254 software is Perl, and not your scripts. Any Perl scripts that you
2255 write are your property, including scripts that make use of
2256 Berkeley DB. Neither the Perl license nor the Berkeley DB license
2257 place any restriction on what you may do with them.
88108326 2258
1f70e1ea 2259If you are in any doubt about the license situation, contact either the
2260Berkeley DB authors or the author of DB_File. See L<"AUTHOR"> for details.
a0b8c8c1 2261
2262
3b35bae3 2263=head1 SEE ALSO
2264
9fe6733a 2265L<perl(1)>, L<dbopen(3)>, L<hash(3)>, L<recno(3)>, L<btree(3)>,
2266L<dbmfilter>
3b35bae3 2267
3b35bae3 2268=head1 AUTHOR
2269
8e07c86e 2270The DB_File interface was written by Paul Marquess
6ca2e664 2271E<lt>Paul.Marquess@btinternet.comE<gt>.
d3ef3b8a 2272Questions about the DB system itself may be addressed to
2273E<lt>db@sleepycat.com<gt>.
3b35bae3 2274
2275=cut