1 # DB_File.pm -- Perl 5 interface to Berkeley DB
3 # written by Paul Marquess (Paul.Marquess@btinternet.com)
4 # last modified 30th July 2001
7 # Copyright (c) 1995-2001 Paul Marquess. All rights reserved.
8 # This program is free software; you can redistribute it and/or
9 # modify it under the same terms as Perl itself.
12 package DB_File::HASHINFO ;
20 @DB_File::HASHINFO::ISA = qw(Tie::Hash);
35 bless { VALID => { map {$_, 1}
36 qw( bsize ffactor nelem cachesize hash lorder)
48 return $self->{GOT}{$key} if exists $self->{VALID}{$key} ;
51 croak "${pkg}::FETCH - Unknown element '$key'" ;
61 if ( exists $self->{VALID}{$key} )
63 $self->{GOT}{$key} = $value ;
68 croak "${pkg}::STORE - Unknown element '$key'" ;
76 if ( exists $self->{VALID}{$key} )
78 delete $self->{GOT}{$key} ;
83 croak "DB_File::HASHINFO::DELETE - Unknown element '$key'" ;
91 exists $self->{VALID}{$key} ;
99 croak ref($self) . " does not define the method ${method}" ;
102 sub FIRSTKEY { my $self = shift ; $self->NotHere("FIRSTKEY") }
103 sub NEXTKEY { my $self = shift ; $self->NotHere("NEXTKEY") }
104 sub CLEAR { my $self = shift ; $self->NotHere("CLEAR") }
106 package DB_File::RECNOINFO ;
111 @DB_File::RECNOINFO::ISA = qw(DB_File::HASHINFO) ;
117 bless { VALID => { map {$_, 1}
118 qw( bval cachesize psize flags lorder reclen bfname )
124 package DB_File::BTREEINFO ;
129 @DB_File::BTREEINFO::ISA = qw(DB_File::HASHINFO) ;
135 bless { VALID => { map {$_, 1}
136 qw( flags cachesize maxkeypage minkeypage psize
137 compare prefix lorder )
148 use vars qw($VERSION @ISA @EXPORT $AUTOLOAD $DB_BTREE $DB_HASH $DB_RECNO
149 $db_version $use_XSLoader
156 #typedef enum { DB_BTREE, DB_HASH, DB_RECNO } DBTYPE;
157 $DB_BTREE = new DB_File::BTREEINFO ;
158 $DB_HASH = new DB_File::HASHINFO ;
159 $DB_RECNO = new DB_File::RECNOINFO ;
166 eval { require XSLoader } ;
171 @ISA = qw(DynaLoader);
175 push @ISA, qw(Tie::Hash Exporter);
177 $DB_BTREE $DB_HASH $DB_RECNO
212 ($constname = $AUTOLOAD) =~ s/.*:://;
213 my $val = constant($constname, @_ ? $_[0] : 0);
215 if ($! =~ /Invalid/ || $!{EINVAL}) {
216 $AutoLoader::AUTOLOAD = $AUTOLOAD;
217 goto &AutoLoader::AUTOLOAD;
220 my($pack,$file,$line) = caller;
221 croak "Your vendor has not defined DB macro $constname, used at $file line $line.
226 *{$AUTOLOAD} = sub { $val };
232 # Make all Fcntl O_XXX constants available for importing
234 my @O = grep /^O_/, @Fcntl::EXPORT;
235 Fcntl->import(@O); # first we import what we want to export
240 { XSLoader::load("DB_File", $VERSION)}
242 { bootstrap DB_File $VERSION }
244 # Preloaded methods go here. Autoload methods go after __END__, and are
245 # processed by the autosplit program.
247 sub tie_hash_or_array
250 my $tieHASH = ( (caller(1))[3] =~ /TIEHASH/ ) ;
252 $arg[4] = tied %{ $arg[4] }
253 if @arg >= 5 && ref $arg[4] && $arg[4] =~ /=HASH/ && tied %{ $arg[4] } ;
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 ;
260 chmod $arg[3] ? $arg[3] : 0666 , $arg[1] ;
263 DoTie_($tieHASH, @arg) ;
268 tie_hash_or_array(@_) ;
273 tie_hash_or_array(@_) ;
281 my $status = $self->seq($key, $value, R_FIRST());
284 while ($status == 0) {
286 $status = $self->seq($key, $value, R_NEXT());
288 foreach $key (reverse @keys) {
289 my $s = $self->del($key);
299 my $current_length = $self->length() ;
301 if ($length < $current_length) {
303 for ($key = $current_length - 1 ; $key >= $length ; -- $key)
306 elsif ($length > $current_length) {
307 $self->put($length-1, "") ;
316 if (not defined $offset) {
317 carp 'Use of uninitialized value in splice';
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().
328 my $size = $self->FETCHSIZE();
330 # 'If OFFSET is negative then it start that far from the end of
334 my $new_offset = $size + $offset;
335 if ($new_offset < 0) {
336 die "Modification of non-creatable array value attempted, "
337 . "subscript $offset";
339 $offset = $new_offset;
342 if ($offset > $size) {
346 if (not defined $length) {
347 carp 'Use of uninitialized value in splice';
351 # 'If LENGTH is omitted, removes everything from OFFSET onward.'
352 if (not defined $length) {
353 $length = $size - $offset;
356 # 'If LENGTH is negative, leave that many elements off the end of
360 $length = $size - $offset + $length;
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.
371 if ($length > $size - $offset) {
372 $length = $size - $offset;
375 # $num_elems holds the current number of elements in the database.
376 my $num_elems = $size;
378 # 'Removes the elements designated by OFFSET and LENGTH from an
382 foreach (0 .. $length - 1) {
384 my $status = $self->get($offset, $old);
386 my $msg = "error from Berkeley DB on get($offset, \$old)";
388 $msg .= ' (no such element?)';
391 $msg .= ": error status $status";
392 if (defined $! and $! ne '') {
393 $msg .= ", message $!";
400 $status = $self->del($offset);
402 my $msg = "error from Berkeley DB on del($offset)";
404 $msg .= ' (no such element?)';
407 $msg .= ": error status $status";
408 if (defined $! and $! ne '') {
409 $msg .= ", message $!";
418 # ...'and replaces them with the elements of LIST, if any.'
420 while (defined (my $elem = shift @list)) {
423 if ($pos >= $num_elems) {
424 $status = $self->put($pos, $elem);
427 $status = $self->put($pos, $elem, $self->R_IBEFORE);
431 my $msg = "error from Berkeley DB on put($pos, $elem, ...)";
433 $msg .= ' (no such element?)';
436 $msg .= ", error status $status";
437 if (defined $! and $! ne '') {
438 $msg .= ", message $!";
444 die "pos unexpectedly changed from $old_pos to $pos with R_IBEFORE"
452 # 'In list context, returns the elements removed from the
457 elsif (defined wantarray and not wantarray) {
458 # 'In scalar context, returns the last element removed, or
459 # undef if no elements are removed.'
462 my $last = pop @removed;
469 elsif (not defined wantarray) {
474 sub ::DB_File::splice { &SPLICE }
478 croak "Usage: \$db->find_dup(key,value)\n"
482 my ($origkey, $value_wanted) = @_ ;
483 my ($key, $value) = ($origkey, 0);
486 for ($status = $db->seq($key, $value, R_CURSOR() ) ;
488 $status = $db->seq($key, $value, R_NEXT() ) ) {
490 return 0 if $key eq $origkey and $value eq $value_wanted ;
498 croak "Usage: \$db->del_dup(key,value)\n"
502 my ($key, $value) = @_ ;
503 my ($status) = $db->find_dup($key, $value) ;
504 return $status if $status != 0 ;
506 $status = $db->del($key, R_CURSOR() ) ;
512 croak "Usage: \$db->get_dup(key [,flag])\n"
513 unless @_ == 2 or @_ == 3 ;
520 my $wantarray = wantarray ;
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()) ) {
532 # save the value or count number of matches
535 { ++ $values{$value} }
537 { push (@values, $value) }
544 return ($wantarray ? ($flag ? %values : @values) : $counter) ;
553 DB_File - Perl5 access to Berkeley DB version 1.x
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 ;
563 $status = $X->del($key [, $flags]) ;
564 $status = $X->put($key, $value [, $flags]) ;
565 $status = $X->get($key, $value [, $flags]) ;
566 $status = $X->seq($key, $value, $flags) ;
567 $status = $X->sync([$flags]) ;
571 $count = $X->get_dup($key) ;
572 @list = $X->get_dup($key) ;
573 %list = $X->get_dup($key, 1) ;
574 $status = $X->find_dup($key, $value) ;
575 $status = $X->del_dup($key, $value) ;
583 @r = $X->splice(offset, length, elements);
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 { ... } ) ;
596 B<DB_File> is a module which allows Perl programs to make use of the
597 facilities provided by Berkeley DB version 1.x (if you have a newer
598 version of DB, see L<Using DB_File with Berkeley DB version 2 or 3>).
599 It is assumed that you have a copy of the Berkeley DB manual pages at
600 hand when reading this documentation. The interface defined here
601 mirrors the Berkeley DB interface closely.
603 Berkeley DB is a C library which provides a consistent interface to a
604 number of database formats. B<DB_File> provides an interface to all
605 three of the database types currently supported by Berkeley DB.
613 This database type allows arbitrary key/value pairs to be stored in data
614 files. This is equivalent to the functionality provided by other
615 hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though,
616 the files created using DB_HASH are not compatible with any of the
617 other packages mentioned.
619 A default hashing algorithm, which will be adequate for most
620 applications, is built into Berkeley DB. If you do need to use your own
621 hashing algorithm it is possible to write your own in Perl and have
622 B<DB_File> use it instead.
626 The btree format allows arbitrary key/value pairs to be stored in a
627 sorted, balanced binary tree.
629 As with the DB_HASH format, it is possible to provide a user defined
630 Perl routine to perform the comparison of keys. By default, though, the
631 keys are stored in lexical order.
635 DB_RECNO allows both fixed-length and variable-length flat text files
636 to be manipulated using the same key/value pair interface as in DB_HASH
637 and DB_BTREE. In this case the key will consist of a record (line)
642 =head2 Using DB_File with Berkeley DB version 2 or 3
644 Although B<DB_File> is intended to be used with Berkeley DB version 1,
645 it can also be used with version 2 or 3. In this case the interface is
646 limited to the functionality provided by Berkeley DB 1.x. Anywhere the
647 version 2 or 3 interface differs, B<DB_File> arranges for it to work
648 like version 1. This feature allows B<DB_File> scripts that were built
649 with version 1 to be migrated to version 2 or 3 without any changes.
651 If you want to make use of the new features available in Berkeley DB
652 2.x or greater, use the Perl module B<BerkeleyDB> instead.
654 B<Note:> The database file format has changed in both Berkeley DB
655 version 2 and 3. If you cannot recreate your databases, you must dump
656 any existing databases with either the C<db_dump> or the C<db_dump185>
657 utility that comes with Berkeley DB.
658 Once you have rebuilt DB_File to use Berkeley DB version 2 or 3, your
659 databases can be recreated using C<db_load>. Refer to the Berkeley DB
660 documentation for further details.
662 Please read L<"COPYRIGHT"> before using version 2.x or 3.x of Berkeley
665 =head2 Interface to Berkeley DB
667 B<DB_File> allows access to Berkeley DB files using the tie() mechanism
668 in Perl 5 (for full details, see L<perlfunc/tie()>). This facility
669 allows B<DB_File> to access Berkeley DB files using either an
670 associative array (for DB_HASH & DB_BTREE file types) or an ordinary
671 array (for the DB_RECNO file type).
673 In addition to the tie() interface, it is also possible to access most
674 of the functions provided in the Berkeley DB API directly.
675 See L<THE API INTERFACE>.
677 =head2 Opening a Berkeley DB Database File
679 Berkeley DB uses the function dbopen() to open or create a database.
680 Here is the C prototype for dbopen():
683 dbopen (const char * file, int flags, int mode,
684 DBTYPE type, const void * openinfo)
686 The parameter C<type> is an enumeration which specifies which of the 3
687 interface methods (DB_HASH, DB_BTREE or DB_RECNO) is to be used.
688 Depending on which of these is actually chosen, the final parameter,
689 I<openinfo> points to a data structure which allows tailoring of the
690 specific interface method.
692 This interface is handled slightly differently in B<DB_File>. Here is
693 an equivalent call using B<DB_File>:
695 tie %array, 'DB_File', $filename, $flags, $mode, $DB_HASH ;
697 The C<filename>, C<flags> and C<mode> parameters are the direct
698 equivalent of their dbopen() counterparts. The final parameter $DB_HASH
699 performs the function of both the C<type> and C<openinfo> parameters in
702 In the example above $DB_HASH is actually a pre-defined reference to a
703 hash object. B<DB_File> has three of these pre-defined references.
704 Apart from $DB_HASH, there is also $DB_BTREE and $DB_RECNO.
706 The keys allowed in each of these pre-defined references is limited to
707 the names used in the equivalent C structure. So, for example, the
708 $DB_HASH reference will only allow keys called C<bsize>, C<cachesize>,
709 C<ffactor>, C<hash>, C<lorder> and C<nelem>.
711 To change one of these elements, just assign to it like this:
713 $DB_HASH->{'cachesize'} = 10000 ;
715 The three predefined variables $DB_HASH, $DB_BTREE and $DB_RECNO are
716 usually adequate for most applications. If you do need to create extra
717 instances of these objects, constructors are available for each file
720 Here are examples of the constructors and the valid options available
721 for DB_HASH, DB_BTREE and DB_RECNO respectively.
723 $a = new DB_File::HASHINFO ;
731 $b = new DB_File::BTREEINFO ;
741 $c = new DB_File::RECNOINFO ;
750 The values stored in the hashes above are mostly the direct equivalent
751 of their C counterpart. Like their C counterparts, all are set to a
752 default values - that means you don't have to set I<all> of the
753 values when you only want to change one. Here is an example:
755 $a = new DB_File::HASHINFO ;
756 $a->{'cachesize'} = 12345 ;
757 tie %y, 'DB_File', "filename", $flags, 0777, $a ;
759 A few of the options need extra discussion here. When used, the C
760 equivalent of the keys C<hash>, C<compare> and C<prefix> store pointers
761 to C functions. In B<DB_File> these keys are used to store references
762 to Perl subs. Below are templates for each of the subs:
768 # return the hash value for $data
774 my ($key, $key2) = @_ ;
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) ;
784 my ($key, $key2) = @_ ;
786 # return number of bytes of $key2 which are
787 # necessary to determine that it is greater than $key1
791 See L<Changing the BTREE sort order> for an example of using the
794 If you are using the DB_RECNO interface and you intend making use of
795 C<bval>, you should check out L<The 'bval' Option>.
797 =head2 Default Parameters
799 It is possible to omit some or all of the final 4 parameters in the
800 call to C<tie> and let them take default values. As DB_HASH is the most
801 common file format used, the call:
803 tie %A, "DB_File", "filename" ;
807 tie %A, "DB_File", "filename", O_CREAT|O_RDWR, 0666, $DB_HASH ;
809 It is also possible to omit the filename parameter as well, so the
816 tie %A, "DB_File", undef, O_CREAT|O_RDWR, 0666, $DB_HASH ;
818 See L<In Memory Databases> for a discussion on the use of C<undef>
819 in place of a filename.
821 =head2 In Memory Databases
823 Berkeley 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>
825 uses C<undef> instead of NULL to provide this functionality.
829 The DB_HASH file format is probably the most commonly used of the three
830 file formats that B<DB_File> supports. It is also very straightforward
833 =head2 A Simple Example
835 This example shows how to create a database, add key/value pairs to the
836 database, delete keys/value pairs and finally how to enumerate the
837 contents of the database.
842 use vars qw( %h $k $v ) ;
845 tie %h, "DB_File", "fruit", O_RDWR|O_CREAT, 0666, $DB_HASH
846 or die "Cannot open file 'fruit': $!\n";
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" ;
854 # Check for existence of a key
855 print "Banana Exists\n\n" if $h{"banana"} ;
857 # Delete a key/value pair.
860 # print the contents of the file
861 while (($k, $v) = each %h)
862 { print "$k -> $v\n" }
874 Note that the like ordinary associative arrays, the order of the keys
875 retrieved is in an apparently random order.
879 The DB_BTREE format is useful when you want to store data in a given
880 order. By default the keys will be stored in lexical order, but as you
881 will see from the example shown in the next section, it is very easy to
882 define your own sorting function.
884 =head2 Changing the BTREE sort order
886 This script shows how to override the default sorting algorithm that
887 BTREE uses. Instead of using the normal lexical ordering, a case
888 insensitive compare function will be used.
898 my ($key1, $key2) = @_ ;
899 "\L$key1" cmp "\L$key2" ;
902 # specify the Perl sub that will do the comparison
903 $DB_BTREE->{'compare'} = \&Compare ;
906 tie %h, "DB_File", "tree", O_RDWR|O_CREAT, 0666, $DB_BTREE
907 or die "Cannot open file 'tree': $!\n" ;
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' ;
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.
926 Here is the output from the code above.
932 There are a few point to bear in mind if you want to change the
933 ordering in a BTREE database:
939 The new compare function must be specified when you create the database.
943 You cannot change the ordering once the database has been created. Thus
944 you must use the same compare function every time you access the
949 Duplicate keys are entirely defined by the comparison function.
950 In the case-insensitive example above, the keys: 'KEY' and 'key'
951 would be considered duplicates, and assigning to the second one
952 would overwrite the first. If duplicates are allowed for (with the
953 R_DUPS flag discussed below), only a single copy of duplicate keys
954 is stored in the database --- so (again with example above) assigning
955 three values to the keys: 'KEY', 'Key', and 'key' would leave just
956 the first key: 'KEY' in the database with three values. For some
957 situations this results in information loss, so care should be taken
958 to provide fully qualified comparison functions when necessary.
959 For example, the above comparison routine could be modified to
960 additionally compare case-sensitively if two keys are equal in the
961 case insensitive comparison:
964 my($key1, $key2) = @_;
965 lc $key1 cmp lc $key2 ||
969 And now you will only have duplicates when the keys themselves
970 are truly the same. (note: in versions of the db library prior to
971 about November 1996, such duplicate keys were retained so it was
972 possible to recover the original keys in sets of keys that
978 =head2 Handling Duplicate Keys
980 The BTREE file type optionally allows a single key to be associated
981 with an arbitrary number of values. This option is enabled by setting
982 the flags element of C<$DB_BTREE> to R_DUP when creating the database.
984 There are some difficulties in using the tied hash interface if you
985 want to manipulate a BTREE database with duplicate keys. Consider this
992 use vars qw($filename %h ) ;
997 # Enable duplicate records
998 $DB_BTREE->{'flags'} = R_DUP ;
1000 tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1001 or die "Cannot open $filename: $!\n";
1003 # Add some key/value pairs to the file
1004 $h{'Wall'} = 'Larry' ;
1005 $h{'Wall'} = 'Brick' ; # Note the duplicate key
1006 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
1007 $h{'Smith'} = 'John' ;
1008 $h{'mouse'} = 'mickey' ;
1010 # iterate through the associative array
1011 # and print each key/value pair.
1012 foreach (sort keys %h)
1013 { print "$_ -> $h{$_}\n" }
1025 As you can see 3 records have been successfully created with key C<Wall>
1026 - the only thing is, when they are retrieved from the database they
1027 I<seem> to have the same value, namely C<Larry>. The problem is caused
1028 by the way that the associative array interface works. Basically, when
1029 the associative array interface is used to fetch the value associated
1030 with a given key, it will only ever retrieve the first value.
1032 Although it may not be immediately obvious from the code above, the
1033 associative array interface can be used to write values with duplicate
1034 keys, but it cannot be used to read them back from the database.
1036 The way to get around this problem is to use the Berkeley DB API method
1037 called C<seq>. This method allows sequential access to key/value
1038 pairs. See L<THE API INTERFACE> for details of both the C<seq> method
1039 and the API in general.
1041 Here is the script above rewritten using the C<seq> API method.
1047 use vars qw($filename $x %h $status $key $value) ;
1049 $filename = "tree" ;
1052 # Enable duplicate records
1053 $DB_BTREE->{'flags'} = R_DUP ;
1055 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1056 or die "Cannot open $filename: $!\n";
1058 # Add some key/value pairs to the file
1059 $h{'Wall'} = 'Larry' ;
1060 $h{'Wall'} = 'Brick' ; # Note the duplicate key
1061 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
1062 $h{'Smith'} = 'John' ;
1063 $h{'mouse'} = 'mickey' ;
1065 # iterate through the btree using seq
1066 # and print each key/value pair.
1068 for ($status = $x->seq($key, $value, R_FIRST) ;
1070 $status = $x->seq($key, $value, R_NEXT) )
1071 { print "$key -> $value\n" }
1084 This time we have got all the key/value pairs, including the multiple
1085 values associated with the key C<Wall>.
1087 To make life easier when dealing with duplicate keys, B<DB_File> comes with
1088 a few utility methods.
1090 =head2 The get_dup() Method
1092 The C<get_dup> method assists in
1093 reading duplicate values from BTREE databases. The method can take the
1096 $count = $x->get_dup($key) ;
1097 @list = $x->get_dup($key) ;
1098 %list = $x->get_dup($key, 1) ;
1100 In a scalar context the method returns the number of values associated
1101 with the key, C<$key>.
1103 In list context, it returns all the values which match C<$key>. Note
1104 that the values will be returned in an apparently random order.
1106 In list context, if the second parameter is present and evaluates
1107 TRUE, the method returns an associative array. The keys of the
1108 associative array correspond to the values that matched in the BTREE
1109 and the values of the array are a count of the number of times that
1110 particular value occurred in the BTREE.
1112 So assuming the database created above, we can use C<get_dup> like
1119 use vars qw($filename $x %h ) ;
1121 $filename = "tree" ;
1123 # Enable duplicate records
1124 $DB_BTREE->{'flags'} = R_DUP ;
1126 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1127 or die "Cannot open $filename: $!\n";
1129 my $cnt = $x->get_dup("Wall") ;
1130 print "Wall occurred $cnt times\n" ;
1132 my %hash = $x->get_dup("Wall", 1) ;
1133 print "Larry is there\n" if $hash{'Larry'} ;
1134 print "There are $hash{'Brick'} Brick Walls\n" ;
1136 my @list = sort $x->get_dup("Wall") ;
1137 print "Wall => [@list]\n" ;
1139 @list = $x->get_dup("Smith") ;
1140 print "Smith => [@list]\n" ;
1142 @list = $x->get_dup("Dog") ;
1143 print "Dog => [@list]\n" ;
1148 Wall occurred 3 times
1150 There are 2 Brick Walls
1151 Wall => [Brick Brick Larry]
1155 =head2 The find_dup() Method
1157 $status = $X->find_dup($key, $value) ;
1159 This method checks for the existence of a specific key/value pair. If the
1160 pair exists, the cursor is left pointing to the pair and the method
1161 returns 0. Otherwise the method returns a non-zero value.
1163 Assuming the database from the previous example:
1169 use vars qw($filename $x %h $found) ;
1171 my $filename = "tree" ;
1173 # Enable duplicate records
1174 $DB_BTREE->{'flags'} = R_DUP ;
1176 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1177 or die "Cannot open $filename: $!\n";
1179 $found = ( $x->find_dup("Wall", "Larry") == 0 ? "" : "not") ;
1180 print "Larry Wall is $found there\n" ;
1182 $found = ( $x->find_dup("Wall", "Harry") == 0 ? "" : "not") ;
1183 print "Harry Wall is $found there\n" ;
1191 Harry Wall is not there
1194 =head2 The del_dup() Method
1196 $status = $X->del_dup($key, $value) ;
1198 This method deletes a specific key/value pair. It returns
1199 0 if they exist and have been deleted successfully.
1200 Otherwise the method returns a non-zero value.
1202 Again assuming the existence of the C<tree> database
1208 use vars qw($filename $x %h $found) ;
1210 my $filename = "tree" ;
1212 # Enable duplicate records
1213 $DB_BTREE->{'flags'} = R_DUP ;
1215 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1216 or die "Cannot open $filename: $!\n";
1218 $x->del_dup("Wall", "Larry") ;
1220 $found = ( $x->find_dup("Wall", "Larry") == 0 ? "" : "not") ;
1221 print "Larry Wall is $found there\n" ;
1228 Larry Wall is not there
1230 =head2 Matching Partial Keys
1232 The BTREE interface has a feature which allows partial keys to be
1233 matched. This functionality is I<only> available when the C<seq> method
1234 is used along with the R_CURSOR flag.
1236 $x->seq($key, $value, R_CURSOR) ;
1238 Here is the relevant quote from the dbopen man page where it defines
1239 the use of the R_CURSOR flag with seq:
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.
1246 In the example script below, the C<match> sub uses this feature to find
1247 and print the first matching key/value pair given a partial key.
1254 use vars qw($filename $x %h $st $key $value) ;
1260 my $orig_key = $key ;
1261 $x->seq($key, $value, R_CURSOR) ;
1262 print "$orig_key\t-> $key\t-> $value\n" ;
1265 $filename = "tree" ;
1268 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1269 or die "Cannot open $filename: $!\n";
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' ;
1279 print "IN ORDER\n" ;
1280 for ($st = $x->seq($key, $value, R_FIRST) ;
1282 $st = $x->seq($key, $value, R_NEXT) )
1284 { print "$key -> $value\n" }
1286 print "\nPARTIAL MATCH\n" ;
1306 a -> mouse -> mickey
1310 DB_RECNO provides an interface to flat text files. Both variable and
1311 fixed length records are supported.
1313 In order to make RECNO more compatible with Perl, the array offset for
1314 all RECNO arrays begins at 0 rather than 1 as in Berkeley DB.
1316 As with normal Perl arrays, a RECNO array can be accessed using
1317 negative 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
1319 the start of the array will raise a fatal run-time error.
1321 =head2 The 'bval' Option
1323 The operation of the bval option warrants some discussion. Here is the
1324 definition of bval from the Berkeley DB 1.85 recno manual page:
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
1333 The second sentence is wrong. In actual fact bval will only default to
1334 C<"\n"> when the openinfo parameter in dbopen is NULL. If a non-NULL
1335 openinfo parameter is used at all, the value that happens to be in bval
1336 will be used. That means you always have to specify bval when making
1337 use of any of the options in the openinfo parameter. This documentation
1338 error will be fixed in the next release of Berkeley DB.
1340 That clarifies the situation with regards Berkeley DB itself. What
1341 about B<DB_File>? Well, the behavior defined in the quote above is
1342 quite useful, so B<DB_File> conforms to it.
1344 That means that you can specify other options (e.g. cachesize) and
1345 still have bval default to C<"\n"> for variable length records, and
1346 space for fixed length records.
1348 Also note that the bval option only allows you to specify a single byte
1351 =head2 A Simple Example
1353 Here is a simple example that uses RECNO (if you are using a version
1354 of Perl earlier than 5.004_57 this example won't work -- see
1355 L<Extra RECNO Methods> for a workaround).
1361 my $filename = "text" ;
1365 tie @h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_RECNO
1366 or die "Cannot open file 'text': $!\n" ;
1368 # Add a few key/value pairs to the file
1373 push @h, "green", "black" ;
1375 my $elements = scalar @h ;
1376 print "The array contains $elements entries\n" ;
1379 print "popped $last\n" ;
1381 unshift @h, "white" ;
1382 my $first = shift @h ;
1383 print "shifted $first\n" ;
1385 # Check for existence of a key
1386 print "Element 1 Exists with value $h[1]\n" if $h[1] ;
1388 # use a negative index
1389 print "The last element is $h[-1]\n" ;
1390 print "The 2nd last element is $h[-2]\n" ;
1394 Here is the output from the script:
1396 The array contains 5 entries
1399 Element 1 Exists with value blue
1400 The last element is green
1401 The 2nd last element is yellow
1403 =head2 Extra RECNO Methods
1405 If you are using a version of Perl earlier than 5.004_57, the tied
1406 array interface is quite limited. In the example script above
1407 C<push>, C<pop>, C<shift>, C<unshift>
1408 or determining the array length will not work with a tied array.
1410 To make the interface more useful for older versions of Perl, a number
1411 of methods are supplied with B<DB_File> to simulate the missing array
1412 operations. All these methods are accessed via the object returned from
1415 Here are the methods:
1419 =item B<$X-E<gt>push(list) ;>
1421 Pushes the elements of C<list> to the end of the array.
1423 =item B<$value = $X-E<gt>pop ;>
1425 Removes and returns the last element of the array.
1427 =item B<$X-E<gt>shift>
1429 Removes and returns the first element of the array.
1431 =item B<$X-E<gt>unshift(list) ;>
1433 Pushes the elements of C<list> to the start of the array.
1435 =item B<$X-E<gt>length>
1437 Returns the number of elements in the array.
1439 =item B<$X-E<gt>splice(offset, length, elements);>
1441 Returns a splice of the the array.
1445 =head2 Another Example
1447 Here is a more complete example that makes use of some of the methods
1448 described above. It also makes use of the API interface directly (see
1449 L<THE API INTERFACE>).
1453 use vars qw(@h $H $file $i) ;
1461 $H = tie @h, "DB_File", $file, O_RDWR|O_CREAT, 0666, $DB_RECNO
1462 or die "Cannot open file $file: $!\n" ;
1464 # first create a text file to play with
1472 # Print the records in order.
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.
1478 print "\nORIGINAL\n" ;
1479 foreach $i (0 .. $H->length - 1) {
1480 print "$i: $h[$i]\n" ;
1483 # use the push & pop methods
1486 print "\nThe last record was [$a]\n" ;
1488 # and the shift & unshift methods
1490 $H->unshift("first") ;
1491 print "The first record was [$a]\n" ;
1493 # Use the API to add a new record after record 2.
1495 $H->put($i, "Newbie", R_IAFTER) ;
1497 # and a new record before record 1.
1499 $H->put($i, "New One", R_IBEFORE) ;
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" }
1509 # same again, but use the API functions instead
1510 print "\nREVERSE again\n" ;
1511 my ($s, $k, $v) = (0, 0, 0) ;
1512 for ($s = $H->seq($k, $v, R_LAST) ;
1514 $s = $H->seq($k, $v, R_PREV))
1515 { print "$k: $v\n" }
1520 and this is what it outputs:
1529 The last record was [four]
1530 The first record was [zero]
1554 Rather than iterating through the array, C<@h> like this:
1558 it is necessary to use either this:
1560 foreach $i (0 .. $H->length - 1)
1564 for ($a = $H->get($k, $v, R_FIRST) ;
1566 $a = $H->get($k, $v, R_NEXT) )
1570 Notice that both times the C<put> method was used the record index was
1571 specified using a variable, C<$i>, rather than the literal value
1572 itself. This is because C<put> will return the record number of the
1573 inserted line via that parameter.
1577 =head1 THE API INTERFACE
1579 As well as accessing Berkeley DB using a tied hash or array, it is also
1580 possible to make direct use of most of the API functions defined in the
1581 Berkeley DB documentation.
1583 To do this you need to store a copy of the object returned from the tie.
1585 $db = tie %hash, "DB_File", "filename" ;
1587 Once you have done that, you can access the Berkeley DB API functions
1588 as B<DB_File> methods directly like this:
1590 $db->put($key, $value, R_NOOVERWRITE) ;
1592 B<Important:> If you have saved a copy of the object returned from
1593 C<tie>, the underlying database file will I<not> be closed until both
1594 the tied variable is untied and all copies of the saved object are
1598 $db = tie %hash, "DB_File", "filename"
1599 or die "Cannot tie filename: $!" ;
1604 See L<The untie() Gotcha> for more details.
1606 All the functions defined in L<dbopen> are available except for
1607 close() and dbopen() itself. The B<DB_File> method interface to the
1608 supported functions have been implemented to mirror the way Berkeley DB
1609 works whenever possible. In particular note that:
1615 The methods return a status value. All return 0 on success.
1616 All return -1 to signify an error and set C<$!> to the exact
1617 error code. The return code 1 generally (but not always) means that the
1618 key specified did not exist in the database.
1620 Other return codes are defined. See below and in the Berkeley DB
1621 documentation for details. The Berkeley DB documentation should be used
1622 as the definitive source.
1626 Whenever a Berkeley DB function returns data via one of its parameters,
1627 the equivalent B<DB_File> method does exactly the same.
1631 If you are careful, it is possible to mix API calls with the tied
1632 hash/array interface in the same piece of code. Although only a few of
1633 the methods used to implement the tied interface currently make use of
1634 the cursor, you should always assume that the cursor has been changed
1635 any time the tied hash/array interface is used. As an example, this
1636 code will probably not do what you expect:
1638 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1639 or die "Cannot tie $filename: $!" ;
1641 # Get the first key/value pair and set the cursor
1642 $X->seq($key, $value, R_FIRST) ;
1644 # this line will modify the cursor
1645 $count = scalar keys %x ;
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) ;
1651 The code above can be rearranged to get around the problem, like this:
1653 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1654 or die "Cannot tie $filename: $!" ;
1656 # this line will modify the cursor
1657 $count = scalar keys %x ;
1659 # Get the first key/value pair and set the cursor
1660 $X->seq($key, $value, R_FIRST) ;
1662 # Get the second key/value pair.
1664 $X->seq($key, $value, R_NEXT) ;
1668 All the constants defined in L<dbopen> for use in the flags parameters
1669 in the methods defined below are also available. Refer to the Berkeley
1670 DB documentation for the precise meaning of the flags values.
1672 Below is a list of the methods available.
1676 =item B<$status = $X-E<gt>get($key, $value [, $flags]) ;>
1678 Given a key (C<$key>) this method reads the value associated with it
1679 from the database. The value read from the database is returned in the
1680 C<$value> parameter.
1682 If the key does not exist the method returns 1.
1684 No flags are currently defined for this method.
1686 =item B<$status = $X-E<gt>put($key, $value [, $flags]) ;>
1688 Stores the key/value pair in the database.
1690 If you use either the R_IAFTER or R_IBEFORE flags, the C<$key> parameter
1691 will have the record number of the inserted key/value pair set.
1693 Valid flags are R_CURSOR, R_IAFTER, R_IBEFORE, R_NOOVERWRITE and
1696 =item B<$status = $X-E<gt>del($key [, $flags]) ;>
1698 Removes all key/value pairs with key C<$key> from the database.
1700 A return code of 1 means that the requested key was not in the
1703 R_CURSOR is the only valid flag at present.
1705 =item B<$status = $X-E<gt>fd ;>
1707 Returns the file descriptor for the underlying database.
1709 See L<Locking: The Trouble with fd> for an explanation for why you should
1710 not use C<fd> to lock your database.
1712 =item B<$status = $X-E<gt>seq($key, $value, $flags) ;>
1714 This interface allows sequential retrieval from the database. See
1715 L<dbopen> for full details.
1717 Both the C<$key> and C<$value> parameters will be set to the key/value
1718 pair read from the database.
1720 The flags parameter is mandatory. The valid flag values are R_CURSOR,
1721 R_FIRST, R_LAST, R_NEXT and R_PREV.
1723 =item B<$status = $X-E<gt>sync([$flags]) ;>
1725 Flushes any cached buffers to disk.
1727 R_RECNOSYNC is the only valid flag at present.
1733 A DBM Filter is a piece of code that is be used when you I<always>
1734 want to make the same transformation to all keys and/or values in a
1737 There are four methods associated with DBM Filters. All work identically,
1738 and each is used to install (or uninstall) a single DBM Filter. Each
1739 expects a single parameter, namely a reference to a sub. The only
1740 difference between them is the place that the filter is installed.
1746 =item B<filter_store_key>
1748 If a filter has been installed with this method, it will be invoked
1749 every time you write a key to a DBM database.
1751 =item B<filter_store_value>
1753 If a filter has been installed with this method, it will be invoked
1754 every time you write a value to a DBM database.
1757 =item B<filter_fetch_key>
1759 If a filter has been installed with this method, it will be invoked
1760 every time you read a key from a DBM database.
1762 =item B<filter_fetch_value>
1764 If a filter has been installed with this method, it will be invoked
1765 every time you read a value from a DBM database.
1769 You can use any combination of the methods, from none, to all four.
1771 All filter methods return the existing filter, if present, or C<undef>
1774 To delete a filter pass C<undef> to it.
1778 When each filter is called by Perl, a local copy of C<$_> will contain
1779 the key or value to be filtered. Filtering is achieved by modifying
1780 the contents of C<$_>. The return code from the filter is ignored.
1782 =head2 An Example -- the NULL termination problem.
1784 Consider the following scenario. You have a DBM database
1785 that you need to share with a third-party C application. The C application
1786 assumes that I<all> keys and values are NULL terminated. Unfortunately
1787 when Perl writes to DBM databases it doesn't use NULL termination, so
1788 your Perl application will have to manage NULL termination itself. When
1789 you write to the database you will have to use something like this:
1791 $hash{"$key\0"} = "$value\0" ;
1793 Similarly the NULL needs to be taken into account when you are considering
1794 the length of existing keys/values.
1796 It would be much better if you could ignore the NULL terminations issue
1797 in the main application code and have a mechanism that automatically
1798 added the terminating NULL to all keys and values whenever you write to
1799 the database and have them removed when you read from the database. As I'm
1800 sure you have already guessed, this is a problem that DBM Filters can
1808 my $filename = "/tmp/filt" ;
1811 my $db = tie %hash, 'DB_File', $filename, O_CREAT|O_RDWR, 0666, $DB_HASH
1812 or die "Cannot open $filename: $!\n" ;
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" } ) ;
1820 $hash{"abc"} = "def" ;
1821 my $a = $hash{"ABC"} ;
1826 Hopefully the contents of each of the filters should be
1827 self-explanatory. Both "fetch" filters remove the terminating NULL,
1828 and both "store" filters add a terminating NULL.
1831 =head2 Another Example -- Key is a C int.
1833 Here is another real-life example. By default, whenever Perl writes to
1834 a DBM database it always writes the key and value as strings. So when
1837 $hash{12345} = "soemthing" ;
1839 the 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
1841 as a C int, you will have to use C<pack> when writing, and C<unpack>
1844 Here is a DBM Filter that does it:
1850 my $filename = "/tmp/filt" ;
1854 my $db = tie %hash, 'DB_File', $filename, O_CREAT|O_RDWR, 0666, $DB_HASH
1855 or die "Cannot open $filename: $!\n" ;
1857 $db->filter_fetch_key ( sub { $_ = unpack("i", $_) } ) ;
1858 $db->filter_store_key ( sub { $_ = pack ("i", $_) } ) ;
1859 $hash{123} = "def" ;
1864 This time only two filters have been used -- we only need to manipulate
1865 the contents of the key, so it wasn't necessary to install any value
1868 =head1 HINTS AND TIPS
1871 =head2 Locking: The Trouble with fd
1873 Until version 1.72 of this module, the recommended technique for locking
1874 B<DB_File> databases was to flock the filehandle returned from the "fd"
1875 function. Unfortunately this technique has been shown to be fundamentally
1876 flawed (Kudos to David Harris for tracking this down). Use it at your own
1879 The locking technique went like this.
1881 $db = tie(%db, 'DB_File', '/tmp/foo.db', O_CREAT|O_RDWR, 0666)
1882 || die "dbcreat /tmp/foo.db $!";
1884 open(DB_FH, "+<&=$fd") || die "dup $!";
1885 flock (DB_FH, LOCK_EX) || die "flock: $!";
1887 $db{"Tom"} = "Jerry" ;
1889 flock(DB_FH, LOCK_UN);
1894 In simple terms, this is what happens:
1900 Use "tie" to open the database.
1904 Lock the database with fd & flock.
1908 Read & Write to the database.
1912 Unlock and close the database.
1916 Here is the crux of the problem. A side-effect of opening the B<DB_File>
1917 database in step 2 is that an initial block from the database will get
1918 read from disk and cached in memory.
1920 To see why this is a problem, consider what can happen when two processes,
1921 say "A" and "B", both want to update the same B<DB_File> database
1922 using the locking steps outlined above. Assume process "A" has already
1923 opened the database and has a write lock, but it hasn't actually updated
1924 the database yet (it has finished step 2, but not started step 3 yet). Now
1925 process "B" tries to open the same database - step 1 will succeed,
1926 but it will block on step 2 until process "A" releases the lock. The
1927 important thing to notice here is that at this point in time both
1928 processes will have cached identical initial blocks from the database.
1930 Now process "A" updates the database and happens to change some of the
1931 data held in the initial buffer. Process "A" terminates, flushing
1932 all cached data to disk and releasing the database lock. At this point
1933 the database on disk will correctly reflect the changes made by process
1936 With the lock released, process "B" can now continue. It also updates the
1937 database and unfortunately it too modifies the data that was in its
1938 initial buffer. Once that data gets flushed to disk it will overwrite
1939 some/all of the changes process "A" made to the database.
1941 The result of this scenario is at best a database that doesn't contain
1942 what you expect. At worst the database will corrupt.
1944 The above won't happen every time competing process update the same
1945 B<DB_File> database, but it does illustrate why the technique should
1948 =head2 Safe ways to lock a database
1950 Starting with version 2.x, Berkeley DB has internal support for locking.
1951 The companion module to this one, B<BerkeleyDB>, provides an interface
1952 to this locking functionality. If you are serious about locking
1953 Berkeley DB databases, I strongly recommend using B<BerkeleyDB>.
1955 If using B<BerkeleyDB> isn't an option, there are a number of modules
1956 available on CPAN that can be used to implement locking. Each one
1957 implements locking differently and has different goals in mind. It is
1958 therefore worth knowing the difference, so that you can pick the right
1959 one for your application. Here are the three locking wrappers:
1963 =item B<Tie::DB_Lock>
1965 A B<DB_File> wrapper which creates copies of the database file for
1966 read access, so that you have a kind of a multiversioning concurrent read
1967 system. However, updates are still serial. Use for databases where reads
1968 may be lengthy and consistency problems may occur.
1970 =item B<Tie::DB_LockFile>
1972 A B<DB_File> wrapper that has the ability to lock and unlock the database
1973 while it is being used. Avoids the tie-before-flock problem by simply
1974 re-tie-ing the database when you get or drop a lock. Because of the
1975 flexibility in dropping and re-acquiring the lock in the middle of a
1976 session, this can be massaged into a system that will work with long
1977 updates and/or reads if the application follows the hints in the POD
1980 =item B<DB_File::Lock>
1982 An extremely lightweight B<DB_File> wrapper that simply flocks a lockfile
1983 before tie-ing the database and drops the lock after the untie. Allows
1984 one to use the same lockfile for multiple databases to avoid deadlock
1985 problems, if desired. Use for databases where updates are reads are
1986 quick and simple flock locking semantics are enough.
1990 =head2 Sharing Databases With C Applications
1992 There is no technical reason why a Berkeley DB database cannot be
1993 shared by both a Perl and a C application.
1995 The vast majority of problems that are reported in this area boil down
1996 to the fact that C strings are NULL terminated, whilst Perl strings are
1997 not. See L<DBM FILTERS> for a generic way to work around this problem.
1999 Here is a real example. Netscape 2.0 keeps a record of the locations you
2000 visit along with the time you last visited them in a DB_HASH database.
2001 This is usually stored in the file F<~/.netscape/history.db>. The key
2002 field in the database is the location string and the value field is the
2003 time the location was last visited stored as a 4 byte binary value.
2005 If you haven't already guessed, the location string is stored with a
2006 terminating NULL. This means you need to be careful when accessing the
2009 Here is a snippet of code that is loosely based on Tom Christiansen's
2010 I<ggh> script (available from your nearest CPAN archive in
2011 F<authors/id/TOMC/scripts/nshist.gz>).
2018 use vars qw( $dotdir $HISTORY %hist_db $href $binary_time $date ) ;
2019 $dotdir = $ENV{HOME} || $ENV{LOGNAME};
2021 $HISTORY = "$dotdir/.netscape/history.db";
2023 tie %hist_db, 'DB_File', $HISTORY
2024 or die "Cannot open $HISTORY: $!\n" ;;
2026 # Dump the complete database
2027 while ( ($href, $binary_time) = each %hist_db ) {
2029 # remove the terminating NULL
2030 $href =~ s/\x00$// ;
2032 # convert the binary time into a user friendly string
2033 $date = localtime unpack("V", $binary_time);
2034 print "$date $href\n" ;
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" ;
2044 print "Never visited mox.perl.com\n"
2049 =head2 The untie() Gotcha
2051 If you make use of the Berkeley DB API, it is I<very> strongly
2052 recommended that you read L<perltie/The untie Gotcha>.
2054 Even if you don't currently make use of the API interface, it is still
2057 Here is an example which illustrates the problem from a B<DB_File>
2066 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_TRUNC
2067 or die "Cannot tie first time: $!" ;
2073 tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
2074 or die "Cannot tie second time: $!" ;
2078 When run, the script will produce this error message:
2080 Cannot tie second time: Invalid argument at bad.file line 14.
2082 Although the error message above refers to the second tie() statement
2083 in the script, the source of the problem is really with the untie()
2084 statement that precedes it.
2086 Having read L<perltie> you will probably have already guessed that the
2087 error is caused by the extra copy of the tied object stored in C<$X>.
2088 If you haven't, then the problem boils down to the fact that the
2089 B<DB_File> destructor, DESTROY, will not be called until I<all>
2090 references to the tied object are destroyed. Both the tied variable,
2091 C<%x>, and C<$X> above hold a reference to the object. The call to
2092 untie() will destroy the first, but C<$X> still holds a valid
2093 reference, so the destructor will not get called and the database file
2094 F<tst.fil> will remain open. The fact that Berkeley DB then reports the
2095 attempt to open a database that is already open via the catch-all
2096 "Invalid argument" doesn't help.
2098 If you run the script with the C<-w> flag the error message becomes:
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.
2103 which pinpoints the real problem. Finally the script can now be
2104 modified to fix the original problem by destroying the API object
2113 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
2117 =head1 COMMON QUESTIONS
2119 =head2 Why is there Perl source in my database?
2121 If you look at the contents of a database file created by DB_File,
2122 there can sometimes be part of a Perl script included in it.
2124 This happens because Berkeley DB uses dynamic memory to allocate
2125 buffers which will subsequently be written to the database file. Being
2126 dynamic, the memory could have been used for anything before DB
2127 malloced it. As Berkeley DB doesn't clear the memory once it has been
2128 allocated, the unused portions will contain random junk. In the case
2129 where a Perl script gets written to the database, the random junk will
2130 correspond to an area of dynamic memory that happened to be used during
2131 the compilation of the script.
2133 Unless you don't like the possibility of there being part of your Perl
2134 scripts embedded in a database file, this is nothing to worry about.
2136 =head2 How do I store complex data structures with DB_File?
2138 Although B<DB_File> cannot do this directly, there is a module which
2139 can layer transparently over B<DB_File> to accomplish this feat.
2141 Check out the MLDBM module, available on CPAN in the directory
2142 F<modules/by-module/MLDBM>.
2144 =head2 What does "Invalid Argument" mean?
2146 You will get this error message when one of the parameters in the
2147 C<tie> call is wrong. Unfortunately there are quite a few parameters to
2148 get wrong, so it can be difficult to figure out which one it is.
2150 Here are a couple of possibilities:
2156 Attempting to reopen a database without closing it.
2160 Using the O_WRONLY flag.
2164 =head2 What does "Bareword 'DB_File' not allowed" mean?
2166 You will encounter this particular error message when you have the
2167 C<strict 'subs'> pragma (or the full strict pragma) in your script.
2168 Consider this script:
2174 tie %x, DB_File, "filename" ;
2176 Running it produces the error in question:
2178 Bareword "DB_File" not allowed while "strict subs" in use
2180 To get around the error, place the word C<DB_File> in either single or
2181 double quotes, like this:
2183 tie %x, "DB_File", "filename" ;
2185 Although it might seem like a real pain, it is really worth the effort
2186 of having a C<use strict> in all your scripts.
2190 Articles that are either about B<DB_File> or make use of it.
2196 I<Full-Text Searching in Perl>, Tim Kientzle (tkientzle@ddj.com),
2197 Dr. Dobb's Journal, Issue 295, January 1999, pp 34-41
2203 Moved to the Changes file.
2207 Some older versions of Berkeley DB had problems with fixed length
2208 records using the RECNO file format. This problem has been fixed since
2209 version 1.85 of Berkeley DB.
2211 I am sure there are bugs in the code. If you do find any, or can
2212 suggest any enhancements, I would welcome your comments.
2216 B<DB_File> comes with the standard Perl source distribution. Look in
2217 the directory F<ext/DB_File>. Given the amount of time between releases
2218 of Perl the version that ships with Perl is quite likely to be out of
2219 date, so the most recent version can always be found on CPAN (see
2220 L<perlmod/CPAN> for details), in the directory
2221 F<modules/by-module/DB_File>.
2223 This version of B<DB_File> will work with either version 1.x, 2.x or
2224 3.x of Berkeley DB, but is limited to the functionality provided by
2227 The official web site for Berkeley DB is F<http://www.sleepycat.com>.
2228 All versions of Berkeley DB are available there.
2230 Alternatively, Berkeley DB version 1 is available at your nearest CPAN
2231 archive in F<src/misc/db.1.85.tar.gz>.
2233 If you are running IRIX, then get Berkeley DB version 1 from
2234 F<http://reality.sgi.com/ariel>. It has the patches necessary to
2235 compile properly on IRIX 5.3.
2239 Copyright (c) 1995-2001 Paul Marquess. All rights reserved. This program
2240 is free software; you can redistribute it and/or modify it under the
2241 same terms as Perl itself.
2243 Although B<DB_File> is covered by the Perl license, the library it
2244 makes use of, namely Berkeley DB, is not. Berkeley DB has its own
2245 copyright and its own license. Please take the time to read it.
2247 Here are are few words taken from the Berkeley DB FAQ (at
2248 F<http://www.sleepycat.com>) regarding the license:
2250 Do I have to license DB to use it in Perl scripts?
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.
2259 If you are in any doubt about the license situation, contact either the
2260 Berkeley DB authors or the author of DB_File. See L<"AUTHOR"> for details.
2265 L<perl(1)>, L<dbopen(3)>, L<hash(3)>, L<recno(3)>, L<btree(3)>,
2270 The DB_File interface was written by Paul Marquess
2271 E<lt>Paul.Marquess@btinternet.comE<gt>.
2272 Questions about the DB system itself may be addressed to
2273 E<lt>db@sleepycat.com<gt>.